diff --git a/CHANGELOG.md b/CHANGELOG.md index 0573a6790..30afaa69b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,32 +5,40 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). - -## [2340.01] - 2023-10-05 +## [2348.01] - 2023-11-30 ### Added ### Changed - ### Fixed +## [2346.01] - 2023-11-16 + +### Added +### Changed +### Fixed + + +## [2342.01] - 2023-11-02 + +### Added +- (Usuarios -> Foto) Se muestra la foto del trabajador +### Fixed +- (Usuarios -> Historial) Abre el descriptor del usuario correctamente + + +## [2340.01] - 2023-10-05 + ## [2338.01] - 2023-09-21 ### Added - (Ticket -> Servicios) Se pueden abonar servicios +- (Facturas -> Datos básicos) Muestra valores por defecto +- (Facturas -> Borrado) Notificación al borrar un asiento ya enlazado en Sage ### Changed - (Trabajadores -> Calendario) Icono de check arreglado cuando pulsas un tipo de dia -### Fixed - ## [2336.01] - 2023-09-07 -### Added - -### Changed - -### Fixed - - ## [2334.01] - 2023-08-24 ### Added diff --git a/back/methods/chat/sendCheckingPresence.js b/back/methods/chat/sendCheckingPresence.js index 274ec3a5b..85b66e94b 100644 --- a/back/methods/chat/sendCheckingPresence.js +++ b/back/methods/chat/sendCheckingPresence.js @@ -26,15 +26,14 @@ module.exports = Self => { Self.sendCheckingPresence = async(ctx, recipientId, message) => { if (!recipientId) return false; - const models = Self.app.models; + const userId = ctx.req.accessToken.userId; const sender = await models.VnUser.findById(userId, {fields: ['id']}); const recipient = await models.VnUser.findById(recipientId, null); // Prevent sending messages to yourself if (recipientId == userId) return false; - if (!recipient) throw new Error(`Could not send message "${message}" to worker id ${recipientId} from user ${userId}`); diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js new file mode 100644 index 000000000..f04822697 --- /dev/null +++ b/back/methods/collection/getTickets.js @@ -0,0 +1,135 @@ + +module.exports = Self => { + Self.remoteMethodCtx('getTickets', { + description: 'Make a new collection of tickets', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + description: 'The collection id', + required: true, + http: {source: 'path'} + }, { + arg: 'print', + type: 'boolean', + description: 'True if you want to print' + }], + returns: { + type: ['object'], + root: true + }, + http: { + path: `/:id/getTickets`, + verb: 'POST' + } + }); + + Self.getTickets = async(ctx, id, print, options) => { + const userId = ctx.req.accessToken.userId; + const url = await Self.app.models.Url.getUrl(); + const $t = ctx.req.__; + const myOptions = {}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + myOptions.userId = userId; + + const promises = []; + const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); + const sales = await Self.rawSql(` + SELECT s.ticketFk, + sgd.saleGroupFk, + s.id saleFk, + s.itemFk, + i.longName, + i.size, + ic.color, + o.code origin, + ish.packing, + ish.grouping, + s.isAdded, + s.originalQuantity, + s.quantity saleQuantity, + iss.quantity reservedQuantity, + SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id) accumulatedQuantity, + ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY pickingOrder) currentItemShelving, + COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) totalItemShelving, + sh.code, + IFNULL(p2.code, p.code) parkingCode, + IFNULL(p2.pickingOrder, p.pickingOrder) pickingOrder, + iss.id itemShelvingSaleFk, + iss.isPicked + FROM ticketCollection tc + LEFT JOIN collection c ON c.id = tc.collectionFk + JOIN ticket t ON t.id = tc.ticketFk + JOIN sale s ON s.ticketFk = t.id + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + LEFT JOIN parking p2 ON p2.id = sg.parkingFk + JOIN item i ON i.id = s.itemFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk + LEFT JOIN origin o ON o.id = i.originFk + WHERE tc.collectionFk = ? + GROUP BY ish.id, p.code, p2.code + ORDER BY pickingOrder;`, [id], myOptions); + + if (print) + await Self.rawSql(`CALL vn.collection_printSticker(?, ?)`, [id, null], myOptions); + + const collection = {collectionFk: id, tickets: []}; + if (tickets && tickets.length) { + for (const ticket of tickets) { + const ticketId = ticket.ticketFk; + if (ticket.observaciones != '') { + for (observation of ticket.observaciones.split(' ')) { + if (['#', '@'].includes(observation.charAt(0))) { + promises.push(Self.app.models.Chat.send(ctx, observation, + $t('The ticket is in preparation', { + ticketId: ticketId, + ticketUrl: `${url}ticket/${ticketId}/summary`, + salesPersonId: ticket.salesPersonFk + }))); + } + } + } + if (sales && sales.length) { + const barcodes = await Self.rawSql(` + SELECT s.id saleFk, b.code, c.id + FROM vn.sale s + LEFT JOIN vn.itemBarcode b ON b.itemFk = s.itemFk + LEFT JOIN vn.buy c ON c.itemFk = s.itemFk + LEFT JOIN vn.entry e ON e.id = c.entryFk + LEFT JOIN vn.travel tr ON tr.id = e.travelFk + WHERE s.ticketFk = ? + AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, + [ticketId], myOptions); + ticket.sales = []; + for (const sale of sales) { + if (sale.ticketFk === ticketId) { + sale.Barcodes = []; + if (barcodes && barcodes.length) { + for (const barcode of barcodes) { + if (barcode.saleFk === sale.saleFk) { + for (const prop in barcode) { + if (['id', 'code'].includes(prop) && barcode[prop]) + sale.Barcodes.push(barcode[prop].toString(), '0' + barcode[prop]); + } + } + } + } + ticket.sales.push(sale); + } + } + } + collection.tickets.push(ticket); + } + } + await Promise.all(promises); + return collection; + }; +}; diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js new file mode 100644 index 000000000..e6b9e6a17 --- /dev/null +++ b/back/methods/collection/spec/getTickets.spec.js @@ -0,0 +1,39 @@ +const models = require('vn-loopback/server/server').models; + +describe('collection getTickets()', () => { + let ctx; + beforeAll(async() => { + ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'http://localhost'} + } + }; + }); + + it('should get tickets, sales and barcodes from collection', async() => { + const tx = await models.Collection.beginTransaction({}); + + try { + const options = {transaction: tx}; + const collectionId = 1; + + const collectionTickets = await models.Collection.getTickets(ctx, collectionId, null, options); + + expect(collectionTickets.collectionFk).toEqual(collectionId); + expect(collectionTickets.tickets.length).toEqual(3); + expect(collectionTickets.tickets[0].ticketFk).toEqual(1); + expect(collectionTickets.tickets[1].ticketFk).toEqual(2); + expect(collectionTickets.tickets[2].ticketFk).toEqual(23); + expect(collectionTickets.tickets[0].sales[0].ticketFk).toEqual(1); + expect(collectionTickets.tickets[0].sales[1].ticketFk).toEqual(1); + expect(collectionTickets.tickets[0].sales[2].ticketFk).toEqual(1); + expect(collectionTickets.tickets[0].sales[0].Barcodes.length).toBeTruthy(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); +}); diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index fdc1bce1a..b563f5b19 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -18,6 +18,14 @@ describe('setSaleQuantity()', () => { it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); try { const options = {transaction: tx}; diff --git a/back/methods/url/getByUser.js b/back/methods/url/getByUser.js new file mode 100644 index 000000000..dd4805182 --- /dev/null +++ b/back/methods/url/getByUser.js @@ -0,0 +1,40 @@ +module.exports = function(Self) { + Self.remoteMethod('getByUser', { + description: 'returns the starred modules for the current user', + accessType: 'READ', + accepts: [{ + arg: 'userId', + type: 'number', + description: 'The user id', + required: true, + http: {source: 'path'} + }], + returns: { + type: 'object', + root: true + }, + http: { + path: `/:userId/get-by-user`, + verb: 'GET' + } + }); + + Self.getByUser = async userId => { + const models = Self.app.models; + const appNames = ['hedera']; + const filter = { + fields: ['appName', 'url'], + where: { + appName: {inq: appNames}, + environment: process.env.NODE_ENV ?? 'development', + } + }; + + const isWorker = await models.Account.findById(userId, {fields: ['id']}); + if (!isWorker) + return models.Url.find(filter); + + appNames.push('salix'); + return models.Url.find(filter); + }; +}; diff --git a/back/methods/url/getUrl.js b/back/methods/url/getUrl.js new file mode 100644 index 000000000..f30719b9f --- /dev/null +++ b/back/methods/url/getUrl.js @@ -0,0 +1,30 @@ +module.exports = Self => { + Self.remoteMethod('getUrl', { + description: 'Returns the colling app name', + accessType: 'READ', + accepts: [ + { + arg: 'app', + type: 'string', + required: false + } + ], + returns: { + type: 'object', + root: true + }, + http: { + path: `/getUrl`, + verb: 'get' + } + }); + Self.getUrl = async(appName = 'salix') => { + const {url} = await Self.app.models.Url.findOne({ + where: { + appName, + enviroment: process.env.NODE_ENV || 'development' + } + }); + return url; + }; +}; diff --git a/back/methods/url/specs/getByUser.spec.js b/back/methods/url/specs/getByUser.spec.js new file mode 100644 index 000000000..f6af6ec00 --- /dev/null +++ b/back/methods/url/specs/getByUser.spec.js @@ -0,0 +1,19 @@ +const {models} = require('vn-loopback/server/server'); + +describe('getByUser()', () => { + const worker = 1; + const notWorker = 2; + it(`should return only hedera url if not is worker`, async() => { + const urls = await models.Url.getByUser(notWorker); + + expect(urls.length).toEqual(1); + expect(urls[0].appName).toEqual('hedera'); + }); + + it(`should return more than hedera url`, async() => { + const urls = await models.Url.getByUser(worker); + + expect(urls.length).toBeGreaterThan(1); + expect(urls.find(url => url.appName == 'salix').appName).toEqual('salix'); + }); +}); diff --git a/back/methods/vn-user/update-user.js b/back/methods/vn-user/update-user.js new file mode 100644 index 000000000..ddaae8548 --- /dev/null +++ b/back/methods/vn-user/update-user.js @@ -0,0 +1,39 @@ +module.exports = Self => { + Self.remoteMethodCtx('updateUser', { + description: 'Update user data', + accepts: [ + { + arg: 'id', + type: 'integer', + description: 'The user id', + required: true, + http: {source: 'path'} + }, { + arg: 'name', + type: 'string', + description: 'The user name', + }, { + arg: 'nickname', + type: 'string', + description: 'The user nickname', + }, { + arg: 'email', + type: 'string', + description: 'The user email' + }, { + arg: 'lang', + type: 'string', + description: 'The user lang' + } + ], + http: { + path: `/:id/update-user`, + verb: 'PATCH' + } + }); + + Self.updateUser = async(ctx, id, name, nickname, email, lang) => { + await Self.userSecurity(ctx, id); + await Self.upsertWithWhere({id}, {name, nickname, email, lang}); + }; +}; diff --git a/back/models/chat.js b/back/models/chat.js index a18edbd3f..882db747e 100644 --- a/back/models/chat.js +++ b/back/models/chat.js @@ -7,17 +7,14 @@ module.exports = Self => { Self.observe('before save', async function(ctx) { if (!ctx.isNewInstance) return; - let {message} = ctx.instance; if (!message) return; const parts = message.match(/(?<=\[)[a-zA-Z0-9_\-+!@#$%^&*()={};':"\\|,.<>/?\s]*(?=])/g); if (!parts) return; - const replacedParts = parts.map(part => { return part.replace(/[!$%^&*()={};':"\\,.<>/?]/g, ''); }); - for (const [index, part] of parts.entries()) message = message.replace(part, replacedParts[index]); diff --git a/back/models/collection.js b/back/models/collection.js index a41742ee7..bfa906af6 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -4,4 +4,5 @@ module.exports = Self => { require('../methods/collection/getSectors')(Self); require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); + require('../methods/collection/getTickets')(Self); }; diff --git a/back/models/specs/vn-user.spec.js b/back/models/specs/vn-user.spec.js index 3700b919a..8689a7854 100644 --- a/back/models/specs/vn-user.spec.js +++ b/back/models/specs/vn-user.spec.js @@ -1,4 +1,5 @@ const models = require('vn-loopback/server/server').models; +const ForbiddenError = require('vn-loopback/util/forbiddenError'); describe('loopback model VnUser', () => { it('should return true if the user has the given role', async() => { @@ -12,4 +13,42 @@ describe('loopback model VnUser', () => { expect(result).toBeFalsy(); }); + + describe('userSecurity', () => { + const itManagementId = 115; + const hrId = 37; + const employeeId = 1; + + it('should check if you are the same user', async() => { + const ctx = {options: {accessToken: {userId: employeeId}}}; + await models.VnUser.userSecurity(ctx, employeeId); + }); + + it('should check for higher privileges', async() => { + const ctx = {options: {accessToken: {userId: itManagementId}}}; + await models.VnUser.userSecurity(ctx, employeeId); + }); + + it('should check if you have medium privileges and the user email is not verified', async() => { + const ctx = {options: {accessToken: {userId: hrId}}}; + await models.VnUser.userSecurity(ctx, employeeId); + }); + + it('should throw an error if you have medium privileges and the users email is verified', async() => { + const tx = await models.VnUser.beginTransaction({}); + const ctx = {options: {accessToken: {userId: hrId}}}; + try { + const options = {transaction: tx}; + const userToUpdate = await models.VnUser.findById(1, null, options); + userToUpdate.updateAttribute('emailVerified', 1, options); + + await models.VnUser.userSecurity(ctx, employeeId, options); + await tx.rollback(); + } catch (error) { + await tx.rollback(); + + expect(error).toEqual(new ForbiddenError()); + } + }); + }); }); diff --git a/back/models/url.js b/back/models/url.js new file mode 100644 index 000000000..b603e9eb5 --- /dev/null +++ b/back/models/url.js @@ -0,0 +1,4 @@ +module.exports = Self => { + require('../methods/url/getByUser')(Self); + require('../methods/url/getUrl')(Self); +}; diff --git a/back/models/vn-user.js b/back/models/vn-user.js index cf210b61b..de5bf7b63 100644 --- a/back/models/vn-user.js +++ b/back/models/vn-user.js @@ -1,6 +1,7 @@ const vnModel = require('vn-loopback/common/models/vn-model'); -const LoopBackContext = require('loopback-context'); const {Email} = require('vn-print'); +const ForbiddenError = require('vn-loopback/util/forbiddenError'); +const LoopBackContext = require('loopback-context'); module.exports = function(Self) { vnModel(Self); @@ -12,6 +13,7 @@ module.exports = function(Self) { require('../methods/vn-user/privileges')(Self); require('../methods/vn-user/validate-auth')(Self); require('../methods/vn-user/renew-token')(Self); + require('../methods/vn-user/update-user')(Self); Self.definition.settings.acls = Self.definition.settings.acls.filter(acl => acl.property !== 'create'); @@ -90,11 +92,7 @@ module.exports = function(Self) { }; Self.on('resetPasswordRequest', async function(info) { - const loopBackContext = LoopBackContext.getCurrentContext(); - const httpCtx = {req: loopBackContext.active}; - const httpRequest = httpCtx.req.http.req; - const headers = httpRequest.headers; - const origin = headers.origin; + const url = await Self.app.models.Url.getUrl(); const defaultHash = '/reset-password?access_token=$token$'; const recoverHashes = { @@ -110,7 +108,7 @@ module.exports = function(Self) { const params = { recipient: info.email, lang: user.lang, - url: origin + '/#!' + recoverHash + url: url.slice(0, -1) + recoverHash }; const options = Object.assign({}, info.options); @@ -178,45 +176,75 @@ module.exports = function(Self) { Self.sharedClass._methods.find(method => method.name == 'changePassword').ctor.settings.acls .filter(acl => acl.property != 'changePassword'); - // FIXME: https://redmine.verdnatura.es/issues/5761 - // Self.afterRemote('prototype.patchAttributes', async(ctx, instance) => { - // if (!ctx.args || !ctx.args.data.email) return; + Self.userSecurity = async(ctx, userId, options) => { + const models = Self.app.models; + const accessToken = ctx?.options?.accessToken || LoopBackContext.getCurrentContext().active.accessToken; + const ctxToken = {req: {accessToken}}; - // const loopBackContext = LoopBackContext.getCurrentContext(); - // const httpCtx = {req: loopBackContext.active}; - // const httpRequest = httpCtx.req.http.req; - // const headers = httpRequest.headers; - // const origin = headers.origin; - // const url = origin.split(':'); + if (userId === accessToken.userId) return; - // class Mailer { - // async send(verifyOptions, cb) { - // const params = { - // url: verifyOptions.verifyHref, - // recipient: verifyOptions.to, - // lang: ctx.req.getLocale() - // }; + const myOptions = {}; + if (typeof options == 'object') + Object.assign(myOptions, options); - // const email = new Email('email-verify', params); - // email.send(); + const hasHigherPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'higherPrivileges', myOptions); + if (hasHigherPrivileges) return; - // cb(null, verifyOptions.to); - // } - // } + const hasMediumPrivileges = await models.ACL.checkAccessAcl(ctxToken, 'VnUser', 'mediumPrivileges', myOptions); + const user = await models.VnUser.findById(userId, {fields: ['id', 'emailVerified']}, myOptions); + if (!user.emailVerified && hasMediumPrivileges) return; - // const options = { - // type: 'email', - // to: instance.email, - // from: {}, - // redirect: `${origin}/#!/account/${instance.id}/basic-data?emailConfirmed`, - // template: false, - // mailer: new Mailer, - // host: url[1].split('/')[2], - // port: url[2], - // protocol: url[0], - // user: Self - // }; + throw new ForbiddenError(); + }; - // await instance.verify(options); - // }); + Self.observe('after save', async ctx => { + const instance = ctx?.instance; + const newEmail = instance?.email; + const oldEmail = ctx?.hookState?.oldInstance?.email; + if (!ctx.isNewInstance && (!newEmail || !oldEmail || newEmail == oldEmail)) return; + + const loopBackContext = LoopBackContext.getCurrentContext(); + const httpCtx = {req: loopBackContext.active}; + const httpRequest = httpCtx.req.http.req; + const headers = httpRequest.headers; + const origin = headers.origin; + const url = origin.split(':'); + + const env = process.env.NODE_ENV; + const liliumUrl = await Self.app.models.Url.findOne({ + where: {and: [ + {appName: 'lilium'}, + {environment: env} + ]} + }); + + class Mailer { + async send(verifyOptions, cb) { + const params = { + url: verifyOptions.verifyHref, + recipient: verifyOptions.to + }; + + const email = new Email('email-verify', params); + email.send(); + + cb(null, verifyOptions.to); + } + } + + const options = { + type: 'email', + to: newEmail, + from: {}, + redirect: `${liliumUrl.url}verifyEmail?userId=${instance.id}`, + template: false, + mailer: new Mailer, + host: url[1].split('/')[2], + port: url[2], + protocol: url[0], + user: Self + }; + + await instance.verify(options, ctx.options); + }); }; diff --git a/back/models/vn-user.json b/back/models/vn-user.json index 9131c9134..0f6daff5a 100644 --- a/back/models/vn-user.json +++ b/back/models/vn-user.json @@ -13,19 +13,12 @@ "type": "number", "id": true }, - "name": { + "name": { "type": "string", "required": true }, "username": { - "type": "string", - "mysql": { - "columnName": "name" - } - }, - "password": { - "type": "string", - "required": true + "type": "string" }, "roleFk": { "type": "number", @@ -45,6 +38,9 @@ "email": { "type": "string" }, + "emailVerified": { + "type": "boolean" + }, "created": { "type": "date" }, @@ -84,7 +80,7 @@ "worker": { "type": "hasOne", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" }, "userConfig": { "type": "hasOne", @@ -144,7 +140,8 @@ "image", "hasGrant", "realm", - "email" + "email", + "emailVerified" ] } } diff --git a/db/.archive/224903/00-timeBusiness_calculate.sql b/db/.archive/224903/00-timeBusiness_calculate.sql index ea13c4a8a..6345475dd 100644 --- a/db/.archive/224903/00-timeBusiness_calculate.sql +++ b/db/.archive/224903/00-timeBusiness_calculate.sql @@ -34,7 +34,7 @@ BEGIN isAllowedToWork FROM(SELECT t.dated, b.id businessFk, - w.userFk, + w.id, b.departmentFk, IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,5) ORDER BY j.start ASC SEPARATOR ' - ')) hourStart , IF(j.start = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,5) ORDER BY j.end ASC SEPARATOR ' - ')) hourEnd, @@ -48,14 +48,14 @@ BEGIN FROM time t LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) LEFT JOIN worker w ON w.id = b.workerFk - JOIN tmp.`user` u ON u.userFK = w.userFK + JOIN tmp.`user` u ON u.userFK = w.id LEFT JOIN workCenter wc ON wc.id = b.workcenterFK LEFT JOIN postgresql.calendar_labour_type cl ON cl.calendar_labour_type_id = b.calendarTypeFk LEFT JOIN postgresql.journey j ON j.business_id = b.id AND j.day_id = WEEKDAY(t.dated) + 1 LEFT JOIN postgresql.calendar_employee ce ON ce.businessFk = b.id AND ce.date = t.dated LEFT JOIN absenceType at2 ON at2.id = ce.calendar_state_id WHERE t.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.userFk, t.dated + GROUP BY w.id, t.dated )sub; UPDATE tmp.timeBusinessCalculate t diff --git a/db/changes/231201/00-ACL.sql b/db/.archive/231201/00-ACL.sql similarity index 100% rename from db/changes/231201/00-ACL.sql rename to db/.archive/231201/00-ACL.sql diff --git a/db/changes/231201/00-chatRefactor.sql b/db/.archive/231201/00-chatRefactor.sql similarity index 100% rename from db/changes/231201/00-chatRefactor.sql rename to db/.archive/231201/00-chatRefactor.sql diff --git a/db/changes/231201/00-invoiceInSerial.sql b/db/.archive/231201/00-invoiceInSerial.sql similarity index 100% rename from db/changes/231201/00-invoiceInSerial.sql rename to db/.archive/231201/00-invoiceInSerial.sql diff --git a/db/changes/231201/00-itemType_isFragile.sql b/db/.archive/231201/00-itemType_isFragile.sql similarity index 100% rename from db/changes/231201/00-itemType_isFragile.sql rename to db/.archive/231201/00-itemType_isFragile.sql diff --git a/db/changes/231201/00-mailACL.sql b/db/.archive/231201/00-mailACL.sql similarity index 100% rename from db/changes/231201/00-mailACL.sql rename to db/.archive/231201/00-mailACL.sql diff --git a/db/changes/231201/00-operator.sql b/db/.archive/231201/00-operator.sql similarity index 100% rename from db/changes/231201/00-operator.sql rename to db/.archive/231201/00-operator.sql diff --git a/db/changes/231201/00-supplierAccount_deleteTriggers.sql b/db/.archive/231201/00-supplierAccount_deleteTriggers.sql similarity index 100% rename from db/changes/231201/00-supplierAccount_deleteTriggers.sql rename to db/.archive/231201/00-supplierAccount_deleteTriggers.sql diff --git a/db/changes/231201/00-ticket_getWarnings.sql b/db/.archive/231201/00-ticket_getWarnings.sql similarity index 100% rename from db/changes/231201/00-ticket_getWarnings.sql rename to db/.archive/231201/00-ticket_getWarnings.sql diff --git a/db/changes/231201/00-wagon.sql b/db/.archive/231201/00-wagon.sql similarity index 100% rename from db/changes/231201/00-wagon.sql rename to db/.archive/231201/00-wagon.sql diff --git a/db/changes/231202/00-delivery.sql b/db/.archive/231202/00-delivery.sql similarity index 100% rename from db/changes/231202/00-delivery.sql rename to db/.archive/231202/00-delivery.sql diff --git a/db/changes/231203/00-delivery.sql b/db/.archive/231203/00-delivery.sql similarity index 100% rename from db/changes/231203/00-delivery.sql rename to db/.archive/231203/00-delivery.sql diff --git a/db/changes/231204/00-rollbackDelivery.sql b/db/.archive/231204/00-rollbackDelivery.sql similarity index 100% rename from db/changes/231204/00-rollbackDelivery.sql rename to db/.archive/231204/00-rollbackDelivery.sql diff --git a/db/changes/231205/00-printQueueArgs.sql b/db/.archive/231205/00-printQueueArgs.sql similarity index 100% rename from db/changes/231205/00-printQueueArgs.sql rename to db/.archive/231205/00-printQueueArgs.sql diff --git a/db/changes/231401/00-claimBeginningAfterInsert.sql b/db/.archive/231401/00-claimBeginningAfterInsert.sql similarity index 100% rename from db/changes/231401/00-claimBeginningAfterInsert.sql rename to db/.archive/231401/00-claimBeginningAfterInsert.sql diff --git a/db/changes/231401/00-clientBeforeUpdate.sql b/db/.archive/231401/00-clientBeforeUpdate.sql similarity index 96% rename from db/changes/231401/00-clientBeforeUpdate.sql rename to db/.archive/231401/00-clientBeforeUpdate.sql index 8f9f70dd5..6bae98f61 100644 --- a/db/changes/231401/00-clientBeforeUpdate.sql +++ b/db/.archive/231401/00-clientBeforeUpdate.sql @@ -46,7 +46,7 @@ BEGIN CONCAT('Cliente ', NEW.id), CONCAT('Recibida la documentación: ', vText) FROM worker w - LEFT JOIN account.user u ON w.userFk = u.id AND u.active + LEFT JOIN account.user u ON w.id = u.id AND u.active LEFT JOIN account.account ac ON ac.id = u.id WHERE w.id = NEW.salesPersonFk; END IF; diff --git a/db/changes/231401/00-hotfixDelivery.sql b/db/.archive/231401/00-hotfixDelivery.sql similarity index 100% rename from db/changes/231401/00-hotfixDelivery.sql rename to db/.archive/231401/00-hotfixDelivery.sql diff --git a/db/changes/231401/00-invoiceOutAfterInsert.sql b/db/.archive/231401/00-invoiceOutAfterInsert.sql similarity index 100% rename from db/changes/231401/00-invoiceOutAfterInsert.sql rename to db/.archive/231401/00-invoiceOutAfterInsert.sql diff --git a/db/changes/231401/00-negativeBases.sql b/db/.archive/231401/00-negativeBases.sql similarity index 100% rename from db/changes/231401/00-negativeBases.sql rename to db/.archive/231401/00-negativeBases.sql diff --git a/db/changes/231401/00-workerNotes.sql b/db/.archive/231401/00-workerNotes.sql similarity index 100% rename from db/changes/231401/00-workerNotes.sql rename to db/.archive/231401/00-workerNotes.sql diff --git a/db/changes/231402/00-negativeBases.sql b/db/.archive/231402/00-negativeBases.sql similarity index 100% rename from db/changes/231402/00-negativeBases.sql rename to db/.archive/231402/00-negativeBases.sql diff --git a/db/changes/231801/00-aclClientInforma.sql b/db/.archive/231801/00-aclClientInforma.sql similarity index 100% rename from db/changes/231801/00-aclClientInforma.sql rename to db/.archive/231801/00-aclClientInforma.sql diff --git a/db/changes/231801/00-acl_receiptEmail.sql b/db/.archive/231801/00-acl_receiptEmail.sql similarity index 100% rename from db/changes/231801/00-acl_receiptEmail.sql rename to db/.archive/231801/00-acl_receiptEmail.sql diff --git a/db/changes/231801/00-clientInforma.sql b/db/.archive/231801/00-clientInforma.sql similarity index 100% rename from db/changes/231801/00-clientInforma.sql rename to db/.archive/231801/00-clientInforma.sql diff --git a/db/changes/231801/00-client_setRatingAcl.sql b/db/.archive/231801/00-client_setRatingAcl.sql similarity index 100% rename from db/changes/231801/00-client_setRatingAcl.sql rename to db/.archive/231801/00-client_setRatingAcl.sql diff --git a/db/changes/231801/00-deleteProcs_refund.sql b/db/.archive/231801/00-deleteProcs_refund.sql similarity index 100% rename from db/changes/231801/00-deleteProcs_refund.sql rename to db/.archive/231801/00-deleteProcs_refund.sql diff --git a/db/changes/231801/00-deviceProduction.sql b/db/.archive/231801/00-deviceProduction.sql similarity index 100% rename from db/changes/231801/00-deviceProduction.sql rename to db/.archive/231801/00-deviceProduction.sql diff --git a/db/changes/231801/00-kkearEntryNotes.sql b/db/.archive/231801/00-kkearEntryNotes.sql similarity index 100% rename from db/changes/231801/00-kkearEntryNotes.sql rename to db/.archive/231801/00-kkearEntryNotes.sql diff --git a/db/changes/231801/00-newCompanyI18n.sql b/db/.archive/231801/00-newCompanyI18n.sql similarity index 100% rename from db/changes/231801/00-newCompanyI18n.sql rename to db/.archive/231801/00-newCompanyI18n.sql diff --git a/db/changes/231801/00-newTableWeb.sql b/db/.archive/231801/00-newTableWeb.sql similarity index 100% rename from db/changes/231801/00-newTableWeb.sql rename to db/.archive/231801/00-newTableWeb.sql diff --git a/db/changes/231801/00-observationEmailACL.sql b/db/.archive/231801/00-observationEmailACL.sql similarity index 100% rename from db/changes/231801/00-observationEmailACL.sql rename to db/.archive/231801/00-observationEmailACL.sql diff --git a/db/changes/231801/00-optimiceZoneEstimatedDelivery.sql b/db/.archive/231801/00-optimiceZoneEstimatedDelivery.sql similarity index 100% rename from db/changes/231801/00-optimiceZoneEstimatedDelivery.sql rename to db/.archive/231801/00-optimiceZoneEstimatedDelivery.sql diff --git a/db/changes/231801/00-saleTracking.sql b/db/.archive/231801/00-saleTracking.sql similarity index 100% rename from db/changes/231801/00-saleTracking.sql rename to db/.archive/231801/00-saleTracking.sql diff --git a/db/changes/231801/00-ticketConfig.sql b/db/.archive/231801/00-ticketConfig.sql similarity index 100% rename from db/changes/231801/00-ticketConfig.sql rename to db/.archive/231801/00-ticketConfig.sql diff --git a/db/changes/231801/00-updateIsVies.sql b/db/.archive/231801/00-updateIsVies.sql similarity index 100% rename from db/changes/231801/00-updateIsVies.sql rename to db/.archive/231801/00-updateIsVies.sql diff --git a/db/changes/231801/00-updateisViesClient.sql b/db/.archive/231801/00-updateisViesClient.sql similarity index 100% rename from db/changes/231801/00-updateisViesClient.sql rename to db/.archive/231801/00-updateisViesClient.sql diff --git a/db/changes/231801/00-userAcl.sql b/db/.archive/231801/00-userAcl.sql similarity index 100% rename from db/changes/231801/00-userAcl.sql rename to db/.archive/231801/00-userAcl.sql diff --git a/db/changes/231801/00-userRoleLog.sql b/db/.archive/231801/00-userRoleLog.sql similarity index 100% rename from db/changes/231801/00-userRoleLog.sql rename to db/.archive/231801/00-userRoleLog.sql diff --git a/db/changes/231801/01-viewCompany10L.sql b/db/.archive/231801/01-viewCompany10L.sql similarity index 100% rename from db/changes/231801/01-viewCompany10L.sql rename to db/.archive/231801/01-viewCompany10L.sql diff --git a/db/changes/232001/00-clientWorkerName.sql b/db/.archive/232001/00-clientWorkerName.sql similarity index 100% rename from db/changes/232001/00-clientWorkerName.sql rename to db/.archive/232001/00-clientWorkerName.sql diff --git a/db/changes/232001/00-createWorker.sql b/db/.archive/232001/00-createWorker.sql similarity index 100% rename from db/changes/232001/00-createWorker.sql rename to db/.archive/232001/00-createWorker.sql diff --git a/db/changes/232001/00-invoiceOut_new.sql b/db/.archive/232001/00-invoiceOut_new.sql similarity index 100% rename from db/changes/232001/00-invoiceOut_new.sql rename to db/.archive/232001/00-invoiceOut_new.sql diff --git a/db/changes/232001/00-wagon.sql b/db/.archive/232001/00-wagon.sql similarity index 100% rename from db/changes/232001/00-wagon.sql rename to db/.archive/232001/00-wagon.sql diff --git a/db/changes/232201/00-defaulterView.sql b/db/.archive/232201/00-defaulterView.sql similarity index 100% rename from db/changes/232201/00-defaulterView.sql rename to db/.archive/232201/00-defaulterView.sql diff --git a/db/changes/232201/00-procedurecanAdvance.sql b/db/.archive/232201/00-procedurecanAdvance.sql similarity index 100% rename from db/changes/232201/00-procedurecanAdvance.sql rename to db/.archive/232201/00-procedurecanAdvance.sql diff --git a/db/changes/232201/00-procedurecanbePostponed.sql b/db/.archive/232201/00-procedurecanbePostponed.sql similarity index 100% rename from db/changes/232201/00-procedurecanbePostponed.sql rename to db/.archive/232201/00-procedurecanbePostponed.sql diff --git a/db/changes/232201/00-workerConfigPayMethod.sql b/db/.archive/232201/00-workerConfigPayMethod.sql similarity index 100% rename from db/changes/232201/00-workerConfigPayMethod.sql rename to db/.archive/232201/00-workerConfigPayMethod.sql diff --git a/db/changes/232202/00-procedurecanAdvance.sql b/db/.archive/232202/00-procedurecanAdvance.sql similarity index 100% rename from db/changes/232202/00-procedurecanAdvance.sql rename to db/.archive/232202/00-procedurecanAdvance.sql diff --git a/db/changes/232202/00-procedurecanbePostponed.sql b/db/.archive/232202/00-procedurecanbePostponed.sql similarity index 100% rename from db/changes/232202/00-procedurecanbePostponed.sql rename to db/.archive/232202/00-procedurecanbePostponed.sql diff --git a/db/changes/232401/.gitkeep b/db/.archive/232401/.gitkeep similarity index 100% rename from db/changes/232401/.gitkeep rename to db/.archive/232401/.gitkeep diff --git a/db/changes/232401/00-buyConfig_travelConfig.sql b/db/.archive/232401/00-buyConfig_travelConfig.sql similarity index 100% rename from db/changes/232401/00-buyConfig_travelConfig.sql rename to db/.archive/232401/00-buyConfig_travelConfig.sql diff --git a/db/changes/232401/00-printer.sql b/db/.archive/232401/00-printer.sql similarity index 100% rename from db/changes/232401/00-printer.sql rename to db/.archive/232401/00-printer.sql diff --git a/db/changes/232401/00-ticket_warehouse.sql b/db/.archive/232401/00-ticket_warehouse.sql similarity index 100% rename from db/changes/232401/00-ticket_warehouse.sql rename to db/.archive/232401/00-ticket_warehouse.sql diff --git a/db/changes/232401/00-userPassExpired.sql b/db/.archive/232401/00-userPassExpired.sql similarity index 100% rename from db/changes/232401/00-userPassExpired.sql rename to db/.archive/232401/00-userPassExpired.sql diff --git a/db/changes/232402/00-hotFix_travelConfig.sql b/db/.archive/232402/00-hotFix_travelConfig.sql similarity index 100% rename from db/changes/232402/00-hotFix_travelConfig.sql rename to db/.archive/232402/00-hotFix_travelConfig.sql diff --git a/db/changes/232601/00-aclAccount.sql b/db/.archive/232601/00-aclAccount.sql similarity index 100% rename from db/changes/232601/00-aclAccount.sql rename to db/.archive/232601/00-aclAccount.sql diff --git a/db/changes/232601/00-aclInvoiceTickets.sql b/db/.archive/232601/00-aclInvoiceTickets.sql similarity index 100% rename from db/changes/232601/00-aclInvoiceTickets.sql rename to db/.archive/232601/00-aclInvoiceTickets.sql diff --git a/db/changes/232601/00-aclMailAliasAccount.sql b/db/.archive/232601/00-aclMailAliasAccount.sql similarity index 100% rename from db/changes/232601/00-aclMailAliasAccount.sql rename to db/.archive/232601/00-aclMailAliasAccount.sql diff --git a/db/changes/232601/00-aclMailForward.sql b/db/.archive/232601/00-aclMailForward.sql similarity index 100% rename from db/changes/232601/00-aclMailForward.sql rename to db/.archive/232601/00-aclMailForward.sql diff --git a/db/changes/232601/00-aclRole.sql b/db/.archive/232601/00-aclRole.sql similarity index 100% rename from db/changes/232601/00-aclRole.sql rename to db/.archive/232601/00-aclRole.sql diff --git a/db/changes/232601/00-aclVnUser.sql b/db/.archive/232601/00-aclVnUser.sql similarity index 100% rename from db/changes/232601/00-aclVnUser.sql rename to db/.archive/232601/00-aclVnUser.sql diff --git a/db/changes/232601/00-aclVnUser_renewToken.sql b/db/.archive/232601/00-aclVnUser_renewToken.sql similarity index 100% rename from db/changes/232601/00-aclVnUser_renewToken.sql rename to db/.archive/232601/00-aclVnUser_renewToken.sql diff --git a/db/changes/232601/00-entry_updateComission.sql b/db/.archive/232601/00-entry_updateComission.sql similarity index 100% rename from db/changes/232601/00-entry_updateComission.sql rename to db/.archive/232601/00-entry_updateComission.sql diff --git a/db/changes/232601/00-packingSiteAdvanced.sql b/db/.archive/232601/00-packingSiteAdvanced.sql similarity index 100% rename from db/changes/232601/00-packingSiteAdvanced.sql rename to db/.archive/232601/00-packingSiteAdvanced.sql diff --git a/db/changes/232601/00-salix.sql b/db/.archive/232601/00-salix.sql similarity index 100% rename from db/changes/232601/00-salix.sql rename to db/.archive/232601/00-salix.sql diff --git a/db/changes/232401/00-useSpecificsAcls.sql b/db/.archive/232601/00-useSpecificsAcls.sql similarity index 99% rename from db/changes/232401/00-useSpecificsAcls.sql rename to db/.archive/232601/00-useSpecificsAcls.sql index 0d17ca948..d124786f6 100644 --- a/db/changes/232401/00-useSpecificsAcls.sql +++ b/db/.archive/232601/00-useSpecificsAcls.sql @@ -3,11 +3,11 @@ INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `pri ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'claimManager'), ('Ticket', 'editDiscount', 'WRITE', 'ALLOW', 'ROLE', 'salesPerson'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'salesAssistant'), - ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'deliveryAssistant'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'buyer'), ('Ticket', 'isRoleAdvanced', '*', 'ALLOW', 'ROLE', 'claimManager'), ('Ticket', 'deleteTicketWithPartPrepared', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'), - ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss'), + ('Ticket', 'editZone', 'WRITE', 'ALLOW', 'ROLE', 'deliveryAssistant'), ('State', 'editableStates', 'READ', 'ALLOW', 'ROLE', 'employee'), ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'administrative'), ('State', 'seeEditableStates', 'READ', 'ALLOW', 'ROLE', 'production'), diff --git a/db/changes/232601/01-invoiceOutPdf.sql b/db/.archive/232601/01-invoiceOutPdf.sql similarity index 100% rename from db/changes/232601/01-invoiceOutPdf.sql rename to db/.archive/232601/01-invoiceOutPdf.sql diff --git a/db/changes/232602/01-aclAddAlias.sql b/db/.archive/232602/01-aclAddAlias.sql similarity index 100% rename from db/changes/232602/01-aclAddAlias.sql rename to db/.archive/232602/01-aclAddAlias.sql diff --git a/db/changes/232801/00-authCode.sql b/db/.archive/232801/00-authCode.sql similarity index 100% rename from db/changes/232801/00-authCode.sql rename to db/.archive/232801/00-authCode.sql diff --git a/db/changes/232801/00-client_create.sql b/db/.archive/232801/00-client_create.sql similarity index 100% rename from db/changes/232801/00-client_create.sql rename to db/.archive/232801/00-client_create.sql diff --git a/db/changes/232801/00-client_create2.sql b/db/.archive/232801/00-client_create2.sql similarity index 100% rename from db/changes/232801/00-client_create2.sql rename to db/.archive/232801/00-client_create2.sql diff --git a/db/changes/232801/00-department.sql b/db/.archive/232801/00-department.sql similarity index 100% rename from db/changes/232801/00-department.sql rename to db/.archive/232801/00-department.sql diff --git a/db/changes/232801/00-fix_editCredit.sql b/db/.archive/232801/00-fix_editCredit.sql similarity index 100% rename from db/changes/232801/00-fix_editCredit.sql rename to db/.archive/232801/00-fix_editCredit.sql diff --git a/db/changes/232801/00-user.sql b/db/.archive/232801/00-user.sql similarity index 100% rename from db/changes/232801/00-user.sql rename to db/.archive/232801/00-user.sql diff --git a/db/changes/232802/01-aclWorkerDisable.sql b/db/.archive/232802/01-aclWorkerDisable.sql similarity index 100% rename from db/changes/232802/01-aclWorkerDisable.sql rename to db/.archive/232802/01-aclWorkerDisable.sql diff --git a/db/changes/233801/01-deviceLog_acl.sql b/db/changes/233801/01-deviceLog_acl.sql index ebe3f8ed5..2b646a6a3 100644 --- a/db/changes/233801/01-deviceLog_acl.sql +++ b/db/changes/233801/01-deviceLog_acl.sql @@ -1,6 +1,6 @@ -ALTER TABLE `vn`.`deviceLog` ADD serialNumber varchar(45) DEFAULT NULL NULL; +-- ALTER TABLE `vn`.`deviceLog` ADD serialNumber varchar(45) DEFAULT NULL NULL; -INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) -VALUES( 'DeviceLog', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'); +-- INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) +-- VALUES( 'DeviceLog', 'create', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/233401/.gitkeep b/db/changes/233802/.gitkeep similarity index 100% rename from db/changes/233401/.gitkeep rename to db/changes/233802/.gitkeep diff --git a/db/changes/233802/00-collectionGetTicketsACL.sql b/db/changes/233802/00-collectionGetTicketsACL.sql new file mode 100644 index 000000000..06b584386 --- /dev/null +++ b/db/changes/233802/00-collectionGetTicketsACL.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL`(model, property, accessType, permission, principalType, principalId) + VALUES + ('Collection', 'getTickets', 'WRITE', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/234001/00-aclClient.sql b/db/changes/234001/00-aclClient.sql new file mode 100644 index 000000000..109b3a4fb --- /dev/null +++ b/db/changes/234001/00-aclClient.sql @@ -0,0 +1,42 @@ +-- No encuentro este back +DELETE FROM `salix`.`ACL` WHERE property = 'activeWorkersWithRole'; +DELETE FROM `salix`.`ACL` WHERE model = 'Client' AND property = '*'; + +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','findOne','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','findById','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','find','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','exists','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Client','__get__addresses','READ','ALLOW','ROLE','employee'); + +DELETE FROM `salix`.`ACL` WHERE model = 'Client' AND property = '*' AND accessType IN ( + 'campaignMetricsEmail', + 'campaignMetricsPdf', + 'clientDebtStatementEmail', + 'clientDebtStatementHtml', + 'clientDebtStatementPdf', + 'clientWelcomeEmail', + 'clientWelcomeHtml', + 'consumptionSendQueued', + 'creditRequestEmail', + 'creditRequestHtml', + 'creditRequestPdf', + 'getClientOrSupplierReference', + 'incotermsAuthorizationEmail', + 'incotermsAuthorizationHtml', + 'incotermsAuthorizationPdf', + 'letterDebtorNdEmail', + 'letterDebtorNdHtml', + 'letterDebtorPdf', + 'letterDebtorStEmail', + 'letterDebtorStHtml', + 'printerSetupEmail', + 'printerSetupHtml', + 'sepaCoreEmail', + 'setPassword', + 'updateUser', + 'uploadFile'); diff --git a/db/changes/234001/00-dropUserFk.sql b/db/changes/234001/00-dropUserFk.sql new file mode 100644 index 000000000..d6ce328a8 --- /dev/null +++ b/db/changes/234001/00-dropUserFk.sql @@ -0,0 +1,4 @@ +ALTER TABLE `vn`.`worker` DROP KEY `user_id_UNIQUE`; + +ALTER TABLE `vn`.`worker` DROP COLUMN `userFk`; + diff --git a/db/changes/233801/00-item_setVisibleDiscard.sql b/db/changes/234001/00-item_setVisibleDiscard.sql similarity index 100% rename from db/changes/233801/00-item_setVisibleDiscard.sql rename to db/changes/234001/00-item_setVisibleDiscard.sql diff --git a/db/changes/234001/00-models.sql b/db/changes/234001/00-models.sql new file mode 100644 index 000000000..abf1e3ea5 --- /dev/null +++ b/db/changes/234001/00-models.sql @@ -0,0 +1,11 @@ +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES + ('ExpeditionMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('WorkerMistakeType', '*', 'READ', 'ALLOW', 'ROLE', 'employee'), + ('ExpeditionMistake','*','WRITE','ALLOW','ROLE','employee'), + ('WorkerMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'), + ('MistakesTypes', '*', 'WRITE', 'ALLOW', 'ROLE', 'coolerBoss'), + ('MistakeType','*','READ','ALLOW','ROLE','employee'), + ('MachineWorker', '*', 'READ', 'ALLOW', 'ROLE', 'coolerAssist'), + ('Printer','*','READ','ALLOW','ROLE','employee'), + ('SaleMistake', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/db/changes/233801/00-ticketConfig.sql b/db/changes/234001/00-ticketConfig.sql similarity index 100% rename from db/changes/233801/00-ticketConfig.sql rename to db/changes/234001/00-ticketConfig.sql diff --git a/db/changes/234001/00-timeBusiness_calculate.sql b/db/changes/234001/00-timeBusiness_calculate.sql new file mode 100644 index 000000000..599dba74a --- /dev/null +++ b/db/changes/234001/00-timeBusiness_calculate.sql @@ -0,0 +1,86 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) +BEGIN +/** + * Horas que debe trabajar un empleado según contrato y día. + * @param vDatedFrom workerTimeControl + * @param vDatedTo workerTimeControl + * @table tmp.user(userFk) + * @return tmp.timeBusinessCalculate + */ + DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate + (INDEX (departmentFk)) + SELECT dated, + businessFk, + sub.id userFk, + departmentFk, + hourStart, + hourEnd, + timeTable, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / 3600 timeWorkDecimal, + timeWorkSeconds timeBusinessSeconds, + SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, + timeWorkSeconds / 3600 timeBusinessDecimal, + name type, + permissionRate, + hoursWeek, + discountRate, + isAllowedToWork + FROM(SELECT t.dated, + b.id businessFk, + w.id, + b.departmentFk, + IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5) ORDER BY bs.started ASC SEPARATOR ' - ')) hourStart , + IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) hourEnd, + IF(bs.started = NULL, NULL, GROUP_CONCAT(DISTINCT LEFT(bs.started,5), " - ", LEFT(bs.ended,5) ORDER BY bs.ended ASC SEPARATOR ' - ')) timeTable, + IF(bs.started = NULL, 0, IFNULL(SUM(TIME_TO_SEC(bs.ended)) - SUM(TIME_TO_SEC(bs.started)), 0)) timeWorkSeconds, + at2.name, + at2.permissionRate, + at2.discountRate, + ct.hoursWeek hoursWeek, + at2.isAllowedToWork + FROM time t + LEFT JOIN business b ON t.dated BETWEEN b.started AND IFNULL(b.ended, vDatedTo) + LEFT JOIN worker w ON w.id = b.workerFk + JOIN tmp.`user` u ON u.userFK = w.id + LEFT JOIN workCenter wc ON wc.id = b.workcenterFK + LEFT JOIN calendarType ct ON ct.id = b.calendarTypeFk + LEFT JOIN businessSchedule bs ON bs.businessFk = b.id AND bs.weekday = WEEKDAY(t.dated) + 1 + LEFT JOIN calendar c ON c.businessFk = b.id AND c.dated = t.dated + LEFT JOIN absenceType at2 ON at2.id = c.dayOffTypeFk + WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + GROUP BY w.id, t.dated + )sub; + + UPDATE tmp.timeBusinessCalculate t + LEFT JOIN businessSchedule bs ON bs.businessFk = t.businessFk + SET t.timeWorkSeconds = t.hoursWeek / 5 * 3600, + t.timeWorkSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), + t.timeWorkDecimal = t.hoursWeek / 5, + t.timeBusinessSeconds = t.hoursWeek / 5 * 3600, + t.timeBusinessSexagesimal = SEC_TO_TIME( t.hoursWeek / 5 * 3600), + t.timeBusinessDecimal = t.hoursWeek / 5 + WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND bs.id IS NULL ; + + UPDATE tmp.timeBusinessCalculate t + SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionRate) , + t.timeWorkSexagesimal = SEC_TO_TIME ((t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate)) * 3600), + t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionRate) + WHERE permissionRate <> 0; + + UPDATE tmp.timeBusinessCalculate t + JOIN calendarHolidays ch ON ch.dated = t.dated + JOIN business b ON b.id = t.businessFk + AND b.workcenterFk = ch.workcenterFk + SET t.timeWorkSeconds = 0, + t.timeWorkSexagesimal = 0, + t.timeWorkDecimal = 0, + t.permissionrate = 1, + t.type = 'Festivo' + WHERE t.type IS NULL; +END$$ +DELIMITER ; diff --git a/db/changes/234001/00-updateAfterBusinnesInsert.sql b/db/changes/234001/00-updateAfterBusinnesInsert.sql new file mode 100644 index 000000000..71356db80 --- /dev/null +++ b/db/changes/234001/00-updateAfterBusinnesInsert.sql @@ -0,0 +1,57 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `account`.`account_enable`(vSelf INT) +BEGIN +/** + * Enables a worker's account and sets up email configurations. + */ + UPDATE user + SET active = TRUE + WHERE id = vSelf; + + INSERT IGNORE INTO account + SET id = vSelf; + + INSERT IGNORE INTO mailAliasAccount (mailAlias, account) + SELECT id, vSelf + FROM mailAlias + WHERE alias = 'general'; + + INSERT IGNORE INTO mailForward (account, forwardTo) + SELECT vSelf, email + FROM user + WHERE id = vSelf; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`worker_updateBusiness`(vSelf INT) +BEGIN +/** + * Activates an account and configures its email settings. + * + * @param vSelf account id. + */ + DECLARE vOldBusinessFk INT; + DECLARE vNewBusinessFk INT; + + SELECT businessFk INTO vOldBusinessFk FROM worker WHERE id = vSelf; + + SELECT id INTO vNewBusinessFk + FROM business + WHERE workerFk = vSelf + AND util.VN_CURDATE() BETWEEN started AND IFNULL(ended, util.VN_CURDATE()); + + UPDATE worker + SET businessFk = vNewBusinessFk + WHERE id = vSelf; + + IF NOT (vOldBusinessFk <=> vNewBusinessFk) THEN + IF vNewBusinessFk IS NULL THEN + CALL workerDisable(vSelf); + END IF; + IF vOldBusinessFk IS NULL THEN + CALL account.account_enable(vSelf); + END IF; + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/234001/01-aclAccount.sql b/db/changes/234001/01-aclAccount.sql new file mode 100644 index 000000000..d749b52ab --- /dev/null +++ b/db/changes/234001/01-aclAccount.sql @@ -0,0 +1,10 @@ +DELETE FROM `salix`.`ACL` WHERE model = 'Account' AND property = '*' AND principalId = 'employee'; + +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','findOne','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','findById','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','find','READ','ALLOW','ROLE','employee'); +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Account','exists','READ','ALLOW','ROLE','employee'); diff --git a/db/changes/234001/01-deliveryAssistantACL.sql b/db/changes/234001/01-deliveryAssistantACL.sql new file mode 100644 index 000000000..0f273325f --- /dev/null +++ b/db/changes/234001/01-deliveryAssistantACL.sql @@ -0,0 +1,21 @@ +-- Auto-generated SQL script. Actual values for binary/complex data types may differ - what you see is the default string representation of values. +INSERT INTO `account`.`role` (name, description) + VALUES ('deliveryAssistant','Jefe auxiliar repartos'); + +INSERT INTO `account`.`roleInherit` (role, inheritsFrom) + SELECT (SELECT id FROM account.role r1 WHERE r1.name = 'deliveryAssistant'), ri.inheritsFrom + FROM account.roleInherit ri + JOIN account.role r2 ON r2.id = ri.`role` + WHERE r2.name = 'deliveryBoss'; + +DELETE `account`.`roleInherit` FROM `account`.`roleInherit` + JOIN `account`.`role` r ON `account`.`roleInherit`.role = r.id + WHERE r.name = 'deliveryBoss'; + +INSERT INTO `account`.`roleInherit` (role, inheritsFrom) + SELECT (SELECT id FROM account.role WHERE name = 'deliveryBoss') role, + (SELECT id FROM account.role WHERE name = 'deliveryAssistant') roleInherit; + +UPDATE `salix`.`ACL` + SET principalId='deliveryAssistant' + WHERE principalId='deliveryBoss'; diff --git a/db/changes/234001/01-workerCreate.sql b/db/changes/234001/01-workerCreate.sql new file mode 100644 index 000000000..166c65a26 --- /dev/null +++ b/db/changes/234001/01-workerCreate.sql @@ -0,0 +1,20 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerCreate`( + vFirstname VARCHAR(50), + vLastName VARCHAR(50), + vCode CHAR(3), + vBossFk INT, + vUserFk INT, + vFi VARCHAR(15) , + vBirth DATE +) +BEGIN +/** + * Create new worker + * + */ + INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth) + VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth); +END$$ +DELIMITER ; diff --git a/db/changes/234001/02-roleSync.sql b/db/changes/234001/02-roleSync.sql new file mode 100644 index 000000000..6fe47f691 --- /dev/null +++ b/db/changes/234001/02-roleSync.sql @@ -0,0 +1,2 @@ +-- Locally it fails because it is executed before the fixtures and the roleConfig table is empty +CALL `account`.`role_syncPrivileges`(); diff --git a/modules/claim/front/development/style.scss b/db/changes/234002/.gitkeep similarity index 100% rename from modules/claim/front/development/style.scss rename to db/changes/234002/.gitkeep diff --git a/db/changes/234002/01-itemShelvingSale.sql b/db/changes/234002/01-itemShelvingSale.sql new file mode 100644 index 000000000..817c6317a --- /dev/null +++ b/db/changes/234002/01-itemShelvingSale.sql @@ -0,0 +1,291 @@ +ALTER TABLE `vn`.`itemShelvingSale` DROP COLUMN IF EXISTS isPicked; + +ALTER TABLE`vn`.`itemShelvingSale` + ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; + +ALTER TABLE `vn`.`productionConfig` DROP COLUMN IF EXISTS orderMode; + +ALTER TABLE `vn`.`productionConfig` + ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveByCollection`( + vCollectionFk INT(11) +) +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT s.id saleFk, NULL userFk + FROM ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN ( + SELECT DISTINCT saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.isChecked + AND s.semaphore = 1)st ON st.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + AND st.saleFk IS NULL + AND NOT s.isPicked; + + CALL itemShelvingSale_reserve(); +END$$ +DELIMITER ; + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en vn.itemShelvingSale y vn.sale.isPicked en caso necesario. + * Si la reserva de la ubicación es fallida, se regulariza la situación + * + * @param vItemShelvingSaleFk Id itemShelvingSaleFK + * @param vQuantity Cantidad real que se ha cogido de la ubicación + * @param vIsItemShelvingSaleEmpty determina si ka ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vCursorSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vUserFk INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + DECLARE vSales CURSOR FOR + SELECT iss.saleFk, iss.userFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND s.itemFk = vItemFk + AND NOT iss.isPicked; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Booking completed'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk + INTO vItemFk, vSaleFk, vItemShelvingFk + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + UPDATE itemShelving + SET visible = IF(vIsItemShelvingSaleEmpty, 0, GREATEST(0,visible - vQuantity)) + WHERE id = vItemShelvingFk; + + IF vIsItemShelvingSaleEmpty THEN + OPEN vSales; +l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vCursorSaleFk, vUserFk; + IF vDone THEN + LEAVE l; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk, userFk)) + ENGINE = MEMORY + SELECT vCursorSaleFk, vUserFk; + + CALL itemShelvingSale_reserveWhitUser(); + DROP TEMPORARY TABLE tmp.sale; + + END LOOP; + CLOSE vSales; + + DELETE iss + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND s.itemFk = vItemFk + AND NOT iss.isPicked; + END IF; + + SELECT SUM(quantity) INTO vRemainingQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk + AND NOT isPicked; + + IF vRemainingQuantity THEN + CALL itemShelvingSale_reserveBySale (vSaleFk, vRemainingQuantity, NULL); + + SELECT SUM(quantity) INTO vRemainingQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk + AND NOT isPicked; + + IF NOT vRemainingQuantity <=> 0 THEN + SELECT SUM(iss.quantity) + INTO vReservedQuantity + FROM itemShelvingSale iss + WHERE iss.saleFk = vSaleFk; + + CALL saleTracking_new( + vSaleFk, + TRUE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vReservedQuantity + WHERE s.id = vSaleFk ; + END IF; + END IF; +END$$ +DELIMITER ; + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserve`() +BEGIN +/** + * Reserva cantidades con ubicaciones para un conjunto de sales del mismo wareHouse + * + * @table tmp.sale(saleFk, userFk) + */ + DECLARE vCalcFk INT; + DECLARE vWarehouseFk INT; + DECLARE vCurrentYear INT DEFAULT YEAR(util.VN_NOW()); + DECLARE vLastPickingOrder INT; + + SELECT t.warehouseFk, MAX(p.pickingOrder) + INTO vWarehouseFk, vLastPickingOrder + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN tmp.sale ts ON ts.saleFk = s.id + LEFT JOIN itemShelvingSale iss ON iss.saleFk = ts.saleFk + LEFT JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + LEFT JOIN shelving sh ON sh.code = ish.shelvingFk + LEFT JOIN parking p ON p.id = sh.parkingFk + WHERE t.warehouseFk IS NOT NULL; + + IF vWarehouseFk IS NULL THEN + CALL util.throw('Warehouse not set'); + END IF; + + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); + + SET @outstanding = 0; + SET @oldsaleFk = 0; + + CREATE OR REPLACE TEMPORARY TABLE tSalePlacementQuantity + (INDEX(saleFk)) + ENGINE = MEMORY + SELECT saleFk, userFk, quantityToReserve, itemShelvingFk + FROM( SELECT saleFk, + sub.userFk, + itemShelvingFk , + IF(saleFk <> @oldsaleFk, @outstanding := quantity, @outstanding), + @qtr := LEAST(@outstanding, available) quantityToReserve, + @outStanding := @outStanding - @qtr, + @oldsaleFk := saleFk + FROM( + SELECT ts.saleFk, + ts.userFk, + s.quantity, + ish.id itemShelvingFk, + ish.visible - IFNULL(ishr.reservedQuantity, 0) available + FROM tmp.sale ts + JOIN sale s ON s.id = ts.saleFk + JOIN itemShelving ish ON ish.itemFk = s.itemFk + LEFT JOIN ( + SELECT itemShelvingFk, SUM(quantity) reservedQuantity + FROM itemShelvingSale + WHERE NOT isPicked + GROUP BY itemShelvingFk) ishr ON ishr.itemShelvingFk = ish.id + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON p.id = sh.parkingFk + JOIN sector sc ON sc.id = p.sectorFk + JOIN warehouse w ON w.id = sc.warehouseFk + JOIN productionConfig pc + WHERE w.id = vWarehouseFk + AND NOT sc.isHideForPickers + ORDER BY + s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.visible >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created) + )sub + )sub2 + WHERE quantityToReserve > 0; + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT itemShelvingFk, + saleFk, + quantityToReserve, + IFNULL(userFk, getUser()) + FROM tSalePlacementQuantity spl; + + DROP TEMPORARY TABLE tmp.sale; +END$$ +DELIMITER ; + + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserveBySale`( + vSelf INT , + vQuantity INT, + vUserFk INT +) +BEGIN +/** + * Reserva cantida y ubicación para una saleFk + * + * @param vSelf Identificador de la venta + * @param vQuantity Cantidad a reservar + * @param vUserFk Id de usuario que realiza la reserva + */ + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + ENGINE = MEMORY + SELECT vSelf saleFk, vUserFk userFk; + + CALL itemShelvingSale_reserve(); +END$$ +DELIMITER ; + + + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_AFTER_INSERT` + AFTER INSERT ON `itemShelvingSale` + FOR EACH ROW +BEGIN + + UPDATE vn.sale + SET isPicked = TRUE + WHERE id = NEW.saleFk; + +END$$ +DELIMITER ; diff --git a/db/changes/234003/00-ticket_canAdvance_zone.sql b/db/changes/234003/00-ticket_canAdvance_zone.sql new file mode 100644 index 000000000..ee07ce978 --- /dev/null +++ b/db/changes/234003/00-ticket_canAdvance_zone.sql @@ -0,0 +1,133 @@ +DELIMITER $$ +$$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_canAdvance`(vDateFuture DATE, vDateToAdvance DATE, vWarehouseFk INT) +BEGIN +/** + * Devuelve los tickets y la cantidad de lineas de venta que se pueden adelantar. + * + * @param vDateFuture Fecha de los tickets que se quieren adelantar. + * @param vDateToAdvance Fecha a cuando se quiere adelantar. + * @param vWarehouseFk Almacén + */ + DECLARE vDateInventory DATE; + + SELECT inventoried INTO vDateInventory FROM config; + + DROP TEMPORARY TABLE IF EXISTS tmp.stock; + CREATE TEMPORARY TABLE tmp.stock + (itemFk INT PRIMARY KEY, + amount INT) + ENGINE = MEMORY; + + INSERT INTO tmp.stock(itemFk, amount) + SELECT itemFk, SUM(quantity) amount FROM + ( + SELECT itemFk, quantity + FROM itemTicketOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE landed >= vDateInventory + AND landed < vDateFuture + AND isVirtualStock = FALSE + AND warehouseInFk = vWarehouseFk + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE shipped >= vDateInventory + AND shipped < vDateFuture + AND warehouseOutFk = vWarehouseFk + ) t + GROUP BY itemFk HAVING amount != 0; + + CREATE OR REPLACE TEMPORARY TABLE tmp.filter + (INDEX (id)) + SELECT + origin.ticketFk futureId, + dest.ticketFk id, + dest.state, + origin.futureState, + origin.futureIpt, + dest.ipt, + origin.workerFk, + origin.futureLiters, + origin.futureLines, + dest.shipped, + origin.shipped futureShipped, + dest.totalWithVat, + origin.totalWithVat futureTotalWithVat, + dest.agency, + origin.futureAgency, + dest.lines, + dest.liters, + origin.futureLines - origin.hasStock AS notMovableLines, + (origin.futureLines = origin.hasStock) AS isFullMovable, + origin.futureZoneFk, + origin.futureZoneName, + origin.classColor futureClassColor, + dest.classColor + FROM ( + SELECT + s.ticketFk, + c.salesPersonFk workerFk, + t.shipped, + t.totalWithVat, + st.name futureState, + t.addressFk, + am.name futureAgency, + count(s.id) futureLines, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) futureIpt, + CAST(SUM(litros) AS DECIMAL(10,0)) futureLiters, + SUM((s.quantity <= IFNULL(st.amount,0))) hasStock, + z.id futureZoneFk, + z.name futureZoneName, + st.classColor + FROM ticket t + JOIN client c ON c.id = t.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + JOIN zone z ON t.zoneFk = z.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + LEFT JOIN tmp.stock st ON st.itemFk = i.id + WHERE t.shipped BETWEEN vDateFuture AND util.dayend(vDateFuture) + AND t.warehouseFk = vWarehouseFk + GROUP BY t.id + ) origin + JOIN ( + SELECT + t.id ticketFk, + t.addressFk, + st.name state, + GROUP_CONCAT(DISTINCT ipt.code ORDER BY ipt.code) ipt, + t.shipped, + t.totalWithVat, + am.name agency, + CAST(SUM(litros) AS DECIMAL(10,0)) liters, + CAST(COUNT(*) AS DECIMAL(10,0)) `lines`, + st.classColor + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN saleVolume sv ON sv.saleFk = s.id + JOIN item i ON i.id = s.itemFk + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state st ON st.id = ts.stateFk + JOIN agencyMode am ON t.agencyModeFk = am.id + LEFT JOIN itemPackingType ipt ON ipt.code = i.itemPackingTypeFk + WHERE t.shipped BETWEEN vDateToAdvance AND util.dayend(vDateToAdvance) + AND t.warehouseFk = vWarehouseFk + AND st.order <= 5 + GROUP BY t.id + ) dest ON dest.addressFk = origin.addressFk + WHERE origin.hasStock != 0; + + DROP TEMPORARY TABLE tmp.stock; +END$$ +DELIMITER ; + diff --git a/db/changes/234004/.gitkeep b/db/changes/234004/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234004/00-workerTimeControl.sql b/db/changes/234004/00-workerTimeControl.sql new file mode 100644 index 000000000..8f6263533 --- /dev/null +++ b/db/changes/234004/00-workerTimeControl.sql @@ -0,0 +1,41 @@ +UPDATE `vn`.`workerTimeControlConfig` + SET `timeToBreakTime` = 18000; + +ALTER TABLE `vn`.`workerTimeControlConfig` + DROP COLUMN IF EXISTS `maxTimeToBreak`; +ALTER TABLE `vn`.`workerTimeControlConfig` + ADD COLUMN maxTimeToBreak INT DEFAULT 3600 NULL; + +ALTER TABLE `vn`.`workerTimeControlConfig` + DROP COLUMN IF EXISTS `maxWorkShortCycle`; + +ALTER TABLE `vn`.`workerTimeControlConfig` + ADD COLUMN `maxWorkShortCycle` INT(10) UNSIGNED DEFAULT 561600 + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal corto'; + +ALTER TABLE `vn`.`workerTimeControlConfig` + DROP COLUMN IF EXISTS `maxWorkLongCycle`; + +ALTER TABLE `vn`.`workerTimeControlConfig` + ADD COLUMN `maxWorkLongCycle` INT(10) UNSIGNED DEFAULT 950400 + COMMENT 'Máximo tiempo que un trabajador puede estar trabajando con el que adquirirá el derecho a un descanso semanal largo'; + +CREATE TABLE IF NOT EXISTS `vn`.`workerTimeControlError` ( + `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT, + `code` char(35) NOT NULL, + `description` varchar(255) NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `code` (`code`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE INTO `vn`.`workerTimeControlError` (`code`, `description`) + VALUES + ('IS_NOT_ALLOWED_FUTURE', 'No se permite fichar a futuro'), + ('INACTIVE_BUSINESS', 'No hay un contrato en vigor'), + ('IS_NOT_ALLOWED_WORK', 'No está permitido trabajar'), + ('ODD_WORKERTIMECONTROL', 'Fichadas impares'), + ('DAY_MAX_TIME', 'Superado el tiempo máximo entre entrada y salida'), + ('BREAK_DAY', 'Descanso diario'), + ('BREAK_WEEK', 'Descanso semanal'), + ('WRONG_DIRECTION', 'Dirección incorrecta'), + ('UNDEFINED_ERROR', 'Error sin definir'); \ No newline at end of file diff --git a/db/changes/234004/01-timeControl_calculate.sql b/db/changes/234004/01-timeControl_calculate.sql new file mode 100644 index 000000000..93d88c047 --- /dev/null +++ b/db/changes/234004/01-timeControl_calculate.sql @@ -0,0 +1,194 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`timeControl_calculate`( + vDatedFrom DATETIME, + vDatedTo DATETIME) +BEGIN +/* + * Agrupa por trabajador y día, el tiempo de trabajo y descanso retribuido(si tiene). + * Los registros horarios incorrectos (tmp.timeControlError) no se considerarán. + * Si un trabajador ha trabajado más de un cierto umbral de tiempo (vTimeToBreakTime) + * y no ha tenido descansos que superen un parámetro determinado(vMaxTimeToBreak), + * se le añadirá un tiempo de descanso (vBreakTime) a sus horas trabajadas. + * El tiempo de descanso solo se añade si el trabajador realmente disfrutó del descanso. + * Si disfrutó de menos tiempo de descanso, solo se añade el tiempo que disfrutó. + * + * @param vDatedFrom + * @param vDatedTo + * + * @return tmp.timeControlCalculate + * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) + */ + DECLARE vHourSeconds INTEGER; + DECLARE vDatedFromYesterday DATETIME; + DECLARE vDatedToTomorrow DATETIME; + DECLARE vTimeToBreakTime INT; + DECLARE vBreakTime INT; + DECLARE vMaxTimeToBreak INT; + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + INTO vDatedFromYesterday, vDatedToTomorrow; + + SELECT timeToBreakTime, breakTime, maxTimeToBreak, TIME_TO_SEC('01:00:00') + INTO vTimeToBreakTime, vBreakTime, vMaxTimeToBreak, vHourSeconds + FROM workerTimeControlConfig + LIMIT 1; + + CALL timeControl_getError(vDatedFromYesterday, vDatedToTomorrow); + + CREATE OR REPLACE TEMPORARY TABLE tmp.workerTimeControl + (INDEX(userFk, timed), INDEX(timed), INDEX(direction)) + ENGINE = MEMORY + SELECT wtc.userFk, + wtc.timed, + DATE(wtc.timed) dated, + wtc.direction, + TRUE isReal + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN ( + SELECT wtc.userFk, MIN(wtc.timed) firstIn + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND wtc.direction = 'in' + AND tce.id IS NULL + GROUP BY userFk + ) fi ON wtc.userFk = fi.userFk + LEFT JOIN ( + SELECT wtc.userFk, MAX(wtc.timed) lastOut + FROM workerTimeControl wtc + JOIN tmp.`user` u ON u.userFk = wtc.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND wtc.direction = 'out' + AND tce.id IS NULL + GROUP BY userFk + ) lo ON wtc.userFk = lo.userFk + LEFT JOIN tmp.timeControlError tce ON tce.id = wtc.id + WHERE wtc.timed BETWEEN fi.firstIn AND lo.lastOut + AND tce.id IS NULL + ORDER BY wtc.userFk, wtc.timed; + + CREATE OR REPLACE TEMPORARY TABLE tmp.wtcToinsert + (INDEX(timed)) + ENGINE = MEMORY + WITH wtc AS( + SELECT timed, + userFk, + dated, + direction, + LEAD(dated) OVER + (PARTITION BY userFk, dated ORDER BY timed) nextDay, + LEAD(userFk) OVER + (PARTITION BY userFk ORDER BY timed) nextUserFk, + ROW_NUMBER() OVER (ORDER BY userFk, timed) MOD 2 isOdd + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + ORDER BY userFk, timed + ), wtcToinsert AS( + SELECT userFk, + dated, + IF(userFk = nextUserFk + AND nextDay IS NULL + AND isOdd + AND direction <> 'out', TRUE, FALSE) outNextDay, + IF(userFk = nextUserFk + AND nextDay IS NULL + AND NOT isOdd + AND direction <> 'out', TRUE, FALSE) outNextDayWhitBreak + FROM wtc + HAVING outNextDay OR outNextDayWhitBreak + )SELECT userFk, util.dayEnd(dated) timed, 'out' direction + FROM wtcToinsert + WHERE outNextDay + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY, 'in' + FROM wtcToinsert + WHERE outNextDay + UNION ALL + SELECT userFk, util.dayEnd(dated) - INTERVAL 1 SECOND, 'middle' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, util.dayEnd(dated), 'out' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY, 'in' + FROM wtcToinsert + WHERE outNextDayWhitBreak + UNION ALL + SELECT userFk, dated + INTERVAL 1 DAY + INTERVAL 1 SECOND, 'middle' + FROM wtcToinsert + WHERE outNextDayWhitBreak; + + INSERT INTO tmp.workerTimeControl (userFk, timed, dated, direction, isReal) + SELECT userFk, timed, DATE(timed), direction, FALSE + FROM tmp.wtcToinsert; + + SET @accumulatedForBreakTime = 0; + SET @oldrealDay = NULL; + CREATE OR REPLACE TEMPORARY TABLE tmp.timeControlCalculate + WITH workerTimed AS ( + SELECT + userFk, + dated, + timed, + (direction ='in' AND isReal) breakPoint, + SUM(CASE WHEN (direction ='in' AND isReal) THEN TRUE ELSE FALSE END) + OVER (ORDER BY userFk, timed) AS realDay, + TIMESTAMPDIFF(SECOND, LAG(timed) + OVER (PARTITION BY userFk, dated ORDER BY timed), timed) gapTime, + ROW_NUMBER() + OVER (PARTITION BY userFk, dated ORDER BY timed) MOD 2 isOdd + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + ), accumulated AS ( + SELECT SUM(IF(isOdd, 0, gapTime)) + OVER (PARTITION BY userFk,dated ORDER BY userFk,timed) accumulatedWorkTime, + SUM(IF(NOT isOdd OR breakPoint, 0, IFNULL(gapTime, 0))) + OVER (PARTITION BY realDay ORDER BY realDay,timed) accumulatedBreakTime, + IF(realDay <> @oldrealDay OR (isOdd AND gapTime >= vMaxTimeToBreak), + @accumulatedForBreakTime := 0, + @accumulatedForBreakTime := @accumulatedForBreakTime + + IF(isOdd, 0, gapTime )) accumulatedForBreakTime, + @oldrealDay := realDay, + userFk, + dated, + realDay + FROM workerTimed + ), totalWorked AS ( + SELECT userFk, + dated, + MAX(accumulatedWorkTime) + + IF(MAX(accumulatedForBreakTime) >= vTimeToBreakTime, + LEAST(vBreakTime, MAX(accumulatedBreakTime)), + 0) timeWorkSeconds + FROM accumulated + GROUP BY userFk, dated + )SELECT tw.userFk, + tw.dated, + timeWorkSeconds, + SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, + timeWorkSeconds / vHourSeconds timeWorkDecimal, + sub.tableTimed + FROM totalWorked tw + JOIN ( + SELECT userFk, + dated, + GROUP_CONCAT(DATE_FORMAT(timed, "%H:%i") ORDER BY timed ASC + SEPARATOR ' - ')tableTimed + FROM tmp.workerTimeControl + WHERE timed BETWEEN vDatedFromYesterday AND vDatedToTomorrow + AND isReal + GROUP BY userFk, dated + )sub ON sub.dated = tw.dated + AND sub.userFk = tw.userFk + WHERE tw.dated BETWEEN vDatedFrom AND vDatedTo; + + DROP TEMPORARY TABLE tmp.timeControlError; + DROP TEMPORARY TABLE tmp.wtcToinsert; + DROP TEMPORARY TABLE tmp.workerTimeControl; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/234004/02-workerTimeControl_clockIn.sql b/db/changes/234004/02-workerTimeControl_clockIn.sql new file mode 100644 index 000000000..69091e51c --- /dev/null +++ b/db/changes/234004/02-workerTimeControl_clockIn.sql @@ -0,0 +1,286 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`workerTimeControl_clockIn`( + vWorkerFk INT, + vTimed DATETIME, + vDirection VARCHAR(10) +) +BEGIN +/** + * Verifica si el empleado puede fichar + * @param vWorkerFk Identificador del trabajador + * @param vTimed valor de la fichada, IF vTimed IS NULL vTimed = NOW + * @param vDirection solo se pueden pasa los valores del campo + * workerTimeControl.direction ENUM('in', 'out', 'middle') + * @return Si todo es correcto, retorna el número de id la tabla workerTimeControl. + * Si hay algún problema, devuelve el mesaje que se debe mostrar al usuario + * Solo retorna el primer problema, en caso de no ocurrir ningún error se añadirá + * fichada a la tabla vn.workerTimeControl + */ + + DECLARE vLastIn DATETIME; + DECLARE vLastOut DATETIME; + DECLARE vNextIn DATETIME; + DECLARE vNextOut DATETIME; + DECLARE vNextDirection ENUM('in', 'out'); + DECLARE vLastDirection ENUM('in', 'out'); + DECLARE vDayMaxTime INTEGER; + DECLARE vDayBreak INT; + DECLARE vShortWeekBreak INT; + DECLARE vLongWeekBreak INT; + DECLARE vWeekScope INT; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vIsError BOOLEAN DEFAULT FALSE; + DECLARE vErrorMessage VARCHAR(255) DEFAULT NULL; + DECLARE vErrorCode VARCHAR(50); + DECLARE vDated DATE; + DECLARE vIsAllowedToWork VARCHAR(50); + DECLARE vIsManual BOOLEAN DEFAULT TRUE; + DECLARE vMaxWorkShortCycle INT; + DECLARE vMaxWorkLongCycle INT; + + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + + SELECT CONCAT(u.name, '@verdnatura.es'), + CONCAT(w.firstName, ' ', w.lastName) + INTO vMailTo, vUserName + FROM account.user u + JOIN worker w ON w.bossFk = u.id + WHERE w.id = vWorkerFk; + + SELECT `description` INTO vErrorMessage + FROM workerTimeControlError + WHERE `code` = vErrorCode; + + IF vErrorMessage IS NULL THEN + SET vErrorMessage = 'Error sin definir'; + END IF; + + SELECT vErrorMessage `error`; + SELECT CONCAT(vUserName, + ' no ha podido fichar por el siguiente problema: ', + vErrorMessage) + INTO vErrorMessage; + + CALL mail_insert( vMailTo, vMailTo, 'Error al fichar', vErrorMessage); + END; + + IF (vTimed IS NULL) THEN + SET vTimed = util.VN_NOW(); + SET vIsManual = FALSE; + END IF; + + SET vDated = DATE(vTimed); + + SELECT IF(pc.name = 'Conductor +3500kg', + wc.dayBreakDriver, + wc.dayBreak), + wc.shortWeekBreak, + wc.longWeekBreak, + wc.weekScope, + wc.dayMaxTime, + wc.maxWorkShortCycle, + wc.maxWorkLongCycle + INTO vDayBreak, + vShortWeekBreak, + vLongWeekBreak, + vWeekScope, + vDayMaxTime, + vMaxWorkShortCycle, + vMaxWorkLongCycle + FROM business b + JOIN professionalCategory pc + ON pc.id = b.workerBusinessProfessionalCategoryFk + JOIN workerTimeControlConfig wc + WHERE b.workerFk = vWorkerFk + AND vDated BETWEEN b.started AND IFNULL(b.ended, vDated); + + -- CONTRATO EN VIGOR + IF vDayBreak IS NULL THEN + SET vErrorCode = 'INACTIVE_BUSINESS'; + CALL util.throw(vErrorCode); + END IF; + + -- FICHADAS A FUTURO + IF vTimed > util.VN_NOW() + INTERVAL 1 MINUTE THEN + SET vErrorCode = 'IS_NOT_ALLOWED_FUTURE'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICAR SI ESTÁ PERMITIDO TRABAJAR + CALL timeBusiness_calculateByWorker(vWorkerFk, vDated, vDated); + SELECT isAllowedToWork INTO vIsAllowedToWork + FROM tmp.timeBusinessCalculate; + DROP TEMPORARY TABLE tmp.timeBusinessCalculate; + + IF NOT vIsAllowedToWork THEN + SET vErrorCode = 'IS_NOT_ALLOWED_WORK'; + CALL util.throw(vErrorCode); + END IF; + + -- DIRECCION CORRECTA + CALL workerTimeControl_direction(vWorkerFk, vTimed); + IF (SELECT + IF(IF(option1 IN ('inMiddle', 'outMiddle'), + 'middle', + option1) <> vDirection + AND IF(option2 IN ('inMiddle', 'outMiddle'), + 'middle', + IFNULL(option2, '')) <> vDirection, + TRUE , + FALSE) + FROM tmp.workerTimeControlDirection + ) THEN + SET vIsError = TRUE; + END IF; + + DROP TEMPORARY TABLE tmp.workerTimeControlDirection; + IF vIsError THEN + SET vErrorCode = 'WRONG_DIRECTION'; + CALL util.throw(vErrorCode); + END IF; + + -- FICHADAS IMPARES + SELECT timed INTO vLastIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + IF (SELECT IF(vDirection = 'in', + MOD(COUNT(*), 2) , + IF (vDirection = 'out', NOT MOD(COUNT(*), 2), FALSE)) + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND timed BETWEEN vLastIn AND vTimed + ) THEN + SET vErrorCode = 'ODD_WORKERTIMECONTROL'; + CALL util.throw(vErrorCode); + END IF; + + -- DESCANSO DIARIO + SELECT timed INTO vLastOut + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'out' + AND timed < vTimed + ORDER BY timed DESC + LIMIT 1; + + SELECT timed INTO vNextIn + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'in' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + CASE vDirection + WHEN 'in' THEN + IF UNIX_TIMESTAMP(vTimed) - UNIX_TIMESTAMP(vLastOut) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + WHEN 'out' THEN + IF UNIX_TIMESTAMP(vNextIn) - UNIX_TIMESTAMP(vTimed) <= vDayBreak THEN + SET vIsError = TRUE; + END IF; + ELSE BEGIN END; + END CASE; + + IF vIsError THEN + SET vErrorCode = 'BREAK_DAY'; + CALL util.throw(vErrorCode); + END IF; + + + + IF (vDirection IN('in', 'out')) THEN + -- VERIFICA MAXIMO TIEMPO DESDE ENTRADA HASTA LA SALIDA + + SELECT timed INTO vNextOut + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction = 'out' + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vNextDirection + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN('in','out') + AND timed > vTimed + ORDER BY timed ASC + LIMIT 1; + + SELECT direction INTO vLastDirection + FROM workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN('in', 'out') + AND timed < vTimed + ORDER BY timed ASC + LIMIT 1; + + IF (vDirection ='in' + AND vNextDirection = 'out' + AND UNIX_TIMESTAMP(vNextOut) - UNIX_TIMESTAMP(vTimed) > vDayMaxTime) OR + (vDirection ='out' + AND vLastDirection = 'in' + AND UNIX_TIMESTAMP(vTimed) -UNIX_TIMESTAMP(vLastIn) > vDayMaxTime) THEN + SET vErrorCode = 'DAY_MAX_TIME'; + CALL util.throw(vErrorCode); + END IF; + + -- VERIFICA DESCANSO SEMANAL + + WITH wtc AS( + (SELECT timed + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk + AND direction IN ('in', 'out') + AND timed BETWEEN vTimed - INTERVAL (vWeekScope * 2) SECOND + AND vTimed + INTERVAL (vWeekScope * 2) SECOND ) + UNION + (SELECT vTimed) + ), wtcGap AS( + SELECT timed, + TIMESTAMPDIFF(SECOND, LAG(timed) OVER (ORDER BY timed), timed) gap + FROM wtc + ORDER BY timed + ), wtcBreak AS( + SELECT timed, + IF(IFNULL(gap, 0) > vShortWeekBreak, TRUE, FALSE) hasShortBreak, + IF(IFNULL(gap, 0) > vLongWeekBreak, TRUE, FALSE) hasLongBreak + FROM wtcGap + ORDER BY timed + ), wtcBreakCounter AS( + SELECT timed, + SUM(hasShortBreak) OVER (ORDER BY timed) breakCounter , + LEAD(hasLongBreak) OVER (ORDER BY timed) nextHasLongBreak + FROM wtcBreak + )SELECT TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed)) > vMaxWorkLongCycle OR + (TIMESTAMPDIFF(SECOND, MIN(timed), MAX(timed))> vMaxWorkShortCycle + AND NOT SUM(IFNULL(nextHasLongBreak, 1))) + hasError INTO vIsError + FROM wtcBreakCounter + GROUP BY breakCounter + HAVING hasError + LIMIT 1; + + IF vIsError THEN + SET vErrorCode = 'BREAK_WEEK'; + CALL util.throw(vErrorCode); + END IF; + END IF; + + -- SE PERMITE FICHAR + INSERT INTO workerTimeControl(userFk, timed, direction, `manual`) + VALUES(vWorkerFk, vTimed, vDirection, vIsManual); + + SELECT LAST_INSERT_ID() id; + +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/234201/.gitkeep b/db/changes/234201/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234201/00-ACL_workerDepartment.sql b/db/changes/234201/00-ACL_workerDepartment.sql new file mode 100644 index 000000000..ceb8d5d75 --- /dev/null +++ b/db/changes/234201/00-ACL_workerDepartment.sql @@ -0,0 +1,3 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('WorkerDepartment', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/234201/00-account_acl.sql b/db/changes/234201/00-account_acl.sql new file mode 100644 index 000000000..8dfe1d1ec --- /dev/null +++ b/db/changes/234201/00-account_acl.sql @@ -0,0 +1,7 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('VnUser', 'higherPrivileges', '*', 'ALLOW', 'ROLE', 'itManagement'), + ('VnUser', 'mediumPrivileges', '*', 'ALLOW', 'ROLE', 'hr'), + ('VnUser', 'updateUser', '*', 'ALLOW', 'ROLE', 'employee'); + +ALTER TABLE `account`.`user` ADD `username` varchar(30) AS (name) VIRTUAL; diff --git a/db/changes/234201/00-aclClient.sql b/db/changes/234201/00-aclClient.sql new file mode 100644 index 000000000..3df9522cf --- /dev/null +++ b/db/changes/234201/00-aclClient.sql @@ -0,0 +1,3 @@ + +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES('TicketCollection', '*', 'WRITE', 'ALLOW', 'ROLE', 'production'); diff --git a/db/changes/234201/00-aclSetPassword.sql b/db/changes/234201/00-aclSetPassword.sql new file mode 100644 index 000000000..44b3e9de0 --- /dev/null +++ b/db/changes/234201/00-aclSetPassword.sql @@ -0,0 +1,4 @@ +INSERT INTO `salix`.`ACL` (model,property,accessType,permission,principalType,principalId) + VALUES ('Worker','setPassword','*','ALLOW','ROLE','employee'); + + diff --git a/db/changes/234201/00-aclUrlHedera.sql b/db/changes/234201/00-aclUrlHedera.sql new file mode 100644 index 000000000..79d9fb4c8 --- /dev/null +++ b/db/changes/234201/00-aclUrlHedera.sql @@ -0,0 +1,7 @@ +INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) + VALUES + ('hedera', 'test', 'https://test-shop.verdnatura.es/'), + ('hedera', 'production', 'https://shop.verdnatura.es/'); + +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) + VALUES('Url', 'getByUser', 'READ', 'ALLOW', 'ROLE', '$everyone'); diff --git a/db/changes/234201/00-dropWorkerCreate.sql b/db/changes/234201/00-dropWorkerCreate.sql new file mode 100644 index 000000000..b903909b6 --- /dev/null +++ b/db/changes/234201/00-dropWorkerCreate.sql @@ -0,0 +1 @@ +DROP PROCEDURE IF EXISTS `vn`.`workerCreate`; diff --git a/db/changes/234201/00-packagingFk.sql b/db/changes/234201/00-packagingFk.sql new file mode 100644 index 000000000..9a775ada9 --- /dev/null +++ b/db/changes/234201/00-packagingFk.sql @@ -0,0 +1,5 @@ +ALTER TABLE `vn`.`buy` CHANGE `packageFk` `packagingFk` varchar(10) +CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT '--' NULL; + +ALTER TABLE `vn`.`buy` +ADD COLUMN `packageFk` varchar(10) AS (`packagingFk`) VIRTUAL; \ No newline at end of file diff --git a/db/changes/234201/00-packagingFkviews.sql b/db/changes/234201/00-packagingFkviews.sql new file mode 100644 index 000000000..49d41c26c --- /dev/null +++ b/db/changes/234201/00-packagingFkviews.sql @@ -0,0 +1,150 @@ +CREATE SCHEMA IF NOT EXISTS `vn2008`; + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`awbVolume` +AS SELECT `d`.`awbFk` AS `awbFk`, + `b`.`stickers` * `i`.`density` * IF( + `p`.`volume` > 0, + `p`.`volume`, + `p`.`width` * `p`.`depth` * IF(`p`.`height` = 0, `i`.`size` + 10, `p`.`height`) + ) / (`vc`.`aerealVolumetricDensity` * 1000) AS `volume`, + `b`.`id` AS `buyFk` +FROM ( + ( + ( + ( + ( + ( + ( + ( + `vn`.`buy` `b` + JOIN `vn`.`item` `i` ON(`b`.`itemFk` = `i`.`id`) + ) + JOIN `vn`.`itemType` `it` ON(`i`.`typeFk` = `it`.`id`) + ) + JOIN `vn`.`packaging` `p` ON(`p`.`id` = `b`.`packagingFk`) + ) + JOIN `vn`.`entry` `e` ON(`b`.`entryFk` = `e`.`id`) + ) + JOIN `vn`.`travel` `t` ON(`t`.`id` = `e`.`travelFk`) + ) + JOIN `vn`.`duaEntry` `de` ON(`de`.`entryFk` = `e`.`id`) + ) + JOIN `vn`.`dua` `d` ON(`d`.`id` = `de`.`duaFk`) + ) + JOIN `vn`.`volumeConfig` `vc` + ) +WHERE `t`.`shipped` > makedate(year(`util`.`VN_CURDATE`()) - 1, 1); + + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`Compres` +AS SELECT `c`.`id` AS `Id_Compra`, + `c`.`entryFk` AS `Id_Entrada`, + `c`.`itemFk` AS `Id_Article`, + `c`.`buyingValue` AS `Costefijo`, + `c`.`quantity` AS `Cantidad`, + `c`.`packagingFk` AS `Id_Cubo`, + `c`.`stickers` AS `Etiquetas`, + `c`.`freightValue` AS `Portefijo`, + `c`.`packageValue` AS `Embalajefijo`, + `c`.`comissionValue` AS `Comisionfija`, + `c`.`packing` AS `Packing`, + `c`.`grouping` AS `grouping`, + `c`.`groupingMode` AS `caja`, + `c`.`location` AS `Nicho`, + `c`.`price1` AS `Tarifa1`, + `c`.`price2` AS `Tarifa2`, + `c`.`price3` AS `Tarifa3`, + `c`.`minPrice` AS `PVP`, + `c`.`printedStickers` AS `Vida`, + `c`.`isChecked` AS `punteo`, + `c`.`ektFk` AS `buy_edi_id`, + `c`.`created` AS `odbc_date`, + `c`.`isIgnored` AS `Novincular`, + `c`.`isPickedOff` AS `isPickedOff`, + `c`.`workerFk` AS `Id_Trabajador`, + `c`.`weight` AS `weight`, + `c`.`dispatched` AS `dispatched`, + `c`.`containerFk` AS `container_id`, + `c`.`itemOriginalFk` AS `itemOriginalFk` +FROM `vn`.`buy` `c`; + +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn2008`.`buySource` +AS SELECT `b`.`entryFk` AS `Id_Entrada`, + `b`.`isPickedOff` AS `isPickedOff`, + NULL AS `tarifa0`, + `e`.`kop` AS `kop`, + `b`.`id` AS `Id_Compra`, + `i`.`typeFk` AS `tipo_id`, + `b`.`itemFk` AS `Id_Article`, + `i`.`size` AS `Medida`, + `i`.`stems` AS `Tallos`, + `b`.`stickers` AS `Etiquetas`, + `b`.`packagingFk` AS `Id_Cubo`, + `b`.`buyingValue` AS `Costefijo`, + `b`.`packing` AS `Packing`, + `b`.`grouping` AS `Grouping`, + `b`.`quantity` AS `Cantidad`, + `b`.`price2` AS `Tarifa2`, + `b`.`price3` AS `Tarifa3`, + `b`.`isChecked` AS `Punteo`, + `b`.`groupingMode` AS `Caja`, + `i`.`isToPrint` AS `Imprimir`, + `i`.`name` AS `Article`, + `vn`.`ink`.`picture` AS `Tinta`, + `i`.`originFk` AS `id_origen`, + `i`.`minPrice` AS `PVP`, + NULL AS `Id_Accion`, + `s`.`company_name` AS `pro`, + `i`.`hasMinPrice` AS `Min`, + `b`.`isIgnored` AS `Novincular`, + `b`.`freightValue` AS `Portefijo`, + round(`b`.`buyingValue` * `b`.`quantity`, 2) AS `Importe`, + `b`.`printedStickers` AS `Vida`, + `i`.`comment` AS `reference`, + `b`.`workerFk` AS `Id_Trabajador`, + `e`.`s1` AS `S1`, + `e`.`s2` AS `S2`, + `e`.`s3` AS `S3`, + `e`.`s4` AS `S4`, + `e`.`s5` AS `S5`, + `e`.`s6` AS `S6`, + 0 AS `price_fixed`, + `i`.`producerFk` AS `producer_id`, + `i`.`subName` AS `tag1`, + `i`.`value5` AS `tag2`, + `i`.`value6` AS `tag3`, + `i`.`value7` AS `tag4`, + `i`.`value8` AS `tag5`, + `i`.`value9` AS `tag6`, + `s`.`company_name` AS `company_name`, + `b`.`weight` AS `weightPacking`, + `i`.`packingOut` AS `packingOut`, + `b`.`itemOriginalFk` AS `itemOriginalFk`, + `io`.`longName` AS `itemOriginalName`, + `it`.`gramsMax` AS `gramsMax` +FROM ( + ( + ( + ( + ( + ( + `vn`.`item` `i` + JOIN `vn`.`itemType` `it` ON(`it`.`id` = `i`.`typeFk`) + ) + LEFT JOIN `vn`.`ink` ON(`vn`.`ink`.`id` = `i`.`inkFk`) + ) + LEFT JOIN `vn`.`buy` `b` ON(`b`.`itemFk` = `i`.`id`) + ) + LEFT JOIN `vn`.`item` `io` ON(`io`.`id` = `b`.`itemOriginalFk`) + ) + LEFT JOIN `edi`.`ekt` `e` ON(`e`.`id` = `b`.`ektFk`) + ) + LEFT JOIN `edi`.`supplier` `s` ON(`e`.`pro` = `s`.`supplier_id`) + ); + diff --git a/db/changes/234201/00-supplierAccountCheckLength.sql b/db/changes/234201/00-supplierAccountCheckLength.sql new file mode 100644 index 000000000..55a68e37b --- /dev/null +++ b/db/changes/234201/00-supplierAccountCheckLength.sql @@ -0,0 +1,6 @@ +UPDATE `vn`.`supplier` + SET account = LPAD(id,10,'0') + WHERE account IS NULL; + +ALTER TABLE `vn`.`supplier` ADD CONSTRAINT supplierAccountTooShort CHECK (LENGTH(account) = 10); +ALTER TABLE `vn`.`supplier` MODIFY COLUMN account varchar(10) CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT 4100000000 NOT NULL COMMENT 'Default accounting code for suppliers.'; diff --git a/db/changes/234201/00-zoneIncluded.sql b/db/changes/234201/00-zoneIncluded.sql new file mode 100644 index 000000000..12d4058cf --- /dev/null +++ b/db/changes/234201/00-zoneIncluded.sql @@ -0,0 +1,26 @@ +ALTER TABLE `vn`.`zoneIncluded` + ADD COLUMN `id` INT(11) UNSIGNED NOT NULL AUTO_INCREMENT FIRST, + DROP PRIMARY KEY, + DROP FOREIGN KEY `zoneFk2`, + DROP FOREIGN KEY `zoneGeoFk2`, + DROP KEY `geoFk_idx`, + ADD PRIMARY KEY (`id`), + ADD CONSTRAINT `zoneIncluded_FK_1` FOREIGN KEY (zoneFk) REFERENCES `vn`.`zone`(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `zoneIncluded_FK_2` FOREIGN KEY (geoFk) REFERENCES `vn`.`zoneGeo`(id) ON DELETE CASCADE ON UPDATE CASCADE, + ADD CONSTRAINT `unique_zone_geo` UNIQUE (`zoneFk`, `geoFk`); + +DROP TRIGGER IF EXISTS `vn`.`zoneIncluded_afterDelete`; +USE `vn`; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`zoneIncluded_afterDelete` + AFTER DELETE ON `zoneIncluded` + FOR EACH ROW +BEGIN + INSERT INTO zoneLog + SET `action` = 'delete', + `changedModel` = 'zoneIncluded', + `changedModelId` = OLD.zoneFk, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/changes/234201/02-packagingFktrigger.sql b/db/changes/234201/02-packagingFktrigger.sql new file mode 100644 index 000000000..4edcd3f3e --- /dev/null +++ b/db/changes/234201/02-packagingFktrigger.sql @@ -0,0 +1,57 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`buy_afterUpdate` + AFTER UPDATE ON `buy` + FOR EACH ROW +trig: BEGIN + DECLARE vLanded DATE; + DECLARE vBuyerFk INT; + DECLARE vIsBuyerToBeEmailed BOOL; + DECLARE vItemName VARCHAR(50); + + IF @isModeInventory OR @isTriggerDisabled THEN + LEAVE trig; + END IF; + + IF !(NEW.id <=> OLD.id) + OR !(NEW.entryFk <=> OLD.entryFk) + OR !(NEW.itemFk <=> OLD.itemFk) + OR !(NEW.quantity <=> OLD.quantity) + OR !(NEW.created <=> OLD.created) THEN + CALL stock.log_add('buy', NEW.id, OLD.id); + END IF; + + CALL buy_afterUpsert(NEW.id); + + SELECT w.isBuyerToBeEmailed, t.landed + INTO vIsBuyerToBeEmailed, vLanded + FROM entry e + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE e.id = NEW.entryFk; + + SELECT it.workerFk, i.longName + INTO vBuyerFk, vItemName + FROM itemCategory k + JOIN itemType it ON it.categoryFk = k.id + JOIN item i ON i.typeFk = it.id + WHERE i.id = OLD.itemFk; + + IF vIsBuyerToBeEmailed AND + vBuyerFk != account.myUser_getId() AND + vLanded = util.VN_CURDATE() THEN + IF !(NEW.itemFk <=> OLD.itemFk) OR + !(NEW.quantity <=> OLD.quantity) OR + !(NEW.packing <=> OLD.packing) OR + !(NEW.grouping <=> OLD.grouping) OR + !(NEW.packagingFk <=> OLD.packagingFk) OR + !(NEW.weight <=> OLD.weight) THEN + CALL vn.mail_insert( + CONCAT(account.user_getNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUser_getName(),'@verdnatura.es'), + CONCAT('E ', NEW.entryFk ,' Se ha modificado item ', NEW.itemFk, ' ', vItemName), + 'Este email se ha generado automáticamente' + ); + END IF; + END IF; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/234201/03-packagingFkProc.sql b/db/changes/234201/03-packagingFkProc.sql new file mode 100644 index 000000000..4876c270e --- /dev/null +++ b/db/changes/234201/03-packagingFkProc.sql @@ -0,0 +1,1381 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume`(vTravelFk INT) +BEGIN + + SELECT w1.name AS ORI, + w2.name AS DES, + tr.shipped shipment, + tr.landed landing, + a.name Agencia, + s.name Proveedor, + e.id Id_Entrada, + e.invoiceNumber Referencia, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + vn.item_getVolume(b.itemFk ,b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode a ON a.id = tr.agencyModeFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + WHERE tr.id = vTravelFk; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travelVolume_get`(vFromDated DATE, vToDated DATE, vWarehouseFk INT) +BEGIN + SELECT tr.landed Fecha, + a.name Agencia, + count(DISTINCT e.id) numEntradas, + FLOOR(sum(item_getVolume(b.itemFk, b.packagingFk) * b.stickers / 1000000 )) AS m3 + FROM vn.travel tr + JOIN vn.agencyMode a ON a.id = tr.agencyModeFk + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + WHERE tr.landed BETWEEN vFromDated AND vToDated + AND e.isRaid = FALSE + AND tr.warehouseInFk = vWarehouseFk + GROUP BY tr.landed , a.name ; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`travel_getEntriesMissingPackage`(vSelf INT) +BEGIN + DECLARE vpackageOrPackingNull INT; + DECLARE vTravelFk INT; + + SELECT travelfk INTO vTravelFk + FROM entry + WHERE id = vSelf; + + SELECT e.id entryFk + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN buy b ON b.entryFk = e.id + WHERE t.id = vTravelFk + AND (b.packing IS NULL OR b.packagingFk IS NULL); +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticketBoxesView`(IN vTicketFk INT) +BEGIN + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, + i.size + FROM ticket t + JOIN sale s ON s.ticketFk = t.id + JOIN item i ON i.id = s.itemFk + JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk + JOIN buy b on b.id = lb.buy_id + JOIN packaging p on p.id = b.packagingFk + WHERE s.quantity >= b.packing + AND t.id = vTicketFk + AND p.isBox + GROUP BY s.itemFk; + + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`stockBuyedByWorker`( + vDated DATE, + vWorker INT +) +BEGIN +/** + * Inserta el volumen de compra de un comprador + * en stockBuyed de acuerdo con la fecha. + * + * @param vDated Fecha de compra + * @param vWorker Id de trabajador + */ + CREATE OR REPLACE TEMPORARY TABLE tStockBuyed + (INDEX (userFk)) + ENGINE = MEMORY + SELECT requested, reserved, userFk + FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; + + DELETE FROM stockBuyed + WHERE dated = vDated + AND userFk = vWorker; + + CALL stockTraslation(vDated); + + INSERT INTO stockBuyed(userFk, buyed, `dated`, reserved, requested, description) + SELECT it.workerFk, + SUM((ti.quantity / b.packing) * buy_getVolume(b.id)) / vc.palletM3 / 1000000, + vDated, + sb.reserved, + sb.requested, + u.name + FROM itemType it + JOIN item i ON i.typeFk = it.id + LEFT JOIN tmp.item ti ON ti.itemFk = i.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN warehouse wh ON wh.code = 'VNH' + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = wh.id + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + JOIN account.`user` u ON u.id = it.workerFk + LEFT JOIN tStockBuyed sb ON sb.userFk = it.workerFk + WHERE ic.display + AND it.workerFk = vWorker; + + SELECT b.entryFk Id_Entrada, + i.id Id_Article, + i.name Article, + ti.quantity Cantidad, + (ac.conversionCoefficient * (ti.quantity / b.packing) * buy_getVolume(b.id)) + / (vc.trolleyM3 * 1000000) buyed, + b.packagingFk id_cubo, + b.packing + FROM tmp.item ti + JOIN item i ON i.id = ti.itemFk + JOIN itemType it ON i.typeFk = it.id + JOIN itemCategory ic ON ic.id = it.categoryFk + JOIN worker w ON w.id = it.workerFk + JOIN auctionConfig ac + JOIN tmp.buyUltimate bu ON bu.itemFk = i.id + AND bu.warehouseFk = ac.warehouseFk + JOIN buy b ON b.id = bu.buyFk + JOIN volumeConfig vc + WHERE ic.display + AND w.id = vWorker; + + DROP TEMPORARY TABLE tmp.buyUltimate, + tmp.item, + tStockBuyed; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) +BEGIN + + DECLARE vItemFk INT; + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + SELECT itemFk INTO vItemFk + FROM vn.buy b + WHERE b.id = vItemFk; + + IF (SELECT COUNT(*) FROM vn.shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO vn.parking(`code`) VALUES(vShelvingFk); + INSERT INTO vn.shelving(`code`, parkingFk) + SELECT vShelvingFk, id + FROM vn.parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE vn.itemShelving + SET visible = visible+vQuantity, + created = vCreated + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + created, + `grouping`, + packing, + packagingFk) + SELECT vItemFk, + vShelvingFk, + vQuantity, + vCreated, + IF(vGrouping = 0, IFNULL(b.packing, vPacking), vGrouping) `grouping`, + IF(vPacking = 0, b.packing, vPacking) packing, + IF(vPackagingFk = '', b.packagingFk, vPackagingFk) packaging + FROM vn.item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) +BEGIN + + +/** + * Añade registro o lo actualiza si ya existe. + * + * @param vShelvingFk matrícula del carro + * @param vBarcode el id del registro + * @param vQuantity indica la cantidad del producto + * @param vPackagingFk el packaging del producto en itemShelving, NULL para coger el de la ultima compra + * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra + * @param vPacking el packing del producto, NULL para coger el de la ultima compra + * @param vWarehouseFk indica el sector + * + **/ + + DECLARE vItemFk INT; + + SELECT barcodeToItem(vBarcode) INTO vItemFk; + + IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN + + INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); + INSERT INTO shelving(code, parkingFk) + SELECT vShelvingFk, id + FROM parking + WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; + + END IF; + + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk + AND packing = vPacking) = 1 THEN + + UPDATE itemShelving + SET visible = visible+vQuantity + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + + ELSE + CALL cache.last_buy_refresh(FALSE); + INSERT INTO itemShelving( itemFk, + shelvingFk, + visible, + grouping, + packing, + packagingFk) + + SELECT vItemFk, + vShelvingFk, + vQuantity, + IFNULL(vGrouping, b.grouping), + IFNULL(vPacking, b.packing), + IFNULL(vPackagingFk, b.packagingFk) + FROM item i + LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk + LEFT JOIN buy b ON b.id = lb.buy_id + WHERE i.id = vItemFk; + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemFreight_Show`(vItemFk INT, vWarehouseFk INT) +BEGIN + + SELECT cm3 Volumen_Entrada, + cm3delivery Volumen_Salida, + p.volume Volumen_del_embalaje, + p.width Ancho_del_embalaje, + p.`depth` Largo_del_embalaje, + b.packagingFk , + IFNULL(p.height, i.`size`) + 10 Altura, + b.packing Packing_Entrada, + i.packingOut Packing_Salida, + i.id itemFk, + b.id buyFk, + b.entryFk, + w.name warehouseFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packagingFk + LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk + WHERE ic.itemFk = vItemFk + AND ic.warehouseFk = vWarehouseFk; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventoryMake`(vDate DATE, vWh INT) +proc: BEGIN +/** +* Recalcula los inventarios de todos los almacenes, si vWh = 0 +* +* @param vDate Fecha de los nuevos inventarios +* @param vWh almacen al cual hacer el inventario +*/ + + DECLARE vDone BOOL; + DECLARE vEntryFk INT; + DECLARE vTravelFk INT; + DECLARE vDateLastInventory DATE; + DECLARE vDateYesterday DATETIME DEFAULT vDate - INTERVAL 1 SECOND; + DECLARE vWarehouseOutFkInventory INT; + DECLARE vInventorySupplierFk INT; + DECLARE vAgencyModeFkInventory INT; + + DECLARE cWarehouses CURSOR FOR + SELECT id + FROM warehouse + WHERE isInventory + AND vWh IN (0,id); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN cWarehouses; + SET @isModeInventory := TRUE; + l: LOOP + + SET vDone = FALSE; + FETCH cWarehouses INTO vWh; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT w.id INTO vWarehouseOutFkInventory + FROM warehouse w + WHERE w.code = 'inv'; + + SELECT inventorySupplierFk INTO vInventorySupplierFk + FROM entryConfig; + + SELECT am.id INTO vAgencyModeFkInventory + FROM agencyMode am + where code = 'inv'; + + SELECT MAX(landed) INTO vDateLastInventory + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + JOIN buy b ON b.entryFk = e.id + WHERE warehouseOutFk = vWarehouseOutFkInventory + AND landed < vDate + AND e.supplierFk = vInventorySupplierFk + AND warehouseInFk = vWh + AND NOT isRaid; + + IF vDateLastInventory IS NULL THEN + SELECT inventoried INTO vDateLastInventory FROM config; + END IF; + + -- Generamos travel, si no existe. + SET vTravelFK = 0; + + SELECT id INTO vTravelFk + FROM travel + WHERE warehouseOutFk = vWarehouseOutFkInventory + AND warehouseInFk = vWh + AND landed = vDate + AND agencyModeFk = vAgencyModeFkInventory + AND ref = 'inventario' + LIMIT 1; + + IF NOT vTravelFK THEN + + INSERT INTO travel SET + warehouseOutFk = vWarehouseOutFkInventory, + warehouseInFk = vWh, + shipped = vDate, + landed = vDate, + agencyModeFk = vAgencyModeFkInventory, + ref = 'inventario', + isDelivered = TRUE, + isReceived = TRUE; + + SELECT LAST_INSERT_ID() INTO vTravelFk; + + END IF; + + -- Generamos entrada si no existe, o la vaciamos. + SET vEntryFk = 0; + + SELECT id INTO vEntryFk + FROM entry + WHERE supplierFk = vInventorySupplierFk + AND travelFk = vTravelFk; + + IF NOT vEntryFk THEN + + INSERT INTO entry SET + supplierFk = vInventorySupplierFk, + isConfirmed = TRUE, + isOrdered = TRUE, + travelFk = vTravelFk; + + SELECT LAST_INSERT_ID() INTO vEntryFk; + + ELSE + + DELETE FROM buy WHERE entryFk = vEntryFk; + + END IF; + + -- Preparamos tabla auxilar + CREATE OR REPLACE TEMPORARY TABLE tmp.inventory ( + itemFk INT(11) NOT NULL PRIMARY KEY, + quantity int(11) DEFAULT '0', + buyingValue decimal(10,3) DEFAULT '0.000', + freightValue decimal(10,3) DEFAULT '0.000', + packing int(11) DEFAULT '0', + `grouping` smallint(5) unsigned NOT NULL DEFAULT '1', + groupingMode tinyint(4) NOT NULL DEFAULT 0 , + comissionValue decimal(10,3) DEFAULT '0.000', + packageValue decimal(10,3) DEFAULT '0.000', + packageFk varchar(10) COLLATE utf8_unicode_ci DEFAULT '--', + price1 decimal(10,2) DEFAULT '0.00', + price2 decimal(10,2) DEFAULT '0.00', + price3 decimal(10,2) DEFAULT '0.00', + minPrice decimal(10,2) DEFAULT '0.00', + producer varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + INDEX (itemFK)) ENGINE = MEMORY; + + -- Compras + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT b.itemFk, SUM(b.quantity) + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseInFk = vWh + AND tr.landed BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk; + SELECT vDateLastInventory , vDateYesterday; + + -- Traslados + INSERT INTO tmp.inventory(itemFk, quantity) + SELECT itemFk, quantityOut + FROM ( + SELECT b.itemFk,- SUM(b.quantity) quantityOut + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel tr ON tr.id = e.travelFk + WHERE tr.warehouseOutFk = vWh + AND tr.shipped BETWEEN vDateLastInventory + AND vDateYesterday + AND NOT isRaid + GROUP BY b.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity, 0) + sub.quantityOut; + + -- Ventas + INSERT INTO tmp.inventory(itemFk,quantity) + SELECT itemFk, saleOut + FROM ( + SELECT s.itemFk, - SUM(s.quantity) saleOut + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + WHERE t.warehouseFk = vWh + AND t.shipped BETWEEN vDateLastInventory AND vDateYesterday + GROUP BY s.itemFk + ) sub + ON DUPLICATE KEY UPDATE quantity = IFNULL(quantity,0) + sub.saleOut; + + -- Actualiza valores de la ultima compra + UPDATE tmp.inventory inv + JOIN cache.last_buy lb ON lb.item_id = inv.itemFk AND lb.warehouse_id = vWh + JOIN buy b ON b.id = lb.buy_id + JOIN item i ON i.id = b.itemFk + LEFT JOIN producer p ON p.id = i.producerFk + SET inv.buyingValue = b.buyingValue, + inv.freightValue = b.freightValue, + inv.packing = b.packing, + inv.`grouping`= b.`grouping`, + inv.groupingMode = b.groupingMode, + inv.comissionValue = b.comissionValue, + inv.packageValue = b.packageValue, + inv.packageFk = b.packagingFk, + inv.price1 = b.price1, + inv.price2 = b.price2, + inv.price3 = b.price3, + inv.minPrice = b.minPrice, + inv.producer = p.name; + + INSERT INTO buy( itemFk, + quantity, + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packagingFk, + price1, + price2, + price3, + minPrice, + entryFk) + SELECT itemFk, + GREATEST(quantity, 0), + buyingValue, + freightValue, + packing, + `grouping`, + groupingMode, + comissionValue, + packageValue, + packagingFk, + price1, + price2, + price3, + minPrice, + vEntryFk + FROM tmp.inventory; + + SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; + + -- Actualizamos el campo lastUsed de item + UPDATE item i + JOIN tmp.inventory i2 ON i2.itemFk = i.id + SET i.lastUsed = NOW() + WHERE i2.quantity; + + -- DROP TEMPORARY TABLE tmp.inventory; + + END LOOP; + + CLOSE cWarehouses; + + UPDATE config SET inventoried = vDate; + SET @isModeInventory := FALSE; + + DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; + CREATE TEMPORARY TABLE tmp.entryToDelete + (INDEX(entryId) USING BTREE) ENGINE = MEMORY + SELECT e.id as entryId, + t.id as travelId + FROM travel t + JOIN `entry` e ON e.travelFk = t.id + WHERE e.supplierFk = vInventorySupplierFk + AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY + AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); + + DELETE e + FROM `entry` e + JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; + + DELETE IGNORE t + FROM travel t + JOIN tmp.entryToDelete tmp ON tmp.travelId = t.id; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`inventory_repair`() +BEGIN + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntry; + CREATE TEMPORARY TABLE tmp.lastEntry + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packagingFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE (b.packagingFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; + CREATE TEMPORARY TABLE tmp.lastEntryOk + (PRIMARY KEY (buyFk)) + SELECT + i.id AS itemFk, + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue, + b.packagingFk, + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.packagingFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) + ORDER BY tr.landed DESC; + + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + (INDEX (warehouseFk,itemFk)) + SELECT * + FROM tmp.lastEntryOk tmp + GROUP BY tmp.itemFk,tmp.warehouseFk; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packagingFk = eo.packagingFk WHERE b.packagingFk = "--"; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.price2 = eo.price2 WHERE b.price2 = 0 ; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.packing = eo.packing WHERE b.packing = 0; + + UPDATE buy b + JOIN tmp.lastEntry lt ON lt.buyFk = b.id + JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk + SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; + + DROP TEMPORARY TABLE tmp.lastEntry; + DROP TEMPORARY TABLE tmp.lastEntryOk; + DROP TEMPORARY TABLE tmp.lastEntryOkGroup; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_afterUpsert`(vSelf INT) +BEGIN +/** + * Triggered actions when a buy is updated or inserted. + * + * @param vSelf The buy reference + */ + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vPackingOut DECIMAL(10,2); + DECLARE vWarehouse INT; + DECLARE vStandardFlowerBox INT; + DECLARE vWarehouseOut INT; + DECLARE vIsMerchandise BOOL; + DECLARE vIsFeedStock BOOL; + DECLARE vWeight DECIMAL(10,2); + DECLARE vPacking INT; + + SELECT b.entryFk, + b.itemFk, + i.packingOut, + ic.merchandise, + vc.standardFlowerBox, + b.weight, + b.packing + INTO + vEntryFk, + vItemFk, + vPackingOut, + vIsMerchandise, + vStandardFlowerBox, + vWeight, + vPacking + FROM buy b + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN packaging p ON p.id = b.packagingFk AND NOT p.isBox + JOIN volumeConfig vc ON TRUE + WHERE b.id = vSelf; + + SELECT t.warehouseInFk, t.warehouseOutFk + INTO vWarehouse, vWarehouseOut + FROM entry e + JOIN travel t ON t.id = e.travelFk + WHERE e.id = vEntryFk; + + IF vIsMerchandise THEN + + REPLACE itemCost SET + itemFk = vItemFk, + warehouseFk = vWarehouse, + cm3 = buy_getUnitVolume(vSelf), + cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); + + IF vWeight AND vPacking THEN + UPDATE itemCost SET + grams = vWeight * 1000 / vPacking + WHERE itemFk = vItemFk + AND warehouseFk = vWarehouse; + END IF; + END IF; + + SELECT isFeedStock INTO vIsFeedStock + FROM warehouse WHERE id = vWarehouseOut; + + IF vIsFeedStock THEN + INSERT IGNORE INTO producer(`name`) + SELECT es.company_name + FROM buy b + JOIN edi.ekt be ON be.id = b.ektFk + JOIN edi.supplier es ON es.supplier_id = be.pro + WHERE b.id = vSelf; + + END IF; + +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`buy_getUnitVolume`(vSelf INT) + RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Calculates the unit volume occupied by a buy. + * + * @param vSelf The buy id + * @return The unit volume in cubic centimeters + */ + DECLARE vItem INT; + DECLARE vPackaging VARCHAR(10); + DECLARE vPacking INT; + + SELECT itemFk, packagingFk, packing + INTO vItem, vPackaging, vPacking + FROM buy + WHERE id = vSelf; + + RETURN IFNULL(ROUND(item_getVolume(vItem, vPackaging) / vPacking), 0); +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_recalcPrices`() +BEGIN +/** + * Recalcula los precios para las compras insertadas en tmp.buyRecalc + * + * @param tmp.buyRecalc (id) + */ + DECLARE vLanded DATE; + DECLARE vWarehouseFk INT; + DECLARE vHasNotPrice BOOL; + DECLARE vBuyingValue DECIMAL(10,3); + DECLARE vPackagingFk VARCHAR(10); + DECLARE vIsWarehouseFloramondo BOOL; + + SELECT t.landed, t.warehouseInFk, (w.`name` = 'Floramondo') + INTO vLanded, vWarehouseFk, vIsWarehouseFloramondo + FROM tmp.buyRecalc br + JOIN buy b ON b.id = br.id + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + LIMIT 1; + + CALL rate_getPrices(vLanded, vWarehouseFk); + + UPDATE buy b + JOIN tmp.buyRecalc br ON br.id = b.id AND (@buyId := b.id) + LEFT JOIN packaging p ON p.id = b.packagingFk + JOIN item i ON i.id = b.itemFk + JOIN entry e ON e.id = b.entryFk + JOIN itemType it ON it.id = i.typeFk + JOIN travel tr ON tr.id = e.travelFk + JOIN agencyMode am ON am.id = tr.agencyModeFk + JOIN tmp.rate r + JOIN volumeConfig vc + SET b.freightValue = @PF:= IFNULL(((am.m3 * @m3:= item_getVolume(b.itemFk, b.packagingFk) / 1000000) + / b.packing) * IF(am.hasWeightVolumetric, GREATEST(b.weight / @m3 / vc.aerealVolumetricDensity, 1), 1), 0), + b.comissionValue = @CF:= ROUND(IFNULL(e.commission * b.buyingValue / 100, 0), 3), + b.packageValue = @EF:= IF(vIsWarehouseFloramondo, 0, IFNULL(ROUND(IF(p.isPackageReturnable, p.returnCost / b.packing , p.`value` / b.packing), 3),0)), + b.price3 = @t3:= IF(r.rate3 = 0, b.buyingValue,ROUND((b.buyingValue + @CF + @EF + @PF) / ((100 - r.rate3 - it.promo ) /100) ,2)), -- He añadido que el coste sea igual a tarifa3 si t3 = 0 + b.price2 = @t2:= round(@t3 * (1 + ((r.rate2 - r.rate3)/100)),2), + b.price2 = @t2:= IF(@t2 <= @t3,@t3 , @t2); + + SELECT (b.buyingValue = b.price2), b.buyingValue, b.packagingFk + INTO vHasNotPrice, vBuyingValue, vPackagingFk + FROM vn.buy b + WHERE b.id = @buyId AND b.buyingValue <> 0.01; + + DROP TEMPORARY TABLE tmp.rate; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `edi`.`ekt_load`(IN `vSelf` INT) +proc:BEGIN + + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vPutOrderFk INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + DECLARE vEntryFk INT; + DECLARE vHasToChangePackagingFk BOOLEAN; + DECLARE vIsFloramondoDirect BOOLEAN; + DECLARE vTicketFk INT; + DECLARE vHasItemGroup BOOL; + DECLARE vDescription VARCHAR(255); + DECLARE vSaleFk INT; + + -- Carga los datos necesarios del EKT + + SELECT e.ref, qty, package, putOrderFk MOD 1000000, i2.id , NOT ISNULL(eea.addressFk), NOT ISNULL(igto.group_code), + CONCAT(e.`ref`, ' ', e.item, ' ', e.sub, ' EktFk:', e.id) + INTO vRef, vQty, vPackage, vPutOrderFk, vItem, vIsFloramondoDirect, vHasItemGroup, vDescription + FROM edi.ekt e + LEFT JOIN edi.item i ON e.ref = i.id + LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk + LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID + LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id + WHERE e.id = vSelf + LIMIT 1; + + IF NOT vHasItemGroup THEN + + CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription); + + CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); + + LEAVE proc; + + END IF; + + -- Asigna la entrada + SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; + + -- Inserta el cubo si no existe + + IF vPackage = 800 THEN + + SET vHasToChangePackagingFk = TRUE; + + IF vItem THEN + + SELECT vn.item_getPackage(vItem) INTO vPackage ; + + ELSE + + SET vPackage = 8000 + vQty; + + INSERT IGNORE INTO vn.packaging(id, width, `depth`) + SELECT vPackage, vc.ccLength / vQty, vc.ccWidth + FROM vn.volumeConfig vc; + + END IF; + + ELSE + + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Si es una compra de Logiflora obtiene el articulo + IF vPutOrderFk THEN + + SELECT i.id INTO vItem + FROM edi.putOrder po + JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID + WHERE po.id = vPutOrderFk + LIMIT 1; + + END IF; + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + IF IFNULL(vItem,0) = 0 THEN + + -- Intenta obtener el artículo en base a los atributos holandeses + + SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem + FROM edi.ekt e + JOIN edi.item_track t ON t.item_id = e.ref + LEFT JOIN edi.ekt l ON l.ref = e.ref + LEFT JOIN vn.buy b ON b.ektFk = l.id + LEFT JOIN vn.item i ON i.id = b.itemFk + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND b.itemFk != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND IF(t.item, l.item = e.item, TRUE) + AND i.isFloramondo = vIsFloramondoDirect + ORDER BY l.now DESC, b.id ASC + LIMIT 1; + + END IF; + + -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo + IF ISNULL(vItem) AND vIsFloramondoDirect THEN + + CALL edi.item_getNewByEkt(vSelf, vItem); + + END IF; + + INSERT INTO vn.buy + ( + entryFk + ,ektFk + ,buyingValue + ,itemFk + ,stickers + ,packing + ,`grouping` + ,quantity + ,groupingMode + ,packagingFk + ,weight + ) + SELECT + vEntryFk + ,vSelf + ,(@t := IF(i.stems, i.stems, 1)) * e.pri / IFNULL(i.stemMultiplier, 1) buyingValue + ,IFNULL(vItem, cfg.generic_item) itemFk + ,e.qty stickers + ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing + ,IFNULL(b.`grouping`, e.pac) + ,@pac * e.qty + ,vForceToPacking + ,IF(vHasToChangePackagingFk OR ISNULL(b.packagingFk), vPackage, b.packagingFk) + ,(IFNULL(i.weightByPiece,0) * @pac)/1000 + FROM edi.ekt e + LEFT JOIN vn.buy b ON b.id = vBuy + LEFT JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.supplier s ON e.pro = s.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; + + DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; + + CREATE TEMPORARY TABLE tmp.buyRecalc + SELECT buy.id + FROM vn.buy + WHERE ektFk = vSelf; + + CALL vn.buy_recalcPrices(); + + -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy + IF vPutOrderFk THEN + + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) + SELECT po.saleFk, b.id, account.myUser_getId() + FROM edi.putOrder po + JOIN vn.buy b ON b.ektFk = vSelf + WHERE po.id = vPutOrderFk; + + END IF; + -- Si es una compra directa en Floramondo hay que añadirlo al ticket + + IF vIsFloramondoDirect THEN + + SELECT t.id INTO vTicketFk + FROM vn.ticket t + JOIN vn.ektEntryAssign eea + ON eea.addressFk = t.addressFk + AND t.warehouseFk = eea.warehouseInFk + JOIN edi.ekt e + ON e.sub = eea.sub + AND e.id = vSelf + WHERE e.fec = t.shipped + LIMIT 1; + + IF ISNULL(vTicketFk) THEN + + INSERT INTO vn.ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus + ) + SELECT + a.clientFk, + e.fec, + a.id, + a.agencyModeFk, + a.nickname, + eea.warehouseInFk, + c.id, + e.fec, + z.id, + z.price, + z.bonus + FROM edi.ekt e + JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + JOIN vn.address a ON a.id = eea.addressFk + JOIN vn.company c ON c.code = 'VNL' + JOIN vn.`zone` z ON z.code = 'FLORAMONDO' + WHERE e.id = vSelf + LIMIT 1; + + SET vTicketFk = LAST_INSERT_ID(); + + INSERT INTO vn.ticketLog + SET originFk = vTicketFk, + userFk = account.myUser_getId(), + `action` = 'insert', + description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk); + + END IF; + + INSERT INTO vn.sale (itemFk, ticketFk, concept, quantity, price) + SELECT vItem, vTicketFk, e.item, e.qty * e.pac, e.pri * ( 1 + fhc.floramondoMargin ) + FROM edi.ekt e + JOIN edi.floraHollandConfig fhc + WHERE e.id = vSelf; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) + SELECT vSaleFk, b.id, account.myUser_getId() + FROM vn.buy b + WHERE b.ektFk = vSelf; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT vSaleFk, c.id, e.pri + FROM edi.ekt e + JOIN vn.component c ON c.code = 'purchaseValue' + WHERE e.id = vSelf; + + INSERT INTO vn.saleComponent(saleFk, componentFk, value) + SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin + FROM edi.ekt e + JOIN edi.floraHollandConfig fhc + JOIN vn.component c ON c.code = 'margin' + WHERE e.id = vSelf; + END IF; + DROP TEMPORARY TABLE tmp.buyRecalc; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `hedera`.`item_getVisible`( + vWarehouse TINYINT, + vDate DATE, + vType INT, + vPrefix VARCHAR(255)) +BEGIN + +/** + * Gets visible items of the specified type at specified date. + * + * @param vWarehouse The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @return tmp.itemVisible Visible items + */ + DECLARE vPrefixLen SMALLINT; + DECLARE vFilter VARCHAR(255) DEFAULT NULL; + DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); + DECLARE EXIT HANDLER FOR 1114 + BEGIN + GET DIAGNOSTICS CONDITION 1 + @message = MESSAGE_TEXT; + CALL vn.mail_insert( + 'cau@verdnatura.es', + NULL, + CONCAT('hedera.item_getVisible error: ', @message), + CONCAT( + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), + ', prefijo: ', IFNULL(vPrefix,''))); + RESIGNAL; + END; + SET vPrefixLen = IFNULL(LENGTH(vPrefix), 0) + 1; + + IF vPrefixLen > 1 THEN + SET vFilter = CONCAT(vPrefix, '%'); + END IF; + + DROP TEMPORARY TABLE IF EXISTS `filter`; + CREATE TEMPORARY TABLE `filter` + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT id itemFk FROM vn.item + WHERE typeFk = vType + AND (vFilter IS NULL OR `name` LIKE vFilter); + + DROP TEMPORARY TABLE IF EXISTS currentStock; + CREATE TEMPORARY TABLE currentStock + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) quantity + FROM ( + SELECT b.itemFk, b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND t.warehouseInFk = vWarehouse + AND NOT e.isRaid + UNION ALL + SELECT b.itemFk, -b.quantity + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() + AND t.warehouseOutFk = vWarehouse + AND NOT e.isRaid + AND t.isDelivered + UNION ALL + SELECT m.itemFk, -m.quantity + FROM vn.sale m + JOIN vn.ticket t ON t.id = m.ticketFk + JOIN vn.ticketState s ON s.ticket = t.id + WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() + AND t.warehouseFk = vWarehouse + AND s.alertLevel = 3 + ) t + GROUP BY itemFk + HAVING quantity > 0; + + DROP TEMPORARY TABLE IF EXISTS tmp; + CREATE TEMPORARY TABLE tmp + (INDEX (itemFk)) + ENGINE = MEMORY + SELECT * + FROM ( + SELECT b.itemFk, b.packagingFk, b.packing + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vDateInv AND vDate + AND NOT b.isIgnored + AND b.price2 >= 0 + AND b.packagingFk IS NOT NULL + ORDER BY t.warehouseInFk = vWarehouse DESC, t.landed DESC + LIMIT 10000000000000000000 + ) t GROUP BY itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.itemVisible; + CREATE TEMPORARY TABLE tmp.itemVisible + ENGINE = MEMORY + SELECT i.id Id_Article, + SUBSTRING(i.`name`, vPrefixLen) Article, + t.packing, p.id Id_Cubo, + IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, + CEIL(s.quantity / t.packing) etiquetas + FROM vn.item i + JOIN `filter` f ON f.itemFk = i.id + JOIN currentStock s ON s.itemFk = i.id + LEFT JOIN tmp t ON t.itemFk = i.id + LEFT JOIN vn.packaging p ON p.id = t.packagingFk + WHERE CEIL(s.quantity / t.packing) > 0 + -- FIXME: Column Cubos.box not included in view vn.packaging + /* AND p.box */; + + DROP TEMPORARY TABLE + `filter`, + currentStock, + tmp; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buy_getVolume`() +BEGIN +/** + * Cálculo de volumen en líneas de compra + * @table tmp.buy(buyFk) + */ + SELECT t.name Temp, + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + item_getVolume(b.itemFk, b.packagingFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , + CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * + item_getVolume(b.itemFk, b.packagingFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais + FROM buy b + JOIN tmp.buy tb ON tb.buyFk = b.id + JOIN volumeConfig vc + JOIN item i ON i.id = b.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN temperature t ON t.code = it.temperatureFk + GROUP BY Temp; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`entry_checkPackaging`(vEntryFk INT) +BEGIN +/** + * Comprueba que los campos package y packaging no sean nulos + * + * @param vEntryFk Id de entrada + */ + DECLARE vpackageOrPackingNull INT; + + SELECT count(*) INTO vpackageOrPackingNull + FROM buy b + WHERE b.entryFk = vEntryFk + AND (b.packing IS NULL OR b.packagingFk IS NULL); + + IF vpackageOrPackingNull THEN + CALL util.throw("packageOrPackingNull"); + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`fustControl`(vFromDated DATE, vToDated DATE) +BEGIN + + DECLARE vSijsnerClientFk INT DEFAULT 19752; + + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + + SET vDateStart = vFromDated; + SET vDateEnd = util.Dayend(vToDated); + + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo + FROM vn.packaging p + LEFT JOIN ( + SELECT FustCode, sum(fustQuantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,b.packagingFk) FustCode, s.quantity / b.packing AS fustQuantity + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub + GROUP BY FustCode) sent ON sent.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk + WHERE t.shipped BETWEEN vDateStart AND vDateEnd + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND c.country = 'FRANCIA' + AND t.clientFk != vSijsnerClientFk + AND tp.quantity > 0) sub + GROUP BY FustCode) tp ON tp.FustCode = p.id + LEFT JOIN ( + SELECT FustCode, sum(quantity) stucks + FROM ( + SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk + LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id + WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) + AND wa.name = 'VNH' + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub + GROUP BY FustCode) sj ON sj.FustCode = p.id + WHERE sent.stucks + OR tp.stucks + OR sj.stucks; + +END$$ +DELIMITER ; + diff --git a/db/changes/234601/.gitkeep b/db/changes/234601/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/changes/234601/00-ACLticketTrackingState.sql b/db/changes/234601/00-ACLticketTrackingState.sql new file mode 100644 index 000000000..ca6dce0c9 --- /dev/null +++ b/db/changes/234601/00-ACLticketTrackingState.sql @@ -0,0 +1,4 @@ +UPDATE `salix`.`ACL` + SET `property` = 'state', + `model` = 'Ticket' + WHERE `property` = 'changeState'; diff --git a/db/changes/234601/00-addressShortage.sql b/db/changes/234601/00-addressShortage.sql new file mode 100644 index 000000000..57c07d480 --- /dev/null +++ b/db/changes/234601/00-addressShortage.sql @@ -0,0 +1,98 @@ + +-- Place your SQL code here + +ALTER TABLE `vn`.`productionConfig` ADD shortageAddressFk int(11) COMMENT 'Consignatario por defecto para añadir un item de alta'; +ALTER TABLE `vn`.`productionConfig` ADD CONSTRAINT productionConfig_FK FOREIGN KEY (shortageAddressFk) REFERENCES vn.address(id) ON DELETE RESTRICT ON UPDATE CASCADE; + +ALTER TABLE `vn`.`sale` MODIFY COLUMN originalQuantity double(9,1) DEFAULT NULL NULL COMMENT 'Se utiliza para notificar a través de rocket los cambios de quantity'; + +INSERT INTO `salix`.`ACL` ( model, property, accessType, permission, principalType, principalId) VALUES( 'AddressShortage', '*', 'READ', 'ALLOW', 'ROLE', 'production'); + +-- vn.addressShortage definition + +CREATE TABLE `vn`.`addressShortage` ( + `addressFk` int(11) NOT NULL, + PRIMARY KEY (`addressFk`), + CONSTRAINT `addressShortage_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + + +DELIMITER $$ + +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDiscard`( + vItemFk INT, + vWarehouseFk INT, + vQuantity INT, + vAddressFk INT) +BEGIN +/** + * Procedimiento para dar dar de baja/alta un item, si vAddressFk es NULL se entiende que se da de alta y se toma el addressFk de la configuración + * + * @param vItemFk Identificador del ítem + * @param vWarehouseFk id del warehouse + * @param vQuantity a dar de alta/baja + * @param vAddressFk id address + */ + DECLARE vTicketFk INT; + DECLARE vClientFk INT; + DECLARE vDefaultCompanyFk INT; + DECLARE vCalc INT; + DECLARE vAddressShortage INT; + + SELECT barcodeToItem(vItemFk) INTO vItemFk; + + SELECT DEFAULT(companyFk) INTO vDefaultCompanyFk + FROM vn.ticket LIMIT 1; + + IF vAddressFk IS NULL THEN + SELECT pc.shortageAddressFk INTO vAddressShortage + FROM productionConfig pc ; + ELSE + SET vAddressShortage = vAddressFk; + END IF; + + SELECT a.clientFk INTO vClientFk + FROM address a + WHERE a.id = vAddressFk; + + SELECT t.id INTO vTicketFk + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN ticketState ts ON ts.ticketFk = t.id + WHERE t.warehouseFk = vWarehouseFk + AND a.id = vAddressShortage + AND DATE(t.shipped) = util.VN_CURDATE() + AND ts.code = 'DELIVERED' + LIMIT 1; + + CALL cache.visible_refresh(vCalc, TRUE, vWarehouseFk); + + IF vTicketFk IS NULL THEN + CALL ticket_add( + vClientFk, + util.VN_CURDATE(), + vWarehouseFk, + vDefaultCompanyFk, + vAddressFk, + NULL, + NULL, + util.VN_CURDATE(), + account.myUser_getId(), + FALSE, + vTicketFk); + END IF; + + INSERT INTO sale(ticketFk, itemFk, concept, quantity) + SELECT vTicketFk, + vItemFk, + CONCAT(longName,' ', worker_getCode(), ' ', LEFT(CAST(util.VN_NOW() AS TIME),5)), + vQuantity + FROM item + WHERE id = vItemFk; + + UPDATE cache.visible + SET visible = visible - vQuantity + WHERE calc_id = vCalc + AND item_id = vItemFk; +END$$ +DELIMITER ; diff --git a/db/changes/233601/00-createClaimReader.sql b/db/changes/234601/00-claimViewerAcl.sql similarity index 86% rename from db/changes/233601/00-createClaimReader.sql rename to db/changes/234601/00-claimViewerAcl.sql index e913c0ed9..17d8d4ce0 100644 --- a/db/changes/233601/00-createClaimReader.sql +++ b/db/changes/234601/00-claimViewerAcl.sql @@ -21,11 +21,11 @@ DELETE FROM `salix`.`ACL` 'getSummary' ); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Claim','filter','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Claim','find','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) VALUES ('Claim','findById','READ','ALLOW','ROLE','claimViewer'); -INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalid`) - VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); \ No newline at end of file +INSERT INTO `salix`.`ACL` (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Claim','getSummary','READ','ALLOW','ROLE','claimViewer'); diff --git a/db/changes/234601/00-clientAfterUpdate.sql b/db/changes/234601/00-clientAfterUpdate.sql new file mode 100644 index 000000000..c6483813f --- /dev/null +++ b/db/changes/234601/00-clientAfterUpdate.sql @@ -0,0 +1,95 @@ +ALTER TABLE `vn`.`client` MODIFY COLUMN `credit` decimal(10,2) unsigned DEFAULT 0.00 NOT NULL; + +DELETE FROM `salix`.`ACL` WHERE `model` = 'Client' AND `property` = 'create'; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_beforeUpdate` + BEFORE UPDATE ON `client` + FOR EACH ROW +BEGIN + DECLARE vText VARCHAR(255) DEFAULT NULL; + DECLARE vPayMethodFk INT; + + SET NEW.editorFk = account.myUser_getId(); + + IF NOT(NEW.credit <=> OLD.credit) THEN + INSERT INTO clientCredit + SET clientFk = NEW.id, + amount = NEW.credit, + workerFk = NEW.editorFk; + END IF; + -- Comprueba que el formato de los teléfonos es válido + + IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN + CALL pbx.phone_isValid(NEW.phone); + END IF; + + IF !(NEW.mobile <=> OLD.mobile) AND (NEW.mobile <> '')THEN + CALL pbx.phone_isValid(NEW.mobile); + END IF; + + SELECT id INTO vPayMethodFk + FROM vn.payMethod + WHERE code = 'bankDraft'; + + IF NEW.payMethodFk = vPayMethodFk AND NEW.dueDay = 0 THEN + SET NEW.dueDay = 5; + END IF; + + -- Avisar al comercial si ha llegado la documentación sepa/core + + IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN + SET vText = 'Sepa de VNL'; + END IF; + + IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN + SET vText = 'Core de VNL'; + END IF; + + IF vText IS NOT NULL + THEN + INSERT INTO mail(receiver, replyTo, `subject`, body) + SELECT + CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), + 'administracion@verdnatura.es', + CONCAT('Cliente ', NEW.id), + CONCAT('Recibida la documentación: ', vText) + FROM worker w + LEFT JOIN account.user u ON w.id = u.id AND u.active + LEFT JOIN account.account ac ON ac.id = u.id + WHERE w.id = NEW.salesPersonFk; + END IF; + + IF NEW.salespersonFk IS NULL AND OLD.salespersonFk IS NOT NULL THEN + IF (SELECT COUNT(clientFk) + FROM clientProtected + WHERE clientFk = NEW.id + ) > 0 THEN + CALL util.throw("HAS_CLIENT_PROTECTED"); + END IF; + END IF; + + IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN + SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); + END IF; + + IF !(NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN + SET NEW.isTaxDataChecked = 0; + END IF; +END$$ +DELIMITER ; + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`client_AfterInsert` + AFTER INSERT ON `client` + FOR EACH ROW +BEGIN + IF NEW.credit IS NOT NULL AND NEW.credit THEN + INSERT INTO clientCredit + SET clientFk = NEW.id, + workerFk = NEW.editorFk, + amount = NEW.credit; + END IF; +END$$ +DELIMITER ; + diff --git a/db/changes/234601/00-expeditionStateBeforeInsert.sql b/db/changes/234601/00-expeditionStateBeforeInsert.sql new file mode 100644 index 000000000..565b3ded3 --- /dev/null +++ b/db/changes/234601/00-expeditionStateBeforeInsert.sql @@ -0,0 +1,13 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`expeditionState_BeforeInsert` + BEFORE INSERT ON `expeditionState` + FOR EACH ROW +BEGIN + + SET NEW.userFk = IFNULL(NEW.userFk, account.myUser_getId()); + +END$$ +DELIMITER ; + + + diff --git a/db/changes/234601/00-ticketSetStateRefactor.sql b/db/changes/234601/00-ticketSetStateRefactor.sql new file mode 100644 index 000000000..9078ffb0e --- /dev/null +++ b/db/changes/234601/00-ticketSetStateRefactor.sql @@ -0,0 +1,55 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setState`( + vSelf INT, + vStateCode VARCHAR(255) COLLATE utf8_general_ci +) +BEGIN +/** + * Modifica el estado de un ticket si se cumplen las condiciones necesarias. + * + * @param vSelf el id del ticket + * @param vStateCode estado a modificar del ticket + */ + DECLARE vticketAlertLevel INT; + DECLARE vTicketStateCode VARCHAR(255); + DECLARE vCanChangeState BOOL; + DECLARE vPackedAlertLevel INT; + DECLARE vZoneFk INT; + + SELECT s.alertLevel, s.`code`, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vZoneFk + FROM state s + JOIN ticketTracking tt ON tt.stateFk = s.id + JOIN ticket t ON t.id = tt.ticketFk + WHERE tt.ticketFk = vSelf + ORDER BY tt.created DESC + LIMIT 1; + + SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; + + IF vStateCode = 'OK' AND vZoneFk IS NULL THEN + CALL util.throw('ASSIGN_ZONE_FIRST'); + END IF; + + SET vCanChangeState = ( + vStateCode <> 'ON_CHECKING' OR + vticketAlertLevel < vPackedAlertLevel + )AND NOT ( + vTicketStateCode IN ('CHECKED', 'CHECKING') + AND vStateCode IN ('PREPARED', 'ON_PREPARATION') + ); + + IF vCanChangeState THEN + INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) + SELECT id, vSelf, account.myUser_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_unicode_ci; + + IF vStateCode = 'PACKED' THEN + CALL ticket_doCmr(vSelf); + END IF; + ELSE + CALL util.throw('INCORRECT_TICKET_STATE'); + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/234601/00-transferInvoice.sql b/db/changes/234601/00-transferInvoice.sql new file mode 100644 index 000000000..7a9890ae4 --- /dev/null +++ b/db/changes/234601/00-transferInvoice.sql @@ -0,0 +1,6 @@ +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + ('CplusRectificationType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('CplusInvoiceType477', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceCorrectionType', '*', 'READ', 'ALLOW', 'ROLE', 'administrative'), + ('InvoiceOut', 'transferInvoice', 'WRITE', 'ALLOW', 'ROLE', 'administrative'); diff --git a/db/changes/234801/.gitkeep b/db/changes/234801/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 9be9d69f6..ae47a1eef 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -87,8 +87,8 @@ INSERT INTO `vn`.`educationLevel` (`id`, `name`) (1, 'ESTUDIOS PRIMARIOS COMPLETOS'), (2, 'ENSEÑANZAS DE BACHILLERATO'); -INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `userFk`, `bossFk`) - SELECT id,UPPER(LPAD(role, 3, '0')), name, name, id, 9 +INSERT INTO `vn`.`worker`(`id`,`code`, `firstName`, `lastName`, `bossFk`) + SELECT id,UPPER(LPAD(role, 3, '0')), name, name, 9 FROM `account`.`user`; UPDATE `vn`.`worker` SET bossFk = NULL WHERE id = 20; @@ -188,13 +188,13 @@ INSERT INTO `vn`.`printer` (`id`, `name`, `path`, `isLabeler`, `sectorFk`, `ipAd UPDATE `vn`.`sector` SET mainPrinterFk = 1 WHERE id = 1; -INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`, `userFk`,`bossFk`, `phone`) +INSERT INTO `vn`.`worker`(`id`, `code`, `firstName`, `lastName`,`bossFk`, `phone`) VALUES - (1106, 'LGN', 'David Charles', 'Haller', 1106, 19, 432978106), - (1107, 'ANT', 'Hank' , 'Pym' , 1107, 19, 432978107), - (1108, 'DCX', 'Charles' , 'Xavier', 1108, 19, 432978108), - (1109, 'HLK', 'Bruce' , 'Banner', 1109, 19, 432978109), - (1110, 'JJJ', 'Jessica' , 'Jones' , 1110, 19, 432978110); + (1106, 'LGN', 'David Charles', 'Haller', 19, 432978106), + (1107, 'ANT', 'Hank' , 'Pym' , 19, 432978107), + (1108, 'DCX', 'Charles' , 'Xavier', 19, 432978108), + (1109, 'HLK', 'Bruce' , 'Banner', 19, 432978109), + (1110, 'JJJ', 'Jessica' , 'Jones' , 19, 432978110); INSERT INTO `vn`.`parking` (`id`, `column`, `row`, `sectorFk`, `code`, `pickingOrder`) VALUES @@ -470,22 +470,22 @@ CREATE TEMPORARY TABLE tmp.address WHERE `defaultAddressFk` IS NULL; DROP TEMPORARY TABLE tmp.address; -INSERT INTO `vn`.`clientCredit`(`id`, `clientFk`, `workerFk`, `amount`, `created`) +INSERT INTO `vn`.`clientCredit`(`clientFk`, `workerFk`, `amount`, `created`) VALUES - (1 , 1101, 5, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 MONTH)), - (2 , 1101, 5, 900, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 MONTH)), - (3 , 1101, 5, 800, DATE_ADD(util.VN_CURDATE(), INTERVAL -9 MONTH)), - (4 , 1101, 5, 700, DATE_ADD(util.VN_CURDATE(), INTERVAL -8 MONTH)), - (5 , 1101, 5, 600, DATE_ADD(util.VN_CURDATE(), INTERVAL -7 MONTH)), - (6 , 1101, 5, 500, DATE_ADD(util.VN_CURDATE(), INTERVAL -6 MONTH)), - (7 , 1101, 5, 400, DATE_ADD(util.VN_CURDATE(), INTERVAL -5 MONTH)), - (8 , 1101, 9, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), - (9 , 1101, 9, 200, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), - (10, 1101, 9, 100, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), - (11, 1101, 9, 50 , DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), - (12, 1102, 9, 800, util.VN_CURDATE()), - (14, 1104, 9, 90 , util.VN_CURDATE()), - (15, 1105, 9, 90 , util.VN_CURDATE()); + (1101, 5, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 MONTH)), + (1101, 5, 900, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 MONTH)), + (1101, 5, 800, DATE_ADD(util.VN_CURDATE(), INTERVAL -9 MONTH)), + (1101, 5, 700, DATE_ADD(util.VN_CURDATE(), INTERVAL -8 MONTH)), + (1101, 5, 600, DATE_ADD(util.VN_CURDATE(), INTERVAL -7 MONTH)), + (1101, 5, 500, DATE_ADD(util.VN_CURDATE(), INTERVAL -6 MONTH)), + (1101, 5, 400, DATE_ADD(util.VN_CURDATE(), INTERVAL -5 MONTH)), + (1101, 9, 300, DATE_ADD(util.VN_CURDATE(), INTERVAL -4 MONTH)), + (1101, 9, 200, DATE_ADD(util.VN_CURDATE(), INTERVAL -3 MONTH)), + (1101, 9, 100, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), + (1101, 9, 50 , DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), + (1102, 9, 800, util.VN_CURDATE()), + (1104, 9, 90 , util.VN_CURDATE()), + (1105, 9, 90 , util.VN_CURDATE()); INSERT INTO `vn`.`clientCreditLimit`(`id`, `maxAmount`, `roleFk`) VALUES @@ -604,7 +604,7 @@ INSERT INTO `vn`.`invoiceOutSerial` (`code`, `description`, `isTaxed`, `taxAreaF INSERT INTO `vn`.`invoiceOut`(`id`, `serial`, `amount`, `issued`,`clientFk`, `created`, `companyFk`, `dued`, `booked`, `bankFk`, `hasPdf`) VALUES - (1, 'T', 1014.24, util.VN_CURDATE(), 1101, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), + (1, 'T', 1026.24, util.VN_CURDATE(), 1101, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (2, 'T', 121.36, util.VN_CURDATE(), 1102, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (3, 'T', 8.88, util.VN_CURDATE(), 1103, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), (4, 'T', 8.88, util.VN_CURDATE(), 1103, util.VN_CURDATE(), 442, util.VN_CURDATE(), util.VN_CURDATE(), 1, 0), @@ -1013,7 +1013,7 @@ INSERT INTO `vn`.`sale`(`id`, `itemFk`, `ticketFk`, `concept`, `quantity`, `pric (4, 4, 1, 'Melee weapon heavy shield 100cm', 20, 1.69, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (5, 1, 2, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), (6, 1, 3, 'Ranged weapon longbow 200cm', 1, 110.33, 0, 0, 0, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), - (7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.44, 0, 0, 0, util.VN_CURDATE()), + (7, 2, 11, 'Melee weapon combat fist 15cm', 15, 7.74, 0, 0, 0, util.VN_CURDATE()), (8, 4, 11, 'Melee weapon heavy shield 100cm', 10, 1.79, 0, 0, 0, util.VN_CURDATE()), (9, 1, 16, 'Ranged weapon longbow 200cm', 1, 103.49, 0, 0, 0, util.VN_CURDATE()), (10, 2, 16, 'Melee weapon combat fist 15cm', 10, 7.09, 0, 0, 0, util.VN_CURDATE()), @@ -1409,10 +1409,8 @@ INSERT INTO `cache`.`cache_calc`(`id`, `cache_id`, `cacheName`, `params`, `last_ INSERT INTO `vn`.`ticketWeekly`(`ticketFk`, `weekDay`) VALUES - (1, 0), (2, 1), (3, 2), - (4, 4), (5, 6), (15, 6); @@ -1456,7 +1454,7 @@ INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeF ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Miscellaneous Accessories', 6, 1, '186', '0', '0.0'), ('HankPym', YEAR(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK)), WEEK(DATE_ADD(util.VN_CURDATE(), INTERVAL -1 WEEK), 1), 'Adhesives', 7, 1, '277', '0', '0.0'); -INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packageFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) +INSERT INTO `vn`.`buy`(`id`,`entryFk`,`itemFk`,`buyingValue`,`quantity`,`packagingFk`,`stickers`,`freightValue`,`packageValue`,`comissionValue`,`packing`,`grouping`,`groupingMode`,`location`,`price1`,`price2`,`price3`, `printedStickers`,`isChecked`,`isIgnored`,`weight`, `created`) VALUES (1, 1, 1, 50, 5000, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -2 MONTH)), (2, 2, 1, 50, 100, 4, 1, 1.500, 1.500, 0.000, 1, 1, 1, NULL, 0.00, 99.6, 99.4, 0, 1, 0, 1, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH)), @@ -2005,6 +2003,10 @@ UPDATE `vn`.`business` b SET b.`departmentFk` = 43 WHERE b.id IN(18, 19); +UPDATE `vn`.`business` b + SET b.`started` = b.`started` - INTERVAL 100 DAY + WHERE b.id = 1107; + INSERT INTO `vn`.`workCenterHoliday` (`workCenterFk`, `days`, `year`) VALUES ('1', '27.5', YEAR(util.VN_CURDATE())), @@ -2053,22 +2055,22 @@ INSERT INTO `vn`.`absenceType` (`id`, `name`, `rgb`, `code`, `holidayEntitlement INSERT INTO `vn`.`calendar` (`businessFk`, `dayOffTypeFk`, `dated`) VALUES - (1, 6, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 10 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 10 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 11 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -12 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 12 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -20 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 20 DAY))), - (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -13 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 8 DAY))), - (1106, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -14 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 9 DAY))), - (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -15 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 7 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -10 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 10 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -11 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 11 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -12 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 12 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, DATE_ADD(util.VN_CURDATE(), INTERVAL -20 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 20 DAY))), - (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -13 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 8 DAY))), - (1107, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -14 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 9 DAY))), - (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, DATE_ADD(util.VN_CURDATE(), INTERVAL -15 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL 7 DAY))), - (1107, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL - 16 DAY)); + (1, 6, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 10 DAY, util.VN_CURDATE() + INTERVAL 10 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 10 DAY, util.VN_CURDATE() + INTERVAL 10 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 11 DAY, util.VN_CURDATE() + INTERVAL 11 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 12 DAY, util.VN_CURDATE() + INTERVAL 12 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 20 DAY, util.VN_CURDATE() + INTERVAL 20 DAY)), + (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 13 DAY, util.VN_CURDATE() + INTERVAL 8 DAY)), + (1106, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 14 DAY, util.VN_CURDATE() + INTERVAL 9 DAY)), + (1106, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 15 DAY, util.VN_CURDATE() + INTERVAL 7 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 10 DAY, util.VN_CURDATE() + INTERVAL 10 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 11 DAY, util.VN_CURDATE() + INTERVAL 11 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 12 DAY, util.VN_CURDATE() + INTERVAL 12 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) = 12 AND DAY(util.VN_CURDATE()) > 10, util.VN_CURDATE() - INTERVAL 20 DAY, util.VN_CURDATE() + INTERVAL 20 DAY)), + (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 13 DAY, util.VN_CURDATE() + INTERVAL 8 DAY)), + (1107, 1, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 14 DAY, util.VN_CURDATE() + INTERVAL 9 DAY)), + (1107, 2, IF(MONTH(util.VN_CURDATE()) >= 1 AND DAY(util.VN_CURDATE()) > 20, util.VN_CURDATE() - INTERVAL 15 DAY, util.VN_CURDATE() + INTERVAL 7 DAY)), + (1107, 2, util.VN_CURDATE() - INTERVAL 16 DAY); INSERT INTO `vn`.`smsConfig` (`id`, `uri`, `title`, `apiKey`) VALUES @@ -2756,9 +2758,9 @@ INSERT INTO `vn`.`sectorCollectionSaleGroup` (`sectorCollectionFk`, `saleGroupFk VALUES (1, 1); -INSERT INTO `vn`.`workerTimeControlConfig` (`id`, `dayBreak`, `dayBreakDriver`, `shortWeekBreak`, `longWeekBreak`, `weekScope`, `mailPass`, `mailHost`, `mailSuccessFolder`, `mailErrorFolder`, `mailUser`, `minHoursToBreak`, `breakHours`, `hoursCompleteWeek`, `startNightlyHours`, `endNightlyHours`, `maxTimePerDay`, `breakTime`, `timeToBreakTime`, `dayMaxTime`, `shortWeekDays`, `longWeekDays`, `teleworkingStart`, `teleworkingStartBreakTime`) +INSERT INTO `vn`.`workerTimeControlConfig` (`id`, `dayBreak`, `dayBreakDriver`, `shortWeekBreak`, `longWeekBreak`, `weekScope`, `mailPass`, `mailHost`, `mailSuccessFolder`, `mailErrorFolder`, `mailUser`, `minHoursToBreak`, `breakHours`, `hoursCompleteWeek`, `startNightlyHours`, `endNightlyHours`, `maxTimePerDay`, `breakTime`, `timeToBreakTime`, `dayMaxTime`, `shortWeekDays`, `longWeekDays`, `teleworkingStart`, `teleworkingStartBreakTime`, `maxTimeToBreak`, `maxWorkShortCycle`, `maxWorkLongCycle`) VALUES - (1, 43200, 32400, 129600, 259200, 604800, '', '', 'Leidos.exito', 'Leidos.error', 'timeControl', 5.33, 0.33, 40, '22:00:00', '06:00:00', 57600, 1200, 18000, 57600, 6, 13, 28800, 32400); + (1, 43200, 32400, 129600, 259200, 1080000, '', 'imap.verdnatura.es', 'Leidos.exito', 'Leidos.error', 'timeControl', 5.00, 0.33, 40, '22:00:00', '06:00:00', 72000, 1200, 18000, 72000, 6, 13, 28800, 32400, 3600, 561600, 950400); INSERT INTO `vn`.`host` (`id`, `code`, `description`, `warehouseFk`, `bankFk`) VALUES @@ -2834,24 +2836,24 @@ UPDATE `account`.`user` INSERT INTO `vn`.`ticketLog` (`originFk`, userFk, `action`, changedModel, oldInstance, newInstance, changedModelId, `description`) VALUES - (7, 18, 'update', 'Sale', '{"quantity":1}', '{"quantity":10}', 1, NULL), - (7, 18, 'update', 'Ticket', '{"quantity":1,"concept":"Chest ammo box"}', '{"quantity":10,"concept":"Chest ammo box"}', 1, NULL), - (7, 18, 'update', 'Sale', '{"price":3}', '{"price":5}', 1, NULL), + (7, 18, 'update', 'Sale', '{"quantity":1}', '{"quantity":10}', 22, NULL), + (7, 18, 'update', 'Ticket', '{"quantity":1,"concept":"Chest ammo box"}', '{"quantity":10,"concept":"Chest ammo box"}', 22, NULL), + (7, 18, 'update', 'Sale', '{"price":3}', '{"price":5}', 22, NULL), (7, 18, 'update', NULL, NULL, NULL, NULL, "Cambio cantidad Melee weapon heavy shield 100cm de '5' a '10'"), - (16, 9, 'update', 'Sale', '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', '{"quantity":8,"concept":"Shield", "price": 10.5, "itemFk": 1}' , 5689, 'Shield'); + (16, 9, 'update', 'Sale', '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', '{"quantity":8,"concept":"Shield", "price": 10.5, "itemFk": 1}' , 12, 'Shield'); INSERT INTO `vn`.`ticketLog` (originFk, userFk, `action`, creationDate, changedModel, changedModelId, changedModelValue, oldInstance, newInstance, description) VALUES (1, NULL, 'delete', '2001-06-09 11:00:04', 'Ticket', 45, 'Spider Man' , NULL, NULL, NULL), (1, 18, 'select', '2001-06-09 11:00:03', 'Ticket', 45, 'Spider Man' , NULL, NULL, NULL), - (1, NULL, 'update', '2001-05-09 10:00:02', 'Sale', 69854, 'Armor' , '{"isPicked": false}','{"isPicked": true}', NULL), - (1, 18, 'update', '2001-01-01 10:05:01', 'Sale', 69854, 'Armor' , NULL, NULL, 'Armor quantity changed from ''15'' to ''10'''), - (1, NULL, 'delete', '2001-01-01 10:00:10', 'Sale', 5689, 'Shield' , '{"quantity":10,"concept":"Shield"}', NULL, NULL), - (1, 18, 'insert', '2000-12-31 15:00:05', 'Sale', 69854, 'Armor' , NULL,'{"quantity":15,"concept":"Armor", "price": 345.99, "itemFk": 2}', NULL), + (1, NULL, 'update', '2001-05-09 10:00:02', 'Sale', 5, 'Armor' , '{"isPicked": false}','{"isPicked": true}', NULL), + (1, 18, 'update', '2001-01-01 10:05:01', 'Sale', 5, 'Armor' , NULL, NULL, 'Armor quantity changed from ''15'' to ''10'''), + (1, NULL, 'delete', '2001-01-01 10:00:10', 'Sale', 4, 'Shield' , '{"quantity":10,"concept":"Shield"}', NULL, NULL), + (1, 18, 'insert', '2000-12-31 15:00:05', 'Sale', 1, 'Armor' , NULL,'{"quantity":15,"concept":"Armor", "price": 345.99, "itemFk": 2}', NULL), (1, 18, 'update', '2000-12-28 08:40:45', 'Ticket', 45, 'Spider Man' , '{"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"isBlocked":false,"hasPriority":false,"companyFk":442,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}','{"warehouseFk":61,"shipped":"2023-05-17T22:00:00.000Z","nickname":"Spider Man","isSigned":false,"isLabeled":false,"isPrinted":false,"packages":1,"hour":0,"isBlocked":true,"hasPriority":true,"companyFk":443,"landed":"2023-05-18T22:00:00.000Z","isBoxed":false,"isDeleted":false,"zoneFk":713,"zonePrice":13,"zoneBonus":1}', NULL), (1, 18, 'select', '2000-12-27 03:40:30', 'Ticket', 45, NULL , NULL, NULL, NULL), - (1, 18, 'insert', '2000-04-10 09:40:15', 'Sale', 5689, 'Shield' , NULL, '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', NULL), + (1, 18, 'insert', '2000-04-10 09:40:15', 'Sale', 4, 'Shield' , NULL, '{"quantity":10,"concept":"Shield", "price": 10.5, "itemFk": 1}', NULL), (1, 18, 'insert', '1999-05-09 10:00:00', 'Ticket', 45, 'Super Man' , NULL, '{"id":45,"clientFk":8608,"warehouseFk":60,"shipped":"2023-05-16T22:00:00.000Z","nickname":"Super Man","addressFk":48637,"isSigned":true,"isLabeled":true,"isPrinted":true,"packages":0,"hour":0,"created":"2023-05-16T11:42:56.000Z","isBlocked":false,"hasPriority":false,"companyFk":442,"agencyModeFk":639,"landed":"2023-05-17T22:00:00.000Z","isBoxed":true,"isDeleted":true,"zoneFk":713,"zonePrice":13,"zoneBonus":0}', NULL); INSERT INTO `vn`.`osTicketConfig` (`id`, `host`, `user`, `password`, `oldStatus`, `newStatusId`, `day`, `comment`, `hostDb`, `userDb`, `passwordDb`, `portDb`, `responseType`, `fromEmailId`, `replyTo`) VALUES @@ -2869,6 +2871,7 @@ INSERT INTO `vn`.`profileType` (`id`, `name`) INSERT INTO `salix`.`url` (`appName`, `environment`, `url`) VALUES ('lilium', 'development', 'http://localhost:9000/#/'), + ('hedera', 'development', 'http://localhost:9090/'), ('salix', 'development', 'http://localhost:5000/#!/'); INSERT INTO `vn`.`report` (`id`, `name`, `paperSizeFk`, `method`) @@ -2974,5 +2977,13 @@ INSERT INTO vn.XDiario (id, ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EU (4, 2.0, util.VN_CURDATE(), '4300001104', NULL, 'n/fra T4444444', 8.88, NULL, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (5, 2.0, util.VN_CURDATE(), '2000000000', '4300001104', 'n/fra T4444444 Tony Stark', NULL, 8.07, NULL, NULL, '0', NULL, 0.00, NULL, NULL, NULL, NULL, NULL, '2', NULL, 1, 2, 'I.F.', 'Nombre Importador', 1, 0, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0), (6, 2.0, util.VN_CURDATE(), '4770000010', '4300001104', 'Inmovilizado pendiente : n/fra T4444444 Tony Stark', NULL, 0.81, 8.07, 'T', '4444444', 10.00, NULL, NULL, NULL, NULL, NULL, '', '2', '', 1, 1, '06089160W', 'IRON MAN', 1, 1, 0, util.VN_CURDATE(), 0, 442, 0, 0, 0.00, NULL, NULL, util.VN_CURDATE(), NULL, 1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 0, NULL, NULL, 0); - - \ No newline at end of file + +INSERT INTO `vn`.`mistakeType` (`id`, `description`) + VALUES + (1, 'Incorrect quantity'); + +INSERT INTO `vn`.`invoiceCorrectionType` (`id`, `description`) + VALUES + (1, 'Error in VAT calculation'), + (2, 'Error in sales details'), + (3, 'Error in customer data'); diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 218d1c183..b242821fc 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -787,7 +787,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + CALL user_checkName(NEW.`name`); IF NEW.nickname = '' THEN @@ -1018,7 +1018,7 @@ BEGIN SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); RETURN vSignature = @userSignature; END IF; - + RETURN FALSE; END ;; @@ -1047,7 +1047,7 @@ BEGIN * @return The user id */ DECLARE vUser INT DEFAULT NULL; - + IF myUser_checkLogin() THEN SET vUser = @userId; @@ -1055,7 +1055,7 @@ BEGIN SELECT id INTO vUser FROM user WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -1090,7 +1090,7 @@ BEGIN ELSE SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); END IF; - + RETURN vUser; END ;; DELIMITER ; @@ -1185,10 +1185,10 @@ BEGIN DECLARE vDigitChars TEXT DEFAULT '1234567890'; DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; - SELECT length, nAlpha, nUpper, nDigits, nPunct + SELECT length, nAlpha, nUpper, nDigits, nPunct INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha + WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO SET vRandIndex = FLOOR((RAND() * 4) + 1); @@ -1263,7 +1263,7 @@ BEGIN DECLARE vRole VARCHAR(255); SELECT CONCAT(IF(r.hasLogin, c.rolePrefix, ''), r.name) INTO vRole - FROM role r + FROM role r JOIN user u ON u.role = r.id JOIN roleConfig c WHERE u.name = vUserName; @@ -1290,16 +1290,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `user_getNameFromId`(vSelf INT) RETUR BEGIN /** * Gets user name from it's id. - * + * * @param vSelf The user id * @return The user name */ DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user + + SELECT `name` INTO vName + FROM user WHERE id = vSelf; - + RETURN vName; END ;; DELIMITER ; @@ -1371,7 +1371,7 @@ BEGIN JOIN role r ON r.id = rr.inheritsFrom WHERE u.`name` = vUser AND r.id = vRoleId; - + RETURN vHasRole; END ;; DELIMITER ; @@ -1405,7 +1405,7 @@ BEGIN AND password = MD5(vPassword) AND active; - IF vAuthIsOk + IF vAuthIsOk THEN CALL myUser_loginWithName (vUserName); ELSE @@ -1466,7 +1466,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_loginWithName`(vUserName VAR BEGIN /** * Logs in using only the user name. This procedure is intended to be executed - * by users with a high level of privileges so that normal users should not have + * by users with a high level of privileges so that normal users should not have * execute permissions on it. * * @param vUserName The user name @@ -1502,7 +1502,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `myUser_logout`() BEGIN /** * Logouts the user. - */ + */ SET @userId = NULL; SET @userName = NULL; SET @userSignature = NULL; @@ -1600,9 +1600,9 @@ BEGIN SELECT COUNT(*) > 0 INTO vIsRoot FROM tmp.role t - JOIN role r ON r.id = t.id + JOIN role r ON r.id = t.id WHERE r.`name` = 'root'; - + IF vIsRoot THEN INSERT IGNORE INTO tmp.role (id) SELECT id FROM role; @@ -2321,7 +2321,7 @@ BEGIN IF vChr REGEXP '[[:alpha:]]' THEN SET vNAlpha = vNAlpha+1; - + IF vChr REGEXP '[A-Z]' THEN SET vNUpper = vNUpper+1; @@ -2792,7 +2792,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -2818,7 +2818,7 @@ BEGIN IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - + END IF; END */;; @@ -3341,11 +3341,11 @@ BEGIN DECLARE vTramo VARCHAR(20); DECLARE vHour INT; - + SET vHour = HOUR(vDateTime) ; - + SET vTramo = - CASE + CASE WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' END ; @@ -3373,7 +3373,7 @@ BEGIN * Inserta en la tabla bancos_evolution los saldos acumulados de cada banco * * @param vStartingDate Fecha desde la cual se recalculan la tabla bs.bancos_evolution - */ + */ DECLARE vCurrentDate DATE; DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, util.VN_CURDATE()); IF IFNULL(vStartingDate,0) < TIMESTAMPADD(YEAR, -5, util.VN_CURDATE()) THEN @@ -3387,49 +3387,49 @@ BEGIN SELECT vCurrentDate, Id_Banco, deuda FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate); - + WHILE vCurrentDate < vMaxDate DO -- insertar solo el dia de ayer INSERT INTO bs.bancos_evolution(Fecha ,Id_Banco, saldo) - SELECT vCurrentDate, Id_Banco, SUM(saldo) + SELECT vCurrentDate, Id_Banco, SUM(saldo) FROM ( SELECT Id_Banco ,saldo FROM bs.bancos_evolution WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior UNION ALL - + SELECT c.Id_Banco, IFNULL(SUM(Entrada),0) - IFNULL(SUM(Salida),0) as saldo FROM vn2008.Cajas c JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND Cajafecha = vCurrentDate AND (Serie = 'MB' OR at2.code = 'fundingLine') GROUP BY Id_Banco - )sub + )sub GROUP BY Id_Banco ON DUPLICATE KEY UPDATE saldo = saldo + VALUES(saldo); - + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); END WHILE; - -- Ahora actualizamos la quilla + -- Ahora actualizamos la quilla UPDATE bs.bancos_evolution be JOIN ( SELECT bp.Id_Banco, - sum(bp.importe) as quilla, t.dated - FROM vn.time t + FROM vn.time t JOIN vn2008.Bancos_poliza bp ON t.dated between apertura AND IFNULL(cierre, t.dated) WHERE t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY Id_Banco, t.dated ) sub ON be.Id_Banco = sub.Id_Banco AND sub.dated = be.Fecha - SET be.quilla = sub.quilla; + SET be.quilla = sub.quilla; -- pagos futuros no concilidados INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, p.id_banco, - importe - FROM vn.time t + FROM vn.time t join vn2008.pago p ON p.fecha <= t.dated WHERE t.dated BETWEEN util.VN_CURDATE() AND vMaxDate AND p.fecha BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3439,7 +3439,7 @@ BEGIN -- cobros futuros INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, r.Id_Banco, SUM(Entregado) - FROM vn.time t + FROM vn.time t JOIN vn2008.Recibos r ON r.Fechacobro <= t.dated WHERE r.Fechacobro > util.VN_CURDATE() AND r.Fechacobro <= vMaxDate AND t.dated BETWEEN util.VN_CURDATE() AND vMaxDate @@ -3449,10 +3449,10 @@ BEGIN -- saldos de la tabla prevision INSERT INTO bs.bancos_evolution(Fecha, Id_Banco, saldo) SELECT t.dated, sp.Id_Banco, SUM(Importe) - FROM vn.time t + FROM vn.time t JOIN vn2008.Saldos_Prevision sp ON sp.Fecha <= t.dated JOIN vn2008.Bancos b ON sp.Id_Banco = b.Id_Banco - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash WHERE at2.code IN ('wireTransfer','fundingLine') AND t.dated BETWEEN vStartingDate AND vMaxDate GROUP BY t.dated, sp.Id_Banco @@ -3466,12 +3466,12 @@ BEGIN -- Deuda UPDATE bs.bancos_evolution be JOIN vn2008.Bancos b using(Id_Banco) - JOIN vn.accountingType at2 ON at2.id = b.cash + JOIN vn.accountingType at2 ON at2.id = b.cash SET be.deuda = IF(at2.code = 'fundingLine', be.saldo_aux, 0) , be.saldo = IF(at2.code = 'fundingLine', 0, be.saldo_aux) WHERE Fecha >= vStartingDate; - -- Liquidez + -- Liquidez update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; -- Disponibilidad update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; @@ -3494,14 +3494,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount + SELECT + workerName, + id, + name, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount FROM ( - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3510,11 +3510,11 @@ BEGIN FROM bs.ventas v INNER JOIN vn.`client` c ON v.Id_Cliente = c.id INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) GROUP BY w.id, v.Id_Cliente) UNION ALL - (SELECT + (SELECT CONCAT(w.firstname, ' ', w.lastName) AS workerName, c.id, c.name, @@ -3548,21 +3548,21 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `carteras_add`() -BEGIN -/** - * Inserta en @bs.carteras. - */ - DELETE FROM bs.carteras - WHERE Año >= YEAR(util.VN_CURDATE()) - 1; - - INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) - SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso - FROM vn.time t - JOIN bs.ventas v on t.dated = v.fecha - JOIN vn.client c on c.id = v.Id_Cliente - JOIN vn.worker w ON w.id = c.salesPersonFk - WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 - GROUP BY w.code, t.year , t.month; +BEGIN +/** + * Inserta en @bs.carteras. + */ + DELETE FROM bs.carteras + WHERE Año >= YEAR(util.VN_CURDATE()) - 1; + + INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) + SELECT t.year AS Año, t.month AS Mes, w.code AS CodigoTrabajador, SUM(v.importe) AS Peso + FROM vn.time t + JOIN bs.ventas v on t.dated = v.fecha + JOIN vn.client c on c.id = v.Id_Cliente + JOIN vn.worker w ON w.id = c.salesPersonFk + WHERE t.year >= YEAR(util.VN_CURDATE()) - 1 + GROUP BY w.code, t.year , t.month; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3594,24 +3594,24 @@ BEGIN DELETE FROM bs.clientNewBorn WHERE lastShipped < vOneYearAgo; - + DELETE FROM ventas WHERE fecha < vFourYearsAgo; - + DELETE FROM payMethodClient WHERE dated < vOneYearAgo; DELETE FROM payMethodClientEvolution WHERE dated < vFourYearsAgo; - DELETE FROM bs.salesByclientSalesPerson + DELETE FROM bs.salesByclientSalesPerson WHERE dated < vFourYearsAgo; - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha < vTwoYearAgo; DELETE FROM salesByItemTypeDay - WHERE dated < vThreeYearAgo; + WHERE dated < vThreeYearAgo; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3710,16 +3710,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `clientNewBorn_recalc`() BLOCK1: BEGIN DECLARE vClientFk INT; - DECLARE vShipped DATE; + DECLARE vShipped DATE; DECLARE vPreviousShipped DATE; - DECLARE vDone boolean; - DECLARE cur cursor for - - SELECT clientFk, firstShipped - FROM bs.clientNewBorn; - - DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; - SET vDone := FALSE; + DECLARE vDone boolean; + DECLARE cur cursor for + + SELECT clientFk, firstShipped + FROM bs.clientNewBorn; + + DECLARE continue HANDLER FOR NOT FOUND SET vDone = TRUE; + SET vDone := FALSE; DELETE FROM bs.clientNewBorn WHERE isModified = FALSE; @@ -3731,7 +3731,7 @@ BLOCK1: BEGIN WHERE t.shipped BETWEEN TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) AND util.VN_CURDATE() AND cb.isModified is null GROUP BY c.id; OPEN cur; - + LOOP1: LOOP SET vDone := FALSE; FETCH cur INTO vClientFk, vShipped; @@ -3742,37 +3742,37 @@ BLOCK1: BEGIN END IF; BLOCK2: BEGIN - DECLARE vCurrentShipped DATE; - DECLARE vDone2 boolean; + DECLARE vCurrentShipped DATE; + DECLARE vDone2 boolean; DECLARE cur2 CURSOR FOR - SELECT shipped - FROM vn.ticket + SELECT shipped + FROM vn.ticket WHERE clientFk = vClientFk AND shipped <= util.VN_CURDATE() ORDER BY shipped DESC; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone2 = TRUE; SET vDone2 := FALSE; OPEN cur2; - + SET vPreviousShipped := vShipped; LOOP2: LOOP SET vDone2 := FALSE; FETCH cur2 INTO vCurrentShipped; - + IF DATEDIFF(vPreviousShipped,vCurrentShipped) > 365 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vPreviousShipped + UPDATE bs.clientNewBorn + SET firstShipped = vPreviousShipped WHERE clientFk= vClientFk; - + CLOSE cur2; - LEAVE LOOP2; + LEAVE LOOP2; END IF; - + SET vPreviousShipped := vCurrentShipped; IF vDone2 THEN - UPDATE bs.clientNewBorn - SET firstShipped = vCurrentShipped + UPDATE bs.clientNewBorn + SET firstShipped = vCurrentShipped WHERE clientFk= vClientFk; CLOSE cur2; LEAVE LOOP2; @@ -3782,14 +3782,14 @@ BLOCK1: BEGIN END BLOCK2; END LOOP LOOP1; - UPDATE bs.clientNewBorn cnb + UPDATE bs.clientNewBorn cnb LEFT JOIN (SELECT DISTINCT t.clientFk FROM vn.ticket t JOIN vn.productionConfig pc WHERE t.shipped BETWEEN util.VN_CURDATE() + INTERVAL -(`notBuyingMonths`) MONTH AND util.VN_CURDATE() + INTERVAL -(`pc`.`rookieDays`) DAY) notRookie ON notRookie.clientFk = cnb.clientFk - SET cnb.isRookie = ISNULL(notRookie.clientFk); - + SET cnb.isRookie = ISNULL(notRookie.clientFk); + END BLOCK1 ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3810,16 +3810,16 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `comercialesCompleto`(IN vWorker INT BEGIN DECLARE vAYearAgoStarted DATE DEFAULT DATE_FORMAT(TIMESTAMPADD(YEAR, - 1, vDate), '%Y-%m-01'); DECLARE vAYearAgoEnded DATE DEFAULT TIMESTAMPADD(YEAR, - 1, LAST_DAY(vDate)); - + CALL vn.worker_GetHierarchy(vWorker); - + INSERT IGNORE INTO tmp.workerHierarchyList (workerFk) SELECT wd2.workerFk FROM vn.workerDepartment wd2 WHERE wd2.workerFk = vWorker; - + -- Falta que en algunos casos solo tenga en cuenta los tipos afectados. - SELECT + SELECT c.Id_Cliente id_cliente, c.Cliente cliente, cr.recobro * 100 tarifa, @@ -3844,7 +3844,7 @@ BEGIN FROM vn2008.Clientes c LEFT JOIN - (SELECT g.Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + (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 LEFT JOIN vn.worker w ON c.salesPersonFk = w.id @@ -3866,14 +3866,14 @@ BEGIN WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente LEFT JOIN - (SELECT + (SELECT Id_Cliente, SUM(importe) consumo FROM bs.ventas v INNER JOIN vn2008.Clientes c USING (Id_Cliente) LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente LEFT JOIN @@ -3934,17 +3934,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_add`(IN vYear INT, IN v BEGIN /** * Sustituye los registros de "bs.compradores". - * + * * @param vYear: año ventas * @param vWeekFrom: semana desde * @param vWeekTo: semana hasta */ REPLACE bs.compradores - SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision + SELECT it.workerFk AS Id_Trabajador, vYear AS año, tm.week AS semana, SUM(importe) AS importe, 0 AS comision FROM bs.ventas v JOIN vn.time tm ON tm.dated = v.fecha - JOIN vn.itemType it ON it.id = v.tipo_id - WHERE tm.year = vYear + JOIN vn.itemType it ON it.id = v.tipo_id + WHERE tm.year = vYear AND tm.week BETWEEN vWeekFrom AND vWeekTo AND it.categoryFk != 6 GROUP BY it.workerFk, tm.week; @@ -3970,22 +3970,22 @@ BEGIN DECLARE vYear INT; DECLARE vWeek INT; DECLARE done BOOL DEFAULT FALSE; - + DECLARE rs CURSOR FOR SELECT year, week FROM vn.time - WHERE dated <= util.VN_CURDATE() - AND year = vYear + WHERE dated <= util.VN_CURDATE() + AND year = vYear AND week >= vWeek; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear + + SELECT MAX(año) INTO vYear FROM compradores; - + SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; + FROM compradores + WHERE año = vYear; OPEN rs; @@ -3994,7 +3994,7 @@ BEGIN WHILE NOT done DO CALL compradores_add(vYear, vWeek, vWeek); - + FETCH rs INTO vYear, vWeek; END WHILE; @@ -4002,7 +4002,7 @@ BEGIN CLOSE rs; CALL compradores_evolution_add; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4023,17 +4023,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `compradores_evolution_add`() BEGIN /** * Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - * + * */ DECLARE vDated DATE; DECLARE vCount INT DEFAULT 1; - SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated + SELECT MAX(fecha) + INTERVAL 1 DAY INTO vDated FROM compradores_evolution; IF vDated IS NULL THEN - - SELECT MIN(dated) INTO vDated + + SELECT MIN(dated) INTO vDated FROM sale; INSERT INTO compradores_evolution( @@ -4054,7 +4054,7 @@ BEGIN WHILE vDated < util.VN_CURDATE() DO SET vCount = vCount + 1; - + REPLACE compradores_evolution( Id_Trabajador, fecha, @@ -4066,18 +4066,18 @@ BEGIN SELECT Id_Trabajador, importe FROM compradores_evolution JOIN ( - SELECT DISTINCT it.workerFk - FROM vn.itemType it + SELECT DISTINCT it.workerFk + FROM vn.itemType it )sub2 ON sub2.workerFk = Id_Trabajador - WHERE fecha = vDated - INTERVAL 1 DAY + WHERE fecha = vDated - INTERVAL 1 DAY UNION ALL - SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) + SELECT it.workerFk, s.amount * IF(s.dated < vDated, -1, 1) FROM sale s JOIN vn.itemType it ON it.id = s.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE s.dated IN (vDated, vDated - INTERVAL 1 YEAR) AND ic.merchandise - )sub + )sub GROUP BY Id_Trabajador; SET vDated = vDated + INTERVAL 1 DAY; @@ -4104,49 +4104,49 @@ BEGIN * Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias */ DECLARE datFEC DATE DEFAULT '2015-01-01'; - - SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) - INTO datFEC + + SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) + INTO datFEC FROM bs.fondo_maniobra; - + WHILE datFEC < util.VN_CURDATE() DO - + IF DAY(datFEC) MOD 28 = 0 THEN -- esto solo sirve para no aburrirse mientras esperamos... SELECT datFEC; END IF; - + REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) SELECT datFEC AS Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos FROM ( SELECT SUM(io.amount) AS Facturas FROM vn.invoiceOut io - JOIN vn.client c ON io.clientFk = c.id + JOIN vn.client c ON io.clientFk = c.id WHERE c.isRelevant - AND io.companyFk <> 1381 + AND io.companyFk <> 1381 AND io.issued BETWEEN '2011-01-01' AND datFEC ) fac JOIN ( SELECT - SUM(r.amountPaid) AS Cobros - FROM vn.receipt r - JOIN vn.client c ON r.clientFk = c.id - WHERE c.isRelevant + FROM vn.receipt r + JOIN vn.client c ON r.clientFk = c.id + WHERE c.isRelevant AND r.companyFk <> 1381 AND r.payed BETWEEN '2011-01-01' AND datFEC ) cob JOIN ( SELECT - SUM(id.amount) AS Recibidas - FROM vn.invoiceIn ii - JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk + FROM vn.invoiceIn ii + JOIN vn.invoiceInDueDay id ON ii.id = id.invoiceInFk WHERE ii.companyFk <> 1381 AND ii.issued BETWEEN '2015-01-01' AND datFEC ) rec JOIN ( SELECT SUM(p.amount) AS Pagos - FROM vn.payment p - WHERE p.companyFk <>1381 + FROM vn.payment p + WHERE p.companyFk <>1381 AND p.received BETWEEN '2015-01-01' AND datFEC ) pag; - + UPDATE bs.fondo_maniobra JOIN ( SELECT AVG(fondo) AS media @@ -4154,7 +4154,7 @@ BEGIN WHERE fecha <= datFEC ) sub SET fondo_medio = media WHERE fecha = datFEC; - + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); END WHILE; @@ -4178,7 +4178,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fruitsEvolution`() BEGIN -select Id_Cliente, +select Id_Cliente, Cliente, count(semana) as semanas, (w.code IS NOT NULL) isWorker from ( select distinct v.Id_Cliente, c.name as Cliente, week(fecha, 3) as semana @@ -4219,40 +4219,40 @@ BEGIN -- Ventas totales del ultimo año UPDATE indicators - SET lastYearSales = + SET lastYearSales = (SELECT SUM(importe + recargo) FROM ventas v JOIN vn2008.empresa e ON e.id = v.empresa_id JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo WHERE fecha BETWEEN oneYearBefore AND vDated AND eg.grupo = 'Verdnatura' - ) + ) WHERE updated = vDated; - + -- Greuge total acumulado UPDATE indicators - SET totalGreuge = + SET totalGreuge = (SELECT SUM(amount) FROM vn.greuge WHERE shipped <= vDated - ) + ) WHERE updated = vDated; -- Tasa de morosidad con respecto a las ventas del último mes UPDATE indicators - SET latePaymentRate = - (SELECT SUM(amount) - FROM bi.defaulters + SET latePaymentRate = + (SELECT SUM(amount) + FROM bi.defaulters WHERE date = vDated AND amount > 0) / - (SELECT SUM(importe + recargo) - FROM ventas + (SELECT SUM(importe + recargo) + FROM ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) WHERE updated = vDated; -- Número de trabajadores activos UPDATE indicators - SET countEmployee = + SET countEmployee = (SELECT CAST(SUM(ct.hoursWeek) / 40 AS DECIMAL (10, 2)) FROM vn.business b JOIN vn.calendarType ct ON ct.id = b.calendarTypeFk @@ -4271,7 +4271,7 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias UPDATE indicators - SET lastMonthActiveClients = + SET lastMonthActiveClients = (SELECT COUNT(DISTINCT t.clientFk) FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4280,9 +4280,9 @@ BEGIN -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores UPDATE indicators - SET lastMonthLostClients = + SET lastMonthLostClients = (SELECT COUNT(lm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4299,9 +4299,9 @@ BEGIN -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores UPDATE indicators - SET lastMonthNewClients = + SET lastMonthNewClients = (SELECT COUNT(cm.clientFk) - FROM + FROM (SELECT DISTINCT t.clientFk FROM vn.ticket t WHERE t.shipped BETWEEN oneMonthBefore AND vDated @@ -4327,7 +4327,7 @@ BEGIN -- Cálculo de las ventas agrupado por semanas SELECT week INTO vWeek - FROM vn.time + FROM vn.time WHERE dated = vDated; TRUNCATE salesByWeek; @@ -4341,12 +4341,12 @@ BEGIN -- Indicador Ventas semana actual UPDATE indicators i - JOIN salesByWeek s ON s.week= vWeek + JOIN salesByWeek s ON s.week= vWeek AND s.year = YEAR(vDated) SET i.thisWeekSales = s.sales WHERE updated = vDated; - -- Indicador ventas semana actual en el año pasado + -- Indicador ventas semana actual en el año pasado UPDATE indicators i JOIN salesByWeek s ON s.week = vWeek AND s.year = YEAR(vDated)-1 @@ -4377,15 +4377,15 @@ BEGIN SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') INTO vDated FROM bs.indicators; - + WHILE vDated < util.VN_CURDATE() DO - + CALL indicatorsUpdate(vDated); - + SELECT TIMESTAMPADD(DAY,1,MAX(updated)) INTO vDated FROM bs.indicators; - + END WHILE; END ;; @@ -4414,7 +4414,7 @@ BEGIN DECLARE vCalc INT; DECLARE vWarehouseFk INT; - DECLARE cWarehouses CURSOR FOR + DECLARE cWarehouses CURSOR FOR SELECT id FROM vn.warehouse WHERE isInventory; @@ -4427,13 +4427,13 @@ BEGIN read_loop: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouseFk; - + IF vDone THEN LEAVE read_loop; END IF; - + CALL cache.visible_refresh(vCalc, FALSE, vWarehouseFk); - + CREATE OR REPLACE TEMPORARY TABLE tVisible SELECT itemFk, SUM(visible) totalVisible FROM vn.itemShelving ish @@ -4442,7 +4442,7 @@ BEGIN JOIN vn.sector sc ON sc.id = p.sectorFk WHERE sc.warehouseFk = vWarehouseFk GROUP BY itemFk; - + INSERT INTO inventoryDiscrepancyDetail( warehouseFk, itemFk, @@ -4514,15 +4514,15 @@ BEGIN DECLARE datSTART DATE; DECLARE datEND DATE; - + SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART FROM bs.m3; - + SET datEND = TIMESTAMPADD(DAY,-1,util.VN_CURDATE()); - - DELETE FROM bs.m3 + + DELETE FROM bs.m3 WHERE fecha >= datSTART; - + INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(s.quantity * ic.cm3delivery) / 1000000 AS m3, tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) @@ -4565,51 +4565,51 @@ BEGIN DECLARE vManaBankId INT; DECLARE vManaGreugeTypeId INT; - SELECT id INTO vManaId + SELECT id INTO vManaId FROM vn.component WHERE code = 'mana'; - - SELECT id INTO vManaAutoId + + SELECT id INTO vManaAutoId FROM vn.component WHERE code = 'autoMana'; - + SELECT id INTO vClaimManaId FROM vn.component WHERE code = 'manaClaim'; - - SELECT id INTO vManaBankId + + SELECT id INTO vManaBankId FROM vn.bank WHERE code = 'mana'; - - SELECT id INTO vManaGreugeTypeId + + SELECT id INTO vManaGreugeTypeId FROM vn.greugeType WHERE code = 'mana'; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; - + DELETE FROM vn.clientManaCache WHERE dated = vFromDated; SELECT IFNULL(MAX(dated), '2016-01-01') - INTO vFromDated + INTO vFromDated FROM vn.clientManaCache; WHILE timestampadd(DAY,30,vFromDated) < util.VN_CURDATE() DO SELECT timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO + timestampadd(DAY,-90,vFromDated) + INTO vToDated, vForDeleteDated; - + DELETE FROM vn.clientManaCache WHERE dated <= vForDeleteDated; INSERT INTO vn.clientManaCache(clientFk, mana, dated) - SELECT + SELECT Id_Cliente, cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM + vToDated as dated + FROM ( SELECT cs.Id_Cliente, Cantidad * Valor as mana FROM vn2008.Tickets t @@ -4617,20 +4617,20 @@ BEGIN JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento WHERE Id_Componente IN (vManaAutoId, vManaId, vClaimManaId) - AND t.Fecha > vFromDated + AND t.Fecha > vFromDated AND date(t.Fecha) <= vToDated UNION ALL SELECT r.Id_Cliente, - Entregado FROM vn2008.Recibos r WHERE Id_Banco = vManaBankId - AND Fechacobro > vFromDated + 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 > vFromDated AND Fecha <= vToDated UNION ALL SELECT clientFk, mana @@ -4641,7 +4641,7 @@ BEGIN HAVING Id_Cliente; SET vFromDated = vToDated; - + END WHILE; END ;; @@ -4662,22 +4662,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `manaSpellers_actualize`() BEGIN -/** - * Recalcula el valor del campo con el modificador de precio +/** + * Recalcula el valor del campo con el modificador de precio * para el componente de maná automático. */ - UPDATE vn.workerMana wm + UPDATE vn.workerMana wm JOIN ( - SELECT c.lastSalesPersonFk, + SELECT c.lastSalesPersonFk, FLOOR(SUM(s.amount) / 12) amount FROM salesByclientSalesPerson s JOIN vn.client c ON c.id = s.clientFk WHERE s.dated BETWEEN util.VN_CURDATE() - INTERVAL 1 YEAR AND util.VN_CURDATE() GROUP BY c.lastSalesPersonFk - )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk + )avgPortfolioWeight ON avgPortfolioWeight.lastSalesPersonFk = wm.workerFk JOIN vn.salespersonConfig spc SET wm.pricesModifierRate = GREATEST( - spc.manaMinRate, + spc.manaMinRate, LEAST(spc.manaMaxRate, ROUND( - wm.amount / avgPortfolioWeight.amount))); END ;; DELIMITER ; @@ -4710,8 +4710,8 @@ BEGIN DECLARE vId INT; DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask + SELECT id, `schema`, `procedure` + FROM nightTask WHERE finished <= util.VN_CURDATE() OR finished IS NULL ORDER BY `order`; @@ -4744,7 +4744,7 @@ BEGIN vError, vErrorCode ); - + IF vError IS NOT NULL THEN SET vNErrors = vNErrors + 1; @@ -4814,7 +4814,7 @@ BEGIN vError = MESSAGE_TEXT, vErrorCode = RETURNED_SQLSTATE; - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); + CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4833,22 +4833,22 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `payMethodClientAdd`() BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) + INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) SELECT util.VN_CURDATE(), c.payMethodFk, c.id - FROM vn.client c + FROM vn.client c JOIN vn.payMethod p ON c.payMethodFk = p.id; - + TRUNCATE `bs`.`payMethodClientEvolution` ; - + INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) - SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) + SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) FROM bs.payMethodClient p - JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente + JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente FROM bs.ventas v WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk JOIN vn.payMethod pm ON p.payMethodFk = pm.id - GROUP BY dated,payMethodFk; + GROUP BY dated,payMethodFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4868,12 +4868,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleGraphic`(IN vItemFk INT, IN vTypeFk INT, IN vCategoryFk INT, IN vFromDate DATE, IN vToDate DATE, IN vProducerFk INT) BEGIN - + DECLARE vFromDateLastYear DATE; DECLARE vToDateLastYear DATE; DECLARE vFromDateTwoYearsAgo DATE; DECLARE vToDateTwoYearsAgo DATE; - + SET vItemFk = IFNULL(vItemFk,0); SET vTypeFk = IFNULL(vTypeFk, 0); SET vCategoryFk = IFNULL(vCategoryFk,0); @@ -4888,19 +4888,19 @@ BEGIN SELECT s.quantity, CAST(v.importe AS DECIMAL(10,0)) importe, v.fecha FROM bs.ventas v - JOIN vn.sale s ON s.id = v.Id_Movimiento - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.sale s ON s.id = v.Id_Movimiento + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE vItemFk IN (i.id, 0) AND vTypeFk IN (i.typeFk, 0) AND vCategoryFk IN (it.categoryFk, 0) AND vProducerFk IN (i.producerFk, 0) AND (v.fecha BETWEEN vFromDate AND vToDate OR v.fecha BETWEEN vFromDateLastYear AND vToDateLastYear - OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo + OR v.fecha BETWEEN vFromDateTwoYearsAgo AND vToDateTwoYearsAgo ); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4919,21 +4919,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) BEGIN - DELETE FROM bs.salePersonEvolution + DELETE FROM bs.salePersonEvolution WHERE dated <= DATE_SUB(util.VN_CURDATE(), INTERVAL 1 YEAR); - - + + INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - SELECT fecha dated, - CAST(SUM(importe) AS DECIMAL(10,2) ) amount, + SELECT fecha dated, + CAST(SUM(importe) AS DECIMAL(10,2) ) amount, CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , IFNULL(salesPersonFk,0) salesPersonFk FROM bs.ventas v - JOIN vn.client c ON v.Id_Cliente = c.id + JOIN vn.client c ON v.Id_Cliente = c.id JOIN vn.company co ON co.id = v.empresa_id WHERE co.code = "VNL" AND fecha >= vDateStart GROUP BY v.fecha,c.salesPersonFk - ORDER BY salesPersonFk,dated ASC; + ORDER BY salesPersonFk,dated ASC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4955,7 +4955,7 @@ BEGIN /** * Agrupa las ventas por cliente/comercial/fecha en la tabla bs.salesByclientSalesPerson * El asociación cliente/comercial/fecha, se mantiene correcta en el tiempo - * + * * @param vDatedFrom el cálculo se realizará desde la fecha introducida hasta ayer */ @@ -4963,17 +4963,17 @@ BEGIN SET vDatedFrom = util.VN_CURDATE() - INTERVAL 1 MONTH; END IF; - UPDATE salesByclientSalesPerson + UPDATE salesByclientSalesPerson SET amount = 0, equalizationTax = 0, amountNewBorn = 0 WHERE dated BETWEEN vDatedFrom AND util.yesterday(); - - INSERT INTO salesByclientSalesPerson( - dated, - salesPersonFk, - clientFk, - amount, + + INSERT INTO salesByclientSalesPerson( + dated, + salesPersonFk, + clientFk, + amount, equalizationTax) SELECT s.dated, c.salesPersonFk, @@ -4982,7 +4982,7 @@ BEGIN SUM(s.surcharge) FROM sale s JOIN vn.client c on s.clientFk = c.id - WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() + WHERE s.dated BETWEEN vDatedFrom AND util.yesterday() GROUP BY s.dated, c.salesPersonFk, s.clientFk ON DUPLICATE KEY UPDATE amount= VALUES(amount), equalizationTax= VALUES(equalizationTax); @@ -5156,8 +5156,8 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesByItemTypeDay_addLauncher`() -BEGIN - CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); +BEGIN + CALL bs.salesByItemTypeDay_add(util.VN_CURDATE() - INTERVAL 30 DAY, util.VN_CURDATE()); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5177,35 +5177,35 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `salesPersonEvolution_add`() BEGIN /** - * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. + * Calcula los datos para los gráficos de evolución agrupado por salesPersonFk y día. * Recalcula automáticamente los 3 últimos meses para comprobar si hay algún cambio. */ DECLARE vDated DATE; DECLARE vCont INT DEFAULT 1; - SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated + SELECT MAX(dated) - INTERVAL 3 MONTH INTO vDated FROM salesPersonEvolution; - DELETE FROM salesPersonEvolution + DELETE FROM salesPersonEvolution WHERE dated >= vDated; IF ISNULL(vDated) THEN - SELECT MIN(dated) INTO vDated + SELECT MIN(dated) INTO vDated FROM salesByclientSalesPerson; - + INSERT INTO salesPersonEvolution( - salesPersonFk, - dated, - amount, - equalizationTax, + salesPersonFk, + dated, + amount, + equalizationTax, amountNewBorn ) - SELECT salesPersonFk, - dated, - amount, - equalizationTax, + SELECT salesPersonFk, + dated, + amount, + equalizationTax, amountNewBorn - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated GROUP BY salesPersonFk; @@ -5213,21 +5213,21 @@ BEGIN END IF; WHILE vDated < util.VN_CURDATE() DO - + SET vCont = vCont + 1; REPLACE salesPersonEvolution(salesPersonFk, dated, amount) SELECT salesPersonFk, vDated, amount FROM(SELECT salesPersonFk, SUM(amount) amount FROM(SELECT salesPersonFk, amount - FROM salesPersonEvolution + FROM salesPersonEvolution WHERE dated = vDated - INTERVAL 1 DAY UNION ALL - SELECT salesPersonFk, amount - FROM salesByclientSalesPerson + SELECT salesPersonFk, amount + FROM salesByclientSalesPerson WHERE dated = vDated UNION ALL SELECT salesPersonFk, - amount - FROM salesByclientSalesPerson + FROM salesByclientSalesPerson WHERE dated = vDated - INTERVAL 1 YEAR )sub GROUP BY salesPersonFk @@ -5256,7 +5256,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `vendedores_add_launcher`() BEGIN CALL bs.salesByclientSalesPerson_add(util.VN_CURDATE()- INTERVAL 45 DAY); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5280,7 +5280,7 @@ BEGIN /** * Añade las ventas que se realizaron entre * vStarted y vEnded -* +* * @param vStarted Fecha de inicio * @param vEnded Fecha de finalizacion * @@ -5288,7 +5288,7 @@ BEGIN DECLARE vStartingDate DATETIME; DECLARE vEndingDate DATETIME; - IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) + IF vStarted < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) OR vEnded < TIMESTAMPADD(YEAR,-5,util.VN_CURDATE()) THEN CALL util.throw('fechaDemasiadoAntigua'); END IF; @@ -5297,8 +5297,8 @@ BEGIN SET vStartingDate = vStarted ; SET vEndingDate = util.dayEnd(vStartingDate); - DELETE - FROM sale + DELETE + FROM sale WHERE dated BETWEEN vStartingDate AND vEnded; WHILE vEndingDate <= vEnded DO @@ -5319,28 +5319,28 @@ BEGIN JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.address a ON a.id = t.addressFk + JOIN vn.address a ON a.id = t.addressFk JOIN vn.client cl ON cl.id = a.clientFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND s.quantity <> 0 AND s.discount <> 100 - AND ic.merchandise + AND ic.merchandise GROUP BY sc.saleFk HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; UPDATE sale s JOIN ( - SELECT s.id, + SELECT s.id, SUM(s.quantity * sc.value ) margen, s.quantity * s.price * (100 - s.discount ) / 100 pvp FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.saleComponent sc ON sc.saleFk = s.id - JOIN vn.component c ON c.id = sc.componentFk - JOIN vn.componentType ct ON ct.id = c.typeFk + JOIN vn.component c ON c.id = sc.componentFk + JOIN vn.componentType ct ON ct.id = c.typeFk WHERE t.shipped BETWEEN vStartingDate AND vEndingDate AND ct.isMargin = TRUE - GROUP BY s.id) sub ON sub.id = s.saleFk + GROUP BY s.id) sub ON sub.id = s.saleFk SET s.margin = sub.margen + s.amount + s.surcharge - sub.pvp; SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); @@ -5368,7 +5368,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_add_launcher`() BEGIN /** * Añade las ventas a la tabla bs.sale que se realizaron desde hace un mes hasta hoy - * + * */ DECLARE vCurDate DATE DEFAULT util.VN_CURDATE(); @@ -5392,7 +5392,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas @@ -5404,8 +5404,8 @@ BEGIN DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - DELETE FROM bs.ventas_contables - WHERE year = vYear + DELETE FROM bs.ventas_contables + WHERE year = vYear AND month = vMonth; DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; @@ -5416,7 +5416,7 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; + AND month(f.Fecha) = vMonth; INSERT INTO bs.ventas_contables(year , month @@ -5426,7 +5426,7 @@ BEGIN , tipo_id , empresa_id , gasto) - + SELECT vYear , vMonth , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) @@ -5438,13 +5438,13 @@ BEGIN , tp.reino_id , a.tipo_id , t.empresa_id - , 7000000000 + , 7000000000 + IF(e.empresa_grupo = e2.empresa_grupo ,1 ,IF(e2.empresa_grupo,2,0) - ) * 1000000 + ) * 1000000 + tp.reino_id * 10000 as Gasto - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente @@ -5458,7 +5458,7 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != TIPO_PATRIMONIAL GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - + INSERT INTO bs.ventas_contables(year , month , venta @@ -5477,17 +5477,17 @@ BEGIN ) as grupo , NULL , NULL - , t.companyFk + , t.companyFk , 7050000000 - FROM vn.ticketService ts + FROM vn.ticketService ts JOIN vn.ticket t ON ts.ticketFk = t.id - JOIN vn.address a on a.id = t.addressFk - JOIN vn.client cl on cl.id = a.clientFk + JOIN vn.address a on a.id = t.addressFk + JOIN vn.client cl on cl.id = a.clientFk JOIN tmp.ticket_list tt on tt.Id_Ticket = t.id - JOIN vn.company c on c.id = t.companyFk + JOIN vn.company c on c.id = t.companyFk LEFT JOIN vn.company c2 on c2.clientFk = cl.id - GROUP BY grupo, t.companyFk ; - + GROUP BY grupo, t.companyFk ; + DROP TEMPORARY TABLE tmp.ticket_list; END ;; DELIMITER ; @@ -5507,13 +5507,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_add_launcher`() BEGIN - + /** * Reemplaza las ventas contables del último año. * Es el origen de datos para el balance de Entradas * **/ - + CALL bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()))); END ;; @@ -5534,12 +5534,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) BEGIN - + /** * Muestra las ventas (€) de cada cliente * dependiendo del año */ - + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; CREATE TEMPORARY TABLE tmp.ticket_list @@ -5548,8 +5548,8 @@ BEGIN FROM vn2008.Tickets t JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - + AND month(f.Fecha) = vMonth; + SELECT vYear Año, vMonth Mes, t.Id_Cliente, @@ -5559,7 +5559,7 @@ BEGIN IF(e2.empresa_grupo,2,0)) AS grupo, t.empresa_id empresa - FROM vn2008.Movimientos m + FROM vn2008.Movimientos m JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna JOIN vn2008.Clientes c ON c.Id_Cliente = cs.Id_Cliente @@ -5573,9 +5573,9 @@ BEGIN AND m.Descuento <> 100 AND a.tipo_id != 188 GROUP BY t.Id_Cliente, grupo,t.empresa_id; - + DROP TEMPORARY TABLE tmp.ticket_list; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5594,7 +5594,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `vivosMuertos`() BEGIN - + /** * Devuelve el número de clientes nuevos y muertos, * dependiendo de la fecha actual. @@ -5605,9 +5605,9 @@ BEGIN SET @datSTART = TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); SET @datEND = TIMESTAMPADD(DAY,-DAY(util.VN_CURDATE()),util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; - + CREATE TEMPORARY TABLE tmp.VivosMuertos SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto FROM vn2008.Clientes c @@ -5623,10 +5623,10 @@ BEGIN 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 + (SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente FROM vn2008.Facturas f JOIN vn2008.time tm ON tm.date = f.Fecha WHERE Fecha BETWEEN @datSTART AND @datEND @@ -5634,9 +5634,9 @@ BEGIN AND fm.Id_Cliente = vm.Id_Cliente SET Nuevo = 1; - + SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - + UPDATE tmp.VivosMuertos vm JOIN ( SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente @@ -5677,23 +5677,23 @@ BEGIN INTO vWeek, vYear FROM vn.time WHERE dated = util.VN_CURDATE(); - + REPLACE bs.waste SELECT *, 100 * mermas / total as porcentaje FROM ( - SELECT buyer, - year, + SELECT buyer, + year, week, family, itemFk, itemTypeFk, - floor(sum(value)) as total, + floor(sum(value)) as total, floor(sum(IF(clientTypeFk = 'loses', value, 0))) as mermas - FROM vn.saleValue + FROM vn.saleValue where year = vYear and week = vWeek - + GROUP BY family, itemFk - + ) sub ORDER BY mermas DESC; END ;; @@ -5725,56 +5725,56 @@ BEGIN DECLARE vDateEnded DATE; DECLARE vCursor CURSOR FOR - SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) + SELECT util.firstDayOfMonth(t.dated), LAST_DAY(t.dated) FROM vn.time t WHERE t.dated BETWEEN vDateStarted AND vDateEnded - GROUP BY year,month; + GROUP BY year,month; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + IF DAY(util.VN_CURDATE()) = 21 THEN - + SELECT util.firstDayOfMonth(DATE_SUB(util.VN_CURDATE(), INTERVAL 12 MONTH)), LAST_DAY(DATE_SUB(util.VN_CURDATE(), INTERVAL 1 MONTH)) - INTO vDateStarted, + INTO vDateStarted, vDateEnded; - - DELETE FROM workerLabourDataByMonth + + DELETE FROM workerLabourDataByMonth WHERE CONCAT(`year`, '-',`month`, '-01') BETWEEN vDateStarted AND vDateEnded; OPEN vCursor; l: LOOP SET vDone = FALSE; - + FETCH vCursor INTO vFristDay, vLastDay; - + IF vDone THEN LEAVE l; END IF; - + -- Altas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'hiring', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.workCenter wc ON wc.id = b.workCenterFk JOIN vn.worker w ON w.id = b.workerFk LEFT JOIN vn.workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk LEFT JOIN (SELECT b.id, b.workerFk FROM vn.business b - LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl + LEFT JOIN (SELECT ended, workerFk FROM vn.business) wl ON wl.ended = DATE_SUB(b.started, INTERVAL 1 DAY) AND wl.workerFk = b.workerFk - WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended + WHERE b.started BETWEEN vFristDay AND vLastDay AND wl.ended )sub ON sub.workerFk = b.workerFk WHERE wc.payrollCenterFk IS NOT NULL AND b.workCenterFk IS NOT NULL AND b.started BETWEEN vFristDay AND vLastDay AND sub.workerFk IS NULL - AND NOT w.isFreelance; + AND NOT w.isFreelance; -- Bajas periodo - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'layoffs', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5785,12 +5785,12 @@ BEGIN AND b.ended BETWEEN vFristDay AND vLastDay AND wl.started IS NULL AND NOT w.isFreelance; - + -- Anterior al periodo SET vLastDay = LAST_DAY(DATE_SUB(vFristDay, INTERVAL 1 DAY)); - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'staff', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -5800,8 +5800,8 @@ BEGIN AND NOT w.isFreelance; -- Discapacidad - INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) - SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) + INSERT INTO workerLabourDataByMonth (code, month, year, total, permanent) + SELECT 'disabled', MONTH(vFristDay), YEAR(vFristDay), COUNT(*), SUM(wbt.isPermanent) FROM vn.business b JOIN vn.worker w ON w.id = b.workerFk JOIN vn.workCenter wc ON wc.id = b.workCenterFk @@ -6210,7 +6210,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addressFriendship_Update`() BEGIN - REPLACE cache.addressFriendship + REPLACE cache.addressFriendship SELECT addressFk1, addressFk2, count(*) friendship FROM ( @@ -6221,7 +6221,7 @@ BEGIN AND t2.shipped >= TIMESTAMPADD(MONTH,-3,util.VN_CURDATE()) AND t.addressFk != t2.addressFk) sub GROUP BY addressFk1, addressFk2; - + REPLACE cache.zoneAgencyFriendship SELECT r.agencyModeFk, t.zoneFk, count(*) friendship FROM vn.route r @@ -6395,12 +6395,12 @@ BEGIN FROM available a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DELETE a FROM availableNoRaids a LEFT JOIN tCalc c ON c.id = a.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -6579,27 +6579,27 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6617,89 +6617,89 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - DECLARE vLastRefresh DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires, ca.last_refresh - INTO v_cache_id, v_calc, v_expires, vLastRefresh - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + DECLARE vLastRefresh DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires, ca.last_refresh + INTO v_cache_id, v_calc, v_expires, vLastRefresh + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires AND vLastRefresh >= CURDATE() + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6729,7 +6729,7 @@ proc: BEGIN FROM cache c JOIN cache_calc ca ON c.id = ca.cache_id WHERE ca.id = v_calc; - + DELETE FROM cache_calc WHERE id = v_calc; IF v_cache_name IS NOT NULL THEN @@ -6825,7 +6825,7 @@ DECLARE rs CURSOR FOR DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; + SET myTime = HOUR(util.VN_NOW()) + MINUTE(util.VN_NOW()) / 60; OPEN rs; @@ -6834,23 +6834,23 @@ DECLARE rs CURSOR FOR WHILE NOT done DO SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0); - + SET inicioProd = rsDeparture - rsHoras; - + IF inicioProd - resto < myTime THEN - + SET done = TRUE; - + ELSE - + SET departureLimit = rsDeparture; - + FETCH rs INTO rsDeparture, rsHoras , rsInicio; - + -- SELECT rsDeparture, rsHoras , rsInicio; - + END IF; - + END WHILE; SET departureLimit = IFNULL(departureLimit,24); @@ -6895,7 +6895,7 @@ proc: BEGIN DECLARE started DATE; DECLARE ended DATE; DECLARE vLastRefresh DATE; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (vCalc); @@ -6945,14 +6945,14 @@ proc: BEGIN DECLARE datEQ DATETIME; DECLARE timDIF TIME; DECLARE v_calc INT; - + CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id); - + IF !v_refresh THEN LEAVE proc; END IF; - + CALL vn2008.production_control_source(wh_id, 0); DELETE FROM prod_graphic_source; @@ -6970,8 +6970,8 @@ proc: BEGIN WHERE Fecha = util.VN_CURDATE() GROUP BY wh_id, graphCategory ; - - + + CALL cache_calc_end (v_calc); END ;; DELIMITER ; @@ -6992,7 +6992,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `stock_refresh`(v_refresh BOOL) proc: BEGIN /** - * Crea o actualiza la cache con el disponible hasta el día de + * Crea o actualiza la cache con el disponible hasta el día de * ayer. Esta cache es usada como base para otros procedimientos * como el cáculo del visible o del ATP. * @@ -7018,21 +7018,21 @@ proc: BEGIN SET v_date_inv = (SELECT inventoried FROM vn.config LIMIT 1); SET vCURDATE = util.VN_CURDATE(); - + DELETE FROM stock; - + INSERT INTO stock (item_id, warehouse_id, amount) SELECT item_id, warehouse_id, SUM(amount) amount FROM ( - SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id, warehouseFk AS warehouse_id, quantity AS amount FROM vn.itemTicketOut WHERE shipped >= v_date_inv AND shipped < vCURDATE UNION ALL - SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount + SELECT itemFk ASitem_id, warehouseInFk AS warehouse_id, quantity AS amount FROM vn.itemEntryIn WHERE landed >= v_date_inv AND landed < vCURDATE AND isVirtualStock is FALSE UNION ALL - SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount + SELECT itemFk AS item_id ,warehouseOutFk AS warehouse_id, quantity AS amount FROM vn.itemEntryOut WHERE shipped >= v_date_inv AND shipped < vCURDATE ) t @@ -7062,12 +7062,12 @@ BEGIN (INDEX (id)) ENGINE = MEMORY SELECT id FROM cache_calc; - + DELETE v FROM visible v LEFT JOIN tCalc c ON c.id = v.calc_id WHERE c.id IS NULL; - + DROP TEMPORARY TABLE tCalc; END ;; DELIMITER ; @@ -7991,9 +7991,9 @@ DELIMITER ;; BEGIN DECLARE nextID INT; - + SELECT 1 + MAX(id) INTO nextID FROM putOrder ; - + SET NEW.orderTradelineItemID = nextID; END */;; @@ -8015,36 +8015,36 @@ DELIMITER ;; BEFORE UPDATE ON `putOrder` FOR EACH ROW BEGIN - + DECLARE vError VARCHAR(100) DEFAULT 'Orderregel niet meer teruggevonden op basis van de orderps'; DECLARE vVmpIdError INT DEFAULT 7; DECLARE vVmpFk INT; DECLARE vSupplyResponseNumberOfUnits INT; - - SELECT sr.vmpID INTO vVmpFk - FROM edi.supplyResponse sr + + SELECT sr.vmpID INTO vVmpFk + FROM edi.supplyResponse sr WHERE sr.id = NEW.supplyResponseID; - - IF NEW.OrderStatus = 3 - AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) - AND NEW.error = vError - AND vVmpFk = vVmpIdError - - THEN - + + IF NEW.OrderStatus = 3 + AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) + AND NEW.error = vError + AND vVmpFk = vVmpIdError + + THEN + SET NEW.OrderStatus = 2; - + END IF; - + -- Error de disponible menor de lo solicitado IF NEW.error LIKE 'error2602%' THEN - + SELECT NumberOfUnits INTO vSupplyResponseNumberOfUnits - FROM edi.supplyResponse sr + FROM edi.supplyResponse sr WHERE sr.ID = NEW.supplyResponseID; - + SET NEW.error = CONCAT('(',vSupplyResponseNumberOfUnits,') ', NEW.error); - + END IF; END */;; DELIMITER ; @@ -8071,16 +8071,16 @@ BEGIN DECLARE vIsEktSender BOOLEAN; IF NEW.OrderStatus = vOrderStatusDenied AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - + SELECT s.id INTO vSaleFk - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN deliveryInformation di ON di.ID = NEW.deliveryInformationID WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID LIMIT 1; - + UPDATE vn.sale s JOIN vn.ticket t ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk @@ -8088,7 +8088,7 @@ BEGIN SET s.quantity = 0 WHERE t.clientFk = NEW.EndUserPartyGLN AND t.shipped >= util.VN_CURDATE() AND i.supplyResponseFk = NEW.supplyResponseID; - + INSERT INTO vn.mail (sender, `subject`, body) SELECT IF(u.id IS NOT NULL AND c.email IS NOT NULL, c.email, @@ -8100,26 +8100,26 @@ BEGIN IF (u.id IS NOT NULL AND c.email IS NOT NULL , CONCAT('https://shop.verdnatura.es/#!form=ecomerce%2Fticket&ticket=', t.id ), CONCAT('https://salix.verdnatura.es/#!/ticket/', t.id ,'/summary'))) - FROM vn.sale s + FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.`client` c ON c.id = t.clientFk LEFT JOIN account.user u ON u.id= c.salesPersonFk AND u.name IN ('ruben', 'ismaelalcolea') WHERE s.id = vSaleFk; - + END IF; IF NEW.OrderStatus = vOrderStatusOK AND NOT (NEW.OrderStatus <=> OLD.OrderStatus) THEN - SELECT v.isEktSender INTO vIsEktSender + SELECT v.isEktSender INTO vIsEktSender FROM edi.VMPSettings v - JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID + JOIN edi.supplyResponse sr ON sr.vmpID = v.VMPID WHERE sr.id = NEW.supplyResponseID; - + IF NOT vIsEktSender THEN CALL edi.ekt_add(NEW.id); - + END IF; IF NEW.barcode THEN @@ -8128,7 +8128,7 @@ BEGIN SELECT i.id, NEW.barcode FROM vn.item i WHERE i.supplyResponseFk = NEW.supplyResponseID; - + END IF; END IF; @@ -8326,8 +8326,8 @@ BEGIN UPDATE vn.buy b JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk JOIN vn.item i ON i.id = b.itemFk JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID SET b.quantity = NEW.NumberOfItemsPerCask * NEW.NumberOfUnits, @@ -8336,7 +8336,7 @@ BEGIN AND am.name = 'LOGIFLORA' AND e.isRaid AND tr.landed >= util.VN_CURDATE(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8478,7 +8478,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `imageName`(vPictureReference VARCHAR(255)) RETURNS varchar(255) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + SET vPictureReference = REPLACE(vPictureReference,'.',''); SET vPictureReference = REPLACE(vPictureReference,'/',''); @@ -8490,7 +8490,7 @@ BEGIN SET vPictureReference = REPLACE(vPictureReference,'?',''); SET vPictureReference = REPLACE(vPictureReference,'=',''); - + RETURN vPictureReference; END ;; @@ -8546,27 +8546,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deliveryInformation_Delete`() BEGIN - + DECLARE vID INT; DECLARE vGap INT DEFAULT 100; DECLARE vTope INT; - - SELECT MIN(ID), MAX(ID) + + SELECT MIN(ID), MAX(ID) INTO vID, vTope FROM edi.deliveryInformation; - WHILE vID <= vTope DO - + WHILE vID <= vTope DO + SET vID = vID + vGap; - - DELETE - FROM edi.deliveryInformation + + DELETE + FROM edi.deliveryInformation WHERE ID < vID AND EarliestDespatchDateTime IS NULL; - + END WHILE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8585,15 +8585,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_add`(vPutOrderFk INT) BEGIN - + /** * Añade ekt para las ordenes de compra de proveedores que no envian el ekt por email - * + * * @param vPutOrderFk PutOrderId de donde coger los datos **/ - - INSERT INTO edi.ekt(entryYear, - deliveryNumber, + + INSERT INTO edi.ekt(entryYear, + deliveryNumber, fec, hor, item, @@ -8633,17 +8633,17 @@ BEGIN i.value10 s6, p.id putOrderFk, sr.Item_ArticleCode, - sr.vmpID + sr.vmpID FROM edi.putOrder p - JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID - JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN vn.origin o ON o.id = i.originFk + JOIN edi.supplyResponse sr ON sr.ID = p.supplyResponseID + JOIN edi.deliveryInformation di ON di.id = p.deliveryInformationID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN vn.origin o ON o.id = i.originFk WHERE p.id = vPutOrderFk; - + CALL edi.ekt_load(LAST_INSERT_ID()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8662,7 +8662,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_load`(IN `vSelf` INT) proc:BEGIN - + DECLARE vRef INT; DECLARE vBuy INT; DECLARE vItem INT; @@ -8687,51 +8687,51 @@ proc:BEGIN FROM edi.ekt e LEFT JOIN edi.item i ON e.ref = i.id LEFT JOIN edi.putOrder po ON po.id = e.putOrderFk - LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID + LEFT JOIN vn.item i2 ON i2.supplyResponseFk = po.supplyResponseID LEFT JOIN vn.ektEntryAssign eea ON eea.sub = e.sub LEFT JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id WHERE e.id = vSelf LIMIT 1; - + IF NOT vHasItemGroup THEN - + CALL vn.mail_insert('logistica@verdnatura.es', 'nocontestar@verdnatura.es', 'Nuevo grupo en Floramondo', vDescription); - + CALL vn.mail_insert('pako@verdnatura.es', 'nocontestar@verdnatura.es', CONCAT('Nuevo grupo en Floramondo: ', vDescription), vDescription); - + LEAVE proc; - + END IF; - + -- Asigna la entrada SELECT vn.ekt_getEntry(vSelf) INTO vEntryFk; - + -- Inserta el cubo si no existe IF vPackage = 800 THEN - + SET vHasToChangePackagingFk = TRUE; - + IF vItem THEN - + SELECT vn.item_getPackage(vItem) INTO vPackage ; - + ELSE - + SET vPackage = 8000 + vQty; INSERT IGNORE INTO vn.packaging(id, width, `depth`) SELECT vPackage, vc.ccLength / vQty, vc.ccWidth FROM vn.volumeConfig vc; - + END IF; - + ELSE - + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) FROM bucket WHERE bucket_id = vPackage; - + IF ROW_COUNT() > 0 THEN INSERT INTO vn2008.mail SET @@ -8740,27 +8740,27 @@ proc:BEGIN `to` = 'ekt@verdnatura.es'; END IF; END IF; - + -- Si es una compra de Logiflora obtiene el articulo IF vPutOrderFk THEN - + SELECT i.id INTO vItem FROM edi.putOrder po JOIN vn.item i ON i.supplyResponseFk = po.supplyResponseID WHERE po.id = vPutOrderFk LIMIT 1; - + END IF; INSERT IGNORE INTO item_track SET item_id = vRef; - + IF IFNULL(vItem,0) = 0 THEN - + -- Intenta obtener el artículo en base a los atributos holandeses - + SELECT b.id, IFNULL(b.itemOriginalFk ,b.itemFk) INTO vBuy, vItem - FROM edi.ekt e + FROM edi.ekt e JOIN edi.item_track t ON t.item_id = e.ref LEFT JOIN edi.ekt l ON l.ref = e.ref LEFT JOIN vn.buy b ON b.ektFk = l.id @@ -8781,19 +8781,19 @@ proc:BEGIN AND IF(t.pro, l.pro = e.pro, TRUE) AND IF(t.package, l.package = e.package, TRUE) AND IF(t.item, l.item = e.item, TRUE) - AND i.isFloramondo = vIsFloramondoDirect - ORDER BY l.now DESC, b.id ASC + AND i.isFloramondo = vIsFloramondoDirect + ORDER BY l.now DESC, b.id ASC LIMIT 1; END IF; - + -- Si no encuentra el articulo lo crea en el caso de las compras directas en Floramondo IF ISNULL(vItem) AND vIsFloramondoDirect THEN - + CALL edi.item_getNewByEkt(vSelf, vItem); - + END IF; - + INSERT INTO vn.buy ( entryFk @@ -8816,15 +8816,15 @@ proc:BEGIN ,e.qty stickers ,@pac := IFNULL(i.stemMultiplier, 1) * e.pac / @t packing ,IFNULL(b.`grouping`, e.pac) - ,@pac * e.qty + ,@pac * e.qty ,vForceToPacking ,IF(vHasToChangePackagingFk OR ISNULL(b.packageFk), vPackage, b.packageFk) ,(IFNULL(i.weightByPiece,0) * @pac)/1000 - FROM edi.ekt e + FROM edi.ekt e LEFT JOIN vn.buy b ON b.id = vBuy LEFT JOIN vn.item i ON i.id = b.itemFk LEFT JOIN vn.supplier s ON e.pro = s.id - JOIN vn2008.config cfg + JOIN vn2008.config cfg WHERE e.id = vSelf LIMIT 1; @@ -8832,36 +8832,36 @@ proc:BEGIN CREATE TEMPORARY TABLE tmp.buyRecalc SELECT buy.id - FROM vn.buy + FROM vn.buy WHERE ektFk = vSelf; CALL vn.buy_recalcPrices(); -- Si es una compra de Logiflora hay que informar la tabla vn.saleBuy IF vPutOrderFk THEN - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT po.saleFk, b.id, account.myUser_getId() FROM edi.putOrder po JOIN vn.buy b ON b.ektFk = vSelf WHERE po.id = vPutOrderFk; - + END IF; - -- Si es una compra directa en Floramondo hay que añadirlo al ticket + -- Si es una compra directa en Floramondo hay que añadirlo al ticket IF vIsFloramondoDirect THEN SELECT t.id INTO vTicketFk FROM vn.ticket t - JOIN vn.ektEntryAssign eea - ON eea.addressFk = t.addressFk + JOIN vn.ektEntryAssign eea + ON eea.addressFk = t.addressFk AND t.warehouseFk = eea.warehouseInFk - JOIN edi.ekt e - ON e.sub = eea.sub + JOIN edi.ekt e + ON e.sub = eea.sub AND e.id = vSelf WHERE e.fec = t.shipped LIMIT 1; - + IF ISNULL(vTicketFk) THEN INSERT INTO vn.ticket ( @@ -8889,8 +8889,8 @@ proc:BEGIN z.id, z.price, z.bonus - FROM edi.ekt e - JOIN vn.ektEntryAssign eea ON eea.sub = e.sub + FROM edi.ekt e + JOIN vn.ektEntryAssign eea ON eea.sub = e.sub JOIN vn.address a ON a.id = eea.addressFk JOIN vn.company c ON c.code = 'VNL' JOIN vn.`zone` z ON z.code = 'FLORAMONDO' @@ -8898,11 +8898,11 @@ proc:BEGIN LIMIT 1; SET vTicketFk = LAST_INSERT_ID(); - + INSERT INTO vn.ticketLog - SET originFk = vTicketFk, - userFk = account.myUser_getId(), - `action` = 'insert', + SET originFk = vTicketFk, + userFk = account.myUser_getId(), + `action` = 'insert', description = CONCAT('EktLoad ha creado el ticket:', ' ', vTicketFk); END IF; @@ -8912,9 +8912,9 @@ proc:BEGIN FROM edi.ekt e JOIN edi.floraHollandConfig fhc WHERE e.id = vSelf; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + REPLACE vn.saleBuy(saleFk, buyFk, workerFk) SELECT vSaleFk, b.id, account.myUser_getId() FROM vn.buy b @@ -8925,9 +8925,9 @@ proc:BEGIN FROM edi.ekt e JOIN vn.component c ON c.code = 'purchaseValue' WHERE e.id = vSelf; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value) - SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin + SELECT vSaleFk, c.id, e.pri * fhc.floramondoMargin FROM edi.ekt e JOIN edi.floraHollandConfig fhc JOIN vn.component c ON c.code = 'margin' @@ -9068,7 +9068,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ekt_scan`(vBarcode VARCHAR(512)) BEGIN /** * Busca transaciones a partir de un código de barras, las marca como escaneadas - * y las devuelve. + * y las devuelve. * Ver https://wiki.verdnatura.es/index.php/Ekt#Algoritmos_de_lectura * * @param vBarcode Código de compra de una etiqueta de subasta @@ -9107,19 +9107,19 @@ BEGIN ENGINE = MEMORY SELECT id ektFk FROM ekt LIMIT 0; - CASE + CASE WHEN LENGTH(vBarcode) <= vFloridayBarcodeLength THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.cps = vBarcode OR e.batchNumber = vBarcode; WHEN LENGTH(vBarcode) = vFloramondoBarcodeLength THEN INSERT INTO tmp.ekt - SELECT e.id + SELECT e.id FROM edi.ektRecent e - WHERE e.pro = MID(vBarcode,2,6) + WHERE e.pro = MID(vBarcode,2,6) AND CAST(e.ptd AS SIGNED) = MID(vBarcode,8,5); ELSE @@ -9134,7 +9134,7 @@ BEGIN -- Clásico de subasta -- Trade standard -- Trade que construye como la subasta - -- Trade como el anterior pero sin trade code + -- Trade como el anterior pero sin trade code INSERT INTO tmp.ekt SELECT id FROM ekt @@ -9155,9 +9155,9 @@ BEGIN -- BatchNumber largo IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e - WHERE e.batchNumber + WHERE e.batchNumber = LEFT(vBarcode,vUsefulAuctionLeftSegmentLength) AND e.batchNumber > 0; @@ -9167,7 +9167,7 @@ BEGIN -- Order Number IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.putOrderFk = vBarcode; @@ -9177,7 +9177,7 @@ BEGIN -- deliveryNumber incrustado IF NOT vIsFound THEN INSERT INTO tmp.ekt - SELECT id + SELECT id FROM edi.ektRecent e WHERE e.deliveryNumber = MID(vBarcode, 4, 13) @@ -9188,7 +9188,7 @@ BEGIN END CASE; IF vIsFound THEN - UPDATE ekt e + UPDATE ekt e JOIN tmp.ekt t ON t.ektFk = e.id SET e.scanned = TRUE; END IF; @@ -9209,524 +9209,524 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `floramondo_offerRefresh`() -proc: BEGIN - DECLARE vLanded DATETIME; - DECLARE vDone INT DEFAULT FALSE; - DECLARE vFreeId INT; - DECLARE vSupplyResponseFk INT; - DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; - DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; - DECLARE vDayRange INT; - - DECLARE cur1 CURSOR FOR - SELECT id - FROM edi.item_free; - - DECLARE cur2 CURSOR FOR - SELECT srId - FROM itemToInsert; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLSTATE '45000' - BEGIN - ROLLBACK; - RESIGNAL; - END; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); - SET @isTriggerDisabled = FALSE; - RESIGNAL; - END; - - IF 'test' = (SELECT environment FROM util.config) THEN - LEAVE proc; - END IF; - - IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN - LEAVE proc; - END IF; - - SELECT dayRange INTO vDayRange - FROM offerRefreshConfig; - - IF vDayRange IS NULL THEN - CALL util.throw("Variable vDayRange not declared"); - END IF; - - SET vStartingTime = util.VN_NOW(); - - TRUNCATE edi.offerList; - - INSERT INTO edi.offerList(supplier, total) - SELECT v.name, COUNT(DISTINCT sr.ID) total - FROM edi.supplyResponse sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - WHERE sr.NumberOfUnits > 0 - AND sr.EmbalageCode != 999 - GROUP BY sr.vmpID; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(*) total - FROM edi.supplyOffer sr - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.`filter` = sub.total; - - -- Elimina de la lista de items libres aquellos que ya existen - DELETE itf.* - FROM edi.item_free itf - JOIN vn.item i ON i.id = itf.id; - - CREATE OR REPLACE TEMPORARY TABLE tmp - (INDEX (`Item_ArticleCode`)) - ENGINE = MEMORY - SELECT t.* - FROM ( - SELECT * - FROM edi.supplyOffer - ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, - NumberOfUnits DESC LIMIT 10000000000000000000) t - GROUP BY t.srId; - - CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), - INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), - INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) - ENGINE = MEMORY - SELECT so.*, - ev1.type_description s1Value, - ev2.type_description s2Value, - ev3.type_description s3Value, - ev4.type_description s4Value, - ev5.type_description s5Value, - ev6.type_description s6Value, - eif1.feature ef1, - eif2.feature ef2, - eif3.feature ef3, - eif4.feature ef4, - eif5.feature ef5, - eif6.feature ef6 - FROM tmp so - LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode - AND eif1.presentation_order = 1 - AND eif1.expiry_date IS NULL - LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode - AND eif2.presentation_order = 2 - AND eif2.expiry_date IS NULL - LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode - AND eif3.presentation_order = 3 - AND eif3.expiry_date IS NULL - LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode - AND eif4.presentation_order = 4 - AND eif4.expiry_date IS NULL - LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode - AND eif5.presentation_order = 5 - AND eif5.expiry_date IS NULL - LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode - AND eif6.presentation_order = 6 - AND eif6.expiry_date IS NULL - LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature - AND so.s1 = ev1.type_value - LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature - AND so.s2 = ev2.type_value - LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature - AND so.s3 = ev3.type_value - LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature - AND so.s4 = ev4.type_value - LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature - AND so.s5 = ev5.type_value - LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature - AND so.s6 = ev6.type_value - ORDER BY Price; - - DROP TEMPORARY TABLE tmp; - - DELETE o - FROM edi.offer o - LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' - LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' - LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' - LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' - LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' - LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' - JOIN vn.floramondoConfig fc ON TRUE - WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) - OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) - OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) - OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) - OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) - OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); - - START TRANSACTION; - - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos - UPDATE IGNORE edi.offer o - JOIN vn.item i - ON i.name = o.product_name - AND i.subname <=> o.company_name - AND i.value5 <=> o.s1Value - AND i.value6 <=> o.s2Value - AND i.value7 <=> o.s3Value - AND i.value8 <=> o.s4Value - AND i.value9 <=> o.s5Value - AND i.value10 <=> o.s6Value - AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask - AND i.EmbalageCode <=> o.EmbalageCode - AND i.quality <=> o.Quality - JOIN vn.itemType it ON it.id = i.typeFk - LEFT JOIN vn.sale s ON s.itemFk = i.id - LEFT JOIN vn.ticket t ON t.id = s.ticketFk - AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) - LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk - AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) - SET i.supplyResponseFk = o.srID - WHERE (sr.ID IS NULL - OR sr.NumberOfUnits = 0 - OR di.LatestOrderDateTime < util.VN_NOW() - OR di.ID IS NULL) - AND it.isInventory - AND t.id IS NULL - AND po.id IS NULL; - - CREATE OR REPLACE TEMPORARY TABLE itemToInsert - ENGINE = MEMORY - SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk - FROM edi.offer o - LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId - WHERE i.id IS NULL - LIMIT vMaxNewItems; - - -- Reciclado de nº de item - OPEN cur1; - OPEN cur2; - - read_loop: LOOP - - FETCH cur2 INTO vSupplyResponseFk; - FETCH cur1 INTO vFreeId; - - IF vDone THEN - LEAVE read_loop; - END IF; - - UPDATE itemToInsert - SET itemFk = vFreeId - WHERE srId = vSupplyResponseFk; - - END LOOP; - - CLOSE cur1; - CLOSE cur2; - - -- Insertamos todos los items en Articles de la oferta - INSERT INTO vn.item(id, - `name`, - longName, - subName, - expenceFk, - typeFk, - intrastatFk, - originFk, - supplyResponseFk, - numberOfItemsPerCask, - embalageCode, - quality, - isFloramondo) - SELECT iti.itemFk, - iti.product_name, - iti.product_name, - iti.company_name, - iti.expenseFk, - iti.itemTypeFk, - iti.intrastatFk, - iti.originFk, - iti.`srId`, - iti.NumberOfItemsPerCask, - iti.EmbalageCode, - iti.Quality, - TRUE - FROM itemToInsert iti; - - -- Inserta la foto de los articulos nuevos (prioridad alta) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) - SELECT i.id, PictureReference - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.srId - WHERE PictureReference IS NOT NULL - AND i.image IS NULL; - - INSERT INTO edi.`log`(tableName, fieldName,fieldValue) - SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) - FROM vn.itemImageQueue - WHERE attempts = 0; - - -- Inserta si se añadiesen tags nuevos - INSERT IGNORE INTO vn.tag (name, ediTypeFk) - SELECT description, type_id FROM edi.type; - - -- Desabilita el trigger para recalcular los tags al final - SET @isTriggerDisabled = TRUE; - - -- Inserta los tags sólo en los articulos nuevos - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.product_name, 1 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Producto' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.product_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.Quality, 3 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Calidad' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.Quality IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , ii.company_name, 4 - FROM itemToInsert ii - JOIN vn.tag t ON t.`name` = 'Productor' - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT ii.company_name IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s1Value, 5 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef1 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s1Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s2Value, 6 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef2 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s2Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s3Value, 7 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef3 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s3Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s4Value, 8 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef4 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s4Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s5Value, 9 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef5 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s5Value IS NULL; - - INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id , s6Value, 10 - FROM itemToInsert ii - JOIN vn.tag t ON t.ediTypeFk = ii.ef6 - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - WHERE NOT s6Value IS NULL; - - INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 - FROM itemToInsert ii - JOIN vn.item i ON i.supplyResponseFk = ii.`srId` - JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode - LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id - AND tp.`description` = 'Hoofdkleur 1' - LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value - LEFT JOIN vn.itemInk ik ON ik.longName = i.longName - WHERE ink.name IS NOT NULL - OR ik.color IS NOT NULL; - - CREATE OR REPLACE TABLE tmp.item - (PRIMARY KEY (id)) - SELECT i.id FROM vn.item i - JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; - - CALL vn.item_refreshTags(); - - DROP TABLE tmp.item; - - SELECT MIN(LatestDeliveryDateTime) INTO vLanded - FROM edi.supplyResponse sr - JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID - JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID - JOIN vn.floramondoConfig fc - WHERE mp.isLatestOrderDateTimeRelevant - AND di.LatestOrderDateTime > IF( - fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), - util.VN_CURDATE(), - util.VN_CURDATE() + INTERVAL 1 DAY); - - UPDATE vn.floramondoConfig - SET nextLanded = vLanded - WHERE vLanded IS NOT NULL; - - -- Elimina la oferta obsoleta - UPDATE vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.agencyMode am ON am.id = tr.agencyModeFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID - LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk - SET b.quantity = 0 - WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() - OR i.supplyResponseFk IS NULL - OR sr.NumberOfUnits = 0) - AND am.name = 'LOGIFLORA' - AND e.isRaid; - - -- Localiza las entradas de cada almacen - UPDATE edi.warehouseFloramondo - SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); - - IF vLanded IS NOT NULL THEN - -- Actualiza la oferta existente - UPDATE vn.buy b - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.offer o ON i.supplyResponseFk = o.`srId` - SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, - b.buyingValue = o.price - WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask - OR b.buyingValue <> o.price); - - -- Inserta el resto - SET vLastInserted := util.VN_NOW(); - - -- Inserta la oferta - INSERT INTO vn.buy ( - entryFk, - itemFk, - quantity, - buyingValue, - stickers, - packing, - `grouping`, - groupingMode, - packageFk, - deliveryFk) - SELECT wf.entryFk, - i.id, - o.NumberOfUnits * o.NumberOfItemsPerCask quantity, - o.Price, - o.NumberOfUnits etiquetas, - o.NumberOfItemsPerCask packing, - GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, - 2, -- Obliga al Packing - o.embalageCode, - o.diId - FROM edi.offer o - JOIN vn.item i ON i.supplyResponseFk = o.srId - JOIN edi.warehouseFloramondo wf - JOIN vn.packaging p ON p.id - LIKE o.embalageCode - LEFT JOIN vn.buy b ON b.itemFk = i.id - AND b.entryFk = wf.entryFk - WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL - - INSERT INTO vn.itemCost( - itemFk, - warehouseFk, - cm3, - cm3delivery) - SELECT b.itemFk, - wf.warehouseFk, - @cm3 := vn.buy_getUnitVolume(b.id), - IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) - FROM warehouseFloramondo wf - JOIN vn.volumeConfig vc - JOIN vn.buy b ON b.entryFk = wf.entryFk - JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk - AND ic.warehouseFk = wf.warehouseFk - WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) - ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); - - CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc - SELECT b.id - FROM vn.buy b - JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk - WHERE b.created >= vLastInserted; - - CALL vn.buy_recalcPrices(); - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'VNH' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.vnh = sub.total; - - UPDATE edi.offerList o - JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total - FROM vn.buy b - JOIN vn.item i ON i.id = b.itemFk - JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk - JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID - JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk - JOIN vn.warehouse w ON w.id = wf.warehouseFk - WHERE w.name = 'ALGEMESI' - AND b.quantity > 0 - GROUP BY sr.vmpID) sub ON o.supplier = sub.name - SET o.algemesi = sub.total; - END IF; - - DROP TEMPORARY TABLE - edi.offer, - itemToInsert; - - SET @isTriggerDisabled = FALSE; - - COMMIT; - - -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias - UPDATE vn.item i - SET typeFk = 121 - WHERE i.longName LIKE 'Rosa Garden %' - AND typeFk = 17; - - UPDATE vn.item i - SET typeFk = 156 - WHERE i.longName LIKE 'Rosa ec %' - AND typeFk = 17; - - -- Refresca las fotos de los items existentes que mostramos (prioridad baja) - INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) - SELECT i.id, sr.PictureReference, 100 - FROM edi.supplyResponse sr - JOIN vn.item i ON i.supplyResponseFk = sr.ID - JOIN edi.supplyOffer so ON so.srId = sr.ID - JOIN hedera.image i2 ON i2.name = i.image - AND i2.collectionFk = 'catalog' - WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) - AND sr.NumberOfUnits; - - INSERT INTO edi.`log` - SET tableName = 'floramondo_offerRefresh', - fieldName = 'Tiempo de proceso', - fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); - - DO RELEASE_LOCK('edi.floramondo_offerRefresh'); +proc: BEGIN + DECLARE vLanded DATETIME; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vDayRange INT; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); + SET @isTriggerDisabled = FALSE; + RESIGNAL; + END; + + IF 'test' = (SELECT environment FROM util.config) THEN + LEAVE proc; + END IF; + + IF !GET_LOCK('edi.floramondo_offerRefresh', 0) THEN + LEAVE proc; + END IF; + + SELECT dayRange INTO vDayRange + FROM offerRefreshConfig; + + IF vDayRange IS NULL THEN + CALL util.throw("Variable vDayRange not declared"); + END IF; + + SET vStartingTime = util.VN_NOW(); + + TRUNCATE edi.offerList; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + CREATE OR REPLACE TEMPORARY TABLE tmp + (INDEX (`Item_ArticleCode`)) + ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, + NumberOfUnits DESC LIMIT 10000000000000000000) t + GROUP BY t.srId; + + CREATE OR REPLACE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 + AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 + AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 + AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 + AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 + AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 + AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature + AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature + AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature + AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature + AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature + AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature + AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR (t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR (t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR (t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR (t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR (t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk + AND t.shipped > (util.VN_CURDATE() - INTERVAL 1 WEEK) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk + AND po.OrderTradeLineDateTime > (util.VN_CURDATE() - INTERVAL 1 WEEK) + SET i.supplyResponseFk = o.srID + WHERE (sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < util.VN_NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + + CREATE OR REPLACE TEMPORARY TABLE itemToInsert + ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF vDone THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item(id, + `name`, + longName, + subName, + expenceFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + -- Inserta la foto de los articulos nuevos (prioridad alta) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL + AND i.image IS NULL; + + INSERT INTO edi.`log`(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + -- Inserta los tags sólo en los articulos nuevos + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.product_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.Quality IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ii.company_name IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s1Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s2Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s3Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s4Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s5Value IS NULL; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT s6Value IS NULL; + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id + AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + CREATE OR REPLACE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + DROP TABLE tmp.item; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF( + fc.MaxLatestOrderHour > HOUR(util.VN_NOW()), + util.VN_CURDATE(), + util.VN_CURDATE() + INTERVAL 1 DAY); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyModeFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,util.VN_NOW()) <= util.VN_NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.entry_getForLogiflora(vLanded + INTERVAL travellingDays DAY, warehouseFk); + + IF vLanded IS NOT NULL THEN + -- Actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask + OR b.buyingValue <> o.price); + + -- Inserta el resto + SET vLastInserted := util.VN_NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy ( + entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packageFk, + deliveryFk) + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask quantity, + o.Price, + o.NumberOfUnits etiquetas, + o.NumberOfItemsPerCask packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask `grouping`, + 2, -- Obliga al Packing + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id + LIKE o.embalageCode + LEFT JOIN vn.buy b ON b.itemFk = i.id + AND b.entryFk = wf.entryFk + WHERE b.id IS NULL; -- Quitar esta linea y mirar de crear los packages a tiempo REAL + + INSERT INTO vn.itemCost( + itemFk, + warehouseFk, + cm3, + cm3delivery) + SELECT b.itemFk, + wf.warehouseFk, + @cm3 := vn.buy_getUnitVolume(b.id), + IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3) + FROM warehouseFloramondo wf + JOIN vn.volumeConfig vc + JOIN vn.buy b ON b.entryFk = wf.entryFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN vn.itemCost ic ON ic.itemFk = b.itemFk + AND ic.warehouseFk = wf.warehouseFk + WHERE (ic.cm3 IS NULL OR ic.cm3 = 0) + ON DUPLICATE KEY UPDATE cm3 = @cm3, cm3delivery = IFNULL((vc.standardFlowerBox * 1000) / i.packingOut, @cm3); + + CREATE OR REPLACE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + SET @isTriggerDisabled = FALSE; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + -- Refresca las fotos de los items existentes que mostramos (prioridad baja) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url, priority) + SELECT i.id, sr.PictureReference, 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + JOIN edi.supplyOffer so ON so.srId = sr.ID + JOIN hedera.image i2 ON i2.name = i.image + AND i2.collectionFk = 'catalog' + WHERE i2.updated <= (UNIX_TIMESTAMP(util.VN_NOW()) - vDayRange) + AND sr.NumberOfUnits; + + INSERT INTO edi.`log` + SET tableName = 'floramondo_offerRefresh', + fieldName = 'Tiempo de proceso', + fieldValue = TIMEDIFF(util.VN_NOW(), vStartingTime); + + DO RELEASE_LOCK('edi.floramondo_offerRefresh'); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9793,7 +9793,7 @@ BEGIN /** * Devuelve un número nuevo de item a partir de un registro de la tabla edi.ekt - * + * * @param vEktFk Identificador de la tabla edi.ekt */ @@ -9802,17 +9802,17 @@ BEGIN SELECT MIN(id) id INTO vItemFk FROM edi.item_free; - DELETE FROM edi.item_free + DELETE FROM edi.item_free WHERE id = vItemFk; - + COMMIT; - + IF ISNULL(vItemFk) THEN SELECT MAX(i.id) + 1 INTO vItemFk FROM vn.item i; END IF; - + INSERT INTO vn.item(id, `name`, longName, @@ -9838,118 +9838,118 @@ BEGIN least(IF((e.package = 800),((e.package * 10) + e.pac), e.package), IFNULL(idt.bucket_id, '999')) packageFk, e.cat, TRUE - FROM edi.ekt e - JOIN edi.item i ON i.id = e.`ref` - JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id - LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` + FROM edi.ekt e + JOIN edi.item i ON i.id = e.`ref` + JOIN edi.item_groupToOffer igto ON igto.group_code = i.group_id + LEFT JOIN edi.item_defaultType idt ON idt.item_id = e.`ref` WHERE e.id = vEktFk; SET @isTriggerDisabled = TRUE; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.item , 1 - FROM edi.ekt e + SELECT vItemFk, t.id , e.item , 1 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Producto' WHERE e.id = vEktFk AND NOT ISNULL(e.item); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.cat , 3 - FROM edi.ekt e + SELECT vItemFk, t.id , e.cat , 3 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Calidad' WHERE e.id = vEktFk AND NOT ISNULL(e.cat); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , s.company_name , 4 - FROM edi.ekt e + SELECT vItemFk, t.id , s.company_name , 4 + FROM edi.ekt e JOIN edi.supplier s ON s.supplier_id = e.pro JOIN vn.tag t ON t.`name` = 'Productor' WHERE e.id = vEktFk AND NOT ISNULL(s.company_name); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s1, 5 + SELECT vItemFk, t.id , e.s1, 5 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 1 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 1 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s1 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s1); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s2, 6 + SELECT vItemFk, t.id , e.s2, 6 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 2 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 2 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s2 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s2); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s3, 7 + SELECT vItemFk, t.id , e.s3, 7 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` - AND eif.presentation_order = 3 + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + AND eif.presentation_order = 3 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s3 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s3); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s4, 8 + SELECT vItemFk, t.id , e.s4, 8 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 4 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s4 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s4); - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s5, 9 + SELECT vItemFk, t.id , e.s5, 9 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 5 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s5 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s5); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id , e.s6, 10 + SELECT vItemFk, t.id , e.s6, 10 FROM edi.ekt e - LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` + LEFT JOIN edi.item_feature eif ON eif.item_id = e.`ref` AND eif.presentation_order = 6 AND eif.expiry_date IS NULL - LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature + LEFT JOIN edi.`value` ev ON ev.type_id = eif.feature AND e.s6 = ev.type_value JOIN vn.tag t ON t.ediTypeFk = eif.feature WHERE e.id = vEktFk AND NOT ISNULL(e.s6); INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) - SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 - FROM edi.ekt e + SELECT vItemFk, t.id, IFNULL(ink.name, ik.color), 11 + FROM edi.ekt e JOIN vn.tag t ON t.`name` = 'Color' - LEFT JOIN edi.feature f ON f.item_id = e.`ref` + LEFT JOIN edi.feature f ON f.item_id = e.`ref` LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1' LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value LEFT JOIN vn.itemInk ik ON ik.longName = e.item WHERE e.id = vEktFk - AND ( ink.name IS NOT NULL + AND ( ink.name IS NOT NULL OR ik.color IS NOT NULL) LIMIT 1; @@ -10016,7 +10016,7 @@ BEGIN sender = vSender, senderFk = vSenderId, messageId = vMessageId; - + IF vIsDuplicated THEN SELECT id INTO vSelf FROM mail @@ -10838,7 +10838,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterInsert` AFTER INSERT ON `order` FOR EACH ROW -BEGIN +BEGIN IF NEW.address_id = 2850 THEN -- Fallo que se insertan no se sabe como tickets en este cliente CALL vn.mail_insert( @@ -10847,7 +10847,7 @@ BEGIN 'Creada order al address 2850', CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) ); - + END IF; END */;; DELIMITER ; @@ -10864,27 +10864,27 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` - AFTER UPDATE ON `order` - FOR EACH ROW -BEGIN - CALL stock.log_add('order', NEW.id, OLD.id); - - IF !(OLD.address_id <=> NEW.address_id) - OR !(OLD.company_id <=> NEW.company_id) - OR !(OLD.customer_id <=> NEW.customer_id) THEN - CALL order_requestRecalc(NEW.id); - END IF; - - IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN - -- Fallo que se actualiza no se sabe como tickets en este cliente - CALL vn.mail_insert( - 'jgallego@verdnatura.es', - 'noreply@verdnatura.es', - 'Actualizada order al address 2850', - CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `hedera`.`order_afterUpdate` + AFTER UPDATE ON `order` + FOR EACH ROW +BEGIN + CALL stock.log_add('order', NEW.id, OLD.id); + + IF !(OLD.address_id <=> NEW.address_id) + OR !(OLD.company_id <=> NEW.company_id) + OR !(OLD.customer_id <=> NEW.customer_id) THEN + CALL order_requestRecalc(NEW.id); + END IF; + + IF !(OLD.address_id <=> NEW.address_id) AND NEW.address_id = 2850 THEN + -- Fallo que se actualiza no se sabe como tickets en este cliente + CALL vn.mail_insert( + 'jgallego@verdnatura.es', + 'noreply@verdnatura.es', + 'Actualizada order al address 2850', + CONCAT(account.myUser_getName(), ' ha creado la order ',NEW.id) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10999,12 +10999,12 @@ DELIMITER ;; BEGIN DECLARE vIsFirst BOOL; - SELECT (first_row_stamp IS NULL) INTO vIsFirst - FROM `order` + SELECT (first_row_stamp IS NULL) INTO vIsFirst + FROM `order` WHERE id = NEW.orderFk; IF vIsFirst THEN - UPDATE `order` SET first_row_stamp = util.VN_NOW() + UPDATE `order` SET first_row_stamp = util.VN_NOW() WHERE id = NEW.orderFk; END IF; END */;; @@ -11593,7 +11593,7 @@ BEGIN IF vCount = 0 THEN RETURN FALSE; - END IF; + END IF; SELECT COUNT(*) > 0 INTO vHasRole @@ -11674,14 +11674,14 @@ BEGIN * @return tmp.ticketComponent * @return tmp.ticketLot * @return tmp.zoneGetShipped - */ + */ DECLARE vAgencyMode INT; - + SELECT a.agencyModeFk INTO vAgencyMode FROM myClient c JOIN vn.address a ON a.clientFk = c.id - WHERE a.id = vAddress; + WHERE a.id = vAddress; CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); @@ -11694,7 +11694,7 @@ BEGIN JOIN tmp.availableCalc a ON a.calcFk = c.calc_id WHERE c.available > 0 GROUP BY c.item_id; - + CALL vn.catalog_calculate(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -11796,7 +11796,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vSelf itemFk; CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -11836,7 +11836,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -11845,7 +11845,7 @@ BEGIN * @param vType The type id * @param vPrefix The article prefix to filter or %NULL for all * @return tmp.itemVisible Visible items - */ + */ DECLARE vPrefixLen SMALLINT; DECLARE vFilter VARCHAR(255) DEFAULT NULL; DECLARE vDateInv DATE DEFAULT vn2008.date_inv(); @@ -11854,13 +11854,13 @@ BEGIN GET DIAGNOSTICS CONDITION 1 @message = MESSAGE_TEXT; CALL vn.mail_insert( - 'cau@verdnatura.es', - NULL, + 'cau@verdnatura.es', + NULL, CONCAT('hedera.item_getVisible error: ', @message), CONCAT( - 'warehouse: ', IFNULL(vWarehouse, ''), - ', Fecha:', IFNULL(vDate, ''), - ', tipo: ', IFNULL(vType,''), + 'warehouse: ', IFNULL(vWarehouse, ''), + ', Fecha:', IFNULL(vDate, ''), + ', tipo: ', IFNULL(vType,''), ', prefijo: ', IFNULL(vPrefix,''))); RESIGNAL; END; @@ -11939,7 +11939,7 @@ BEGIN IF(p.depth > 0, p.depth, 0) depth, p.width, p.height, CEIL(s.quantity / t.packing) etiquetas FROM vn.item i - JOIN `filter` f ON f.itemFk = i.id + JOIN `filter` f ON f.itemFk = i.id JOIN currentStock s ON s.itemFk = i.id LEFT JOIN tmp t ON t.itemFk = i.id LEFT JOIN vn.packaging p ON p.id = t.packageFk @@ -12416,15 +12416,15 @@ BEGIN START TRANSACTION; - SELECT a.agencyModeFk, a.id + SELECT a.agencyModeFk, a.id INTO vAgencyMode, vAddressFk - FROM vn.address a + FROM vn.address a WHERE a.id = vAddressFk; - + SELECT deliveryMethodFk INTO vDeliveryMethodId FROM vn.agencyMode am WHERE am.id = vAgencyMode; - + IF vCompany IS NULL THEN SELECT defaultCompanyFk INTO vCompany @@ -12442,7 +12442,7 @@ BEGIN company_id = vCompany; SET vSelf = LAST_INSERT_ID(); - + CALL order_checkConfig(vSelf); COMMIT; @@ -12488,15 +12488,15 @@ BEGIN START TRANSACTION; - SELECT a.agencyModeFk, a.id + SELECT a.agencyModeFk, a.id INTO vAgencyMode, vAddress FROM myClient c JOIN vn.address a ON a.id = c.defaultAddressFk; - + SELECT deliveryMethodFk INTO vDeliveryMethodId FROM vn.agencyMode am WHERE am.id = vAgencyMode; - + IF vCompany IS NULL THEN SELECT defaultCompanyFk INTO vCompany @@ -12514,7 +12514,7 @@ BEGIN company_id = vCompany; SET vSelf = LAST_INSERT_ID(); - + CALL order_checkConfig(vSelf); COMMIT; @@ -12697,7 +12697,7 @@ BEGIN SELECT t.id ticketFk FROM myTicket t WHERE shipped BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59'); - + CALL vn.ticketGetTotal(NULL); SELECT v.id, IFNULL(v.landed, v.shipped) landed, @@ -12962,10 +12962,10 @@ BEGIN CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY - SELECT itemFk FROM orderRow + SELECT itemFk FROM orderRow WHERE orderFk = vSelf GROUP BY itemFk; - + CALL vn.catalog_calculate(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE tmp.item; @@ -13340,7 +13340,7 @@ BEGIN END; -- Carga los datos del pedido - SELECT o.date_send, o.address_id, o.note, a.clientFk, + SELECT o.date_send, o.address_id, o.note, a.clientFk, o.company_id, o.agency_id, c.isTaxDataChecked INTO vDelivery, vAddress, vNotes, vClientId, vCompanyId, vAgencyModeId, vIsTaxDataChecked @@ -13661,7 +13661,7 @@ BEGIN INTO vDelivery, vAddress, vAgencyMode FROM `order` WHERE id = vSelf; - + CALL vn.available_calc(vDelivery, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable; @@ -13703,7 +13703,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; CREATE TEMPORARY TABLE tmp.addressCompany (INDEX (addressFk, companyFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT DISTINCT o.address_id addressFk, o.company_id companyFk FROM tmp.`order` tmpOrder JOIN hedera.`order` o ON o.id = tmpOrder.orderFk; @@ -13738,7 +13738,7 @@ BEGIN JOIN vn.taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpOrder.orderFk, pgc.`code`, pgc.rate HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.orderAmount; CREATE TEMPORARY TABLE tmp.orderAmount (INDEX (orderFk)) @@ -13747,7 +13747,7 @@ BEGIN SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax FROM tmp.orderTax GROUP BY orderFk, `code`; - + DROP TEMPORARY TABLE tmp.addressTaxArea; END ;; DELIMITER ; @@ -13817,7 +13817,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.`order` ENGINE = MEMORY SELECT vSelf orderFk; - + CALL order_getTax; SELECT IFNULL(SUM(taxableBase), 0.0), IFNULL(SUM(tax), 0.0) @@ -13908,7 +13908,7 @@ proc: BEGIN FROM orderRow r JOIN orderRowComponent c ON c.rowFk = r.id WHERE r.orderFk = vSelf; - + UPDATE orderRow r LEFT JOIN tmp.ticketComponentPrice p ON p.warehouseFk = r.warehouseFk @@ -13933,7 +13933,7 @@ proc: BEGIN ON t.id = c.componentFk AND (t.classRate IS NULL OR t.classRate = r.rate) WHERE r.orderFk = vSelf; - + CALL vn.ticketCalculatePurge; END IF; @@ -14461,13 +14461,13 @@ p: BEGIN AND DATE(FECHA) = vDate AND EURODEBE = vAmount LIMIT 1; - + -- Actualiza la transaccion UPDATE tpvTransaction SET response = NULL, status = 'started' WHERE id = vSelf; - + COMMIT; END ;; DELIMITER ; @@ -14500,7 +14500,7 @@ BEGIN UPDATE userSession SET userVisitFk = vUserVisit WHERE ssid = vSsid; - + DELETE FROM userSession WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, util.VN_NOW()); END ;; @@ -14624,7 +14624,7 @@ BEGIN UPDATE visitAgent SET firstAccessFk = vAccessId WHERE id = vAgentId; END IF; - + -- Returns the visit info SELECT vVisit visit, vAccessId access; @@ -15333,7 +15333,7 @@ BEGIN WHILE vI < vLen DO SET vChr = SUBSTR(vPhone, vI + 1, 1); - + IF vChr REGEXP '^[0-9]$' THEN SET vNewPhone = CONCAT(vNewPhone, vChr); @@ -15341,7 +15341,7 @@ BEGIN THEN SET vNewPhone = CONCAT(vNewPhone, '00'); END IF; - + SET vI = vI + 1; END WHILE; @@ -15440,18 +15440,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sip_getExtension`(vUserId INT(10)) BEGIN - + /* * Devuelve la extensión pbx del usuario - * - * @param vUserId Id del usuario - * + * + * @param vUserId Id del usuario + * */ SELECT extension - FROM sip s + FROM sip s WHERE s.user_id = vUserId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -16239,22 +16239,22 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `company_getCode`(vCompanyFk INT) RET READS SQL DATA BEGIN /** - * Devuelve la correspondencía del código de empresa de sage. + * Devuelve la correspondencía del código de empresa de sage. * Tiene en cuenta el entorno - * + * * @param vSelf Id de empresa de verdnatura * @return Código de empresa sage */ DECLARE vCompanySageFk INT(2); - - SELECT IF(c.environment = 'production', - co.companyCode, + + SELECT IF(c.environment = 'production', + co.companyCode, co.companyCodeTest ) INTO vCompanySageFk FROM util.config c JOIN vn.company co WHERE co.id = vCompanyFk; - + RETURN vCompanySageFk; END ;; DELIMITER ; @@ -16273,12 +16273,12 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `accountingMovements_add`( - vYear INT, + vYear INT, vCompanyFk INT ) BEGIN /** - * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta + * Traslada la info de contabilidad generada en base a vn.XDiario a la tabla sage.movConta * para poder ejecutar posteriormente el proceso de importación de datos de SQL Server * Solo traladará los asientos marcados con el campo vn.XDiario.enlazadoSage = FALSE * @vYear Año contable del que se quiere trasladar la información @@ -16594,8 +16594,8 @@ BEGIN mci.FechaFacturaOriginal = x.FECHA_EX, mci.SuFacturaNo = x.FACTURAEX, mci.FechaOperacion = x.FECHA_OP, - mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + mci.ImporteFactura = mci.ImporteFactura + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16614,7 +16614,7 @@ BEGIN mci.CodigoIva2 = vTaxImportFk, mci.IvaDeducible2 = TRUE, mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16632,8 +16632,8 @@ BEGIN mci.CodigoTransaccion3 = vDuaTransactionFk , mci.CodigoIva3 = vTaxImportSuperReducedFk, mci.IvaDeducible3 = TRUE, - mci.ImporteFactura = mci.ImporteFactura + - x.BASEEURO + + mci.ImporteFactura = mci.ImporteFactura + + x.BASEEURO + CAST((x.IVA / 100) * x.BASEEURO AS DECIMAL(10, 2)) WHERE pm.description = 'HP Iva pendiente' AND mci.enlazadoSage = FALSE @@ -16667,14 +16667,14 @@ BEGIN OR CodigoTransaccion2 = vTransactionExportFk OR CodigoTransaccion3 = vTransactionExportFk OR CodigoTransaccion4 = vTransactionExportFk) - AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, + AND SiglaNacion IN (vCountryCanariasCode COLLATE utf8mb3_unicode_ci, vCountryCeutaMelillaCode COLLATE utf8mb3_unicode_ci); UPDATE movConta mc SET CodigoDivisa = 'USD', FactorCambio = TRUE, - ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, - ImporteAsiento / ImporteDivisa, + ImporteCambio = ABS( CAST( IF( ImporteDivisa <> 0 AND ImporteCambio = 0, + ImporteAsiento / ImporteDivisa, ImporteCambio) AS DECIMAL( 10, 2))) WHERE enlazadoSage = FALSE AND (ImporteCambio <> 0 OR ImporteDivisa <> 0 OR FactorCambio); @@ -16716,8 +16716,8 @@ BEGIN AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase) sub; IF vBookEntries IS NOT NULL THEN - SELECT util.notification_send ("book-entries-imported-incorrectly", - CONCAT('{"bookEntries":"', vBookEntries,'"}'), + SELECT util.notification_send ("book-entries-imported-incorrectly", + CONCAT('{"bookEntries":"', vBookEntries,'"}'), null); END IF; END ;; @@ -16798,8 +16798,8 @@ BEGIN IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion), IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'), - IF(cu.code = 'ES', - 1, + IF(cu.code = 'ES', + 1, IF((cu.isUeeMember AND c.isVies), 2, 4)), IFNULL(c.taxTypeSageFk,0), IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8mb3_unicode_ci, @@ -16877,10 +16877,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_add`(vInvoiceInFk INT, vX BEGIN /** * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * * @vInvoiceInFk Factura recibida * @vXDiarioFk Id tabla XDiario - */ + */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vBase DOUBLE; DECLARE vVat DOUBLE; @@ -16897,25 +16897,25 @@ BEGIN DECLARE vInvoiceTypeInformative VARCHAR(1); DECLARE vIsInformativeExportation BOOL DEFAULT FALSE; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT it.taxableBase, CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)), t.PorcentajeIva, it.transactionTypeSageFk, it.taxTypeSageFk, tty.isIntracommunity, - tt.ClaveOperacionDefecto + tt.ClaveOperacionDefecto FROM vn.invoiceIn i JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk JOIN taxType tty ON tty.id = t.CodigoIva JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk LEFT JOIN vn.dua d ON d.id = vInvoiceInFk - WHERE i.id = vInvoiceInFk + WHERE i.id = vInvoiceInFk AND d.id IS NULL; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; @@ -16938,22 +16938,22 @@ BEGIN vTaxCode, vIsIntracommunity, vOperationCode; - - IF vDone THEN + + IF vDone THEN LEAVE l; END IF; - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; - IF vOperationCode IS NOT NULL THEN + IF vOperationCode IS NOT NULL THEN UPDATE movContaIVA SET ClaveOperacionFactura = vOperationCode WHERE id = vXDiarioFk; END IF; - + SET vCounter = vCounter + 1; - CASE vCounter + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -16989,31 +16989,31 @@ BEGIN WHERE id = vXDiarioFk; ELSE SELECT vXDiarioFk INTO vXDiarioFk; - END CASE; + END CASE; IF vIsIntracommunity THEN UPDATE movContaIVA SET Intracomunitaria = TRUE WHERE id = vXDiarioFk; END IF; - - SET vTransactionCodeOld = vTransactionCode; - SET vTaxCodeOld = vTaxCode; - + + SET vTransactionCodeOld = vTransactionCode; + SET vTaxCodeOld = vTaxCode; + END LOOP; CLOSE vCursor; SELECT d.ASIEN AND x.ASIEN IS NULL INTO vIsInformativeExportation FROM vn.dua d - LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN + LEFT JOIN vn.XDiario x ON x.ASIEN = d.ASIEN AND x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci WHERE d.ASIEN = ( SELECT ASIEN - FROM vn.XDiario + FROM vn.XDiario WHERE id = vXDiarioFk) LIMIT 1; - + UPDATE movContaIVA mci JOIN tmp.invoiceIn ii ON ii.id = vInvoiceInFk JOIN vn.XDiario x ON x.id = mci.id @@ -17025,13 +17025,13 @@ BEGIN mci.Serie = ii.serial, mci.Factura = ii.id, mci.FechaFactura = ii.issued, - mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + - IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + - IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + + mci.ImporteFactura = IFNULL(mci.BaseIva1, 0) + IFNULL(mci.CuotaIva1, 0) + + IFNULL(mci.BaseIva2, 0) + IFNULL(mci.CuotaIva2, 0) + + IFNULL(mci.BaseIva3, 0) + IFNULL(mci.CuotaIva3, 0) + IFNULL(mci.BaseIva4, 0) + IFNULL(mci.CuotaIva4, 0), - mci.TipoFactura = IF(id.id, - IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), - IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), + mci.TipoFactura = IF(id.id, + IF( ii.serial = vSerialDua COLLATE utf8mb3_unicode_ci, vInvoiceTypeReceived, vInvoiceTypeInformative), + IF(vIsInformativeExportation,vInvoiceTypeInformative, vInvoiceTypeReceived)), mci.CodigoCuentaFactura = x.SUBCTA, mci.CifDni = IF(LEFT(TRIM(s.nif), 2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif), 3), s.nif), mci.Nombre = s.name, @@ -17059,7 +17059,7 @@ BEGIN JOIN (SELECT SUM(x2.BASEEURO) taxableBase, SUM(x2.EURODEBE) taxBase FROM vn.XDiario x1 JOIN vn.XDiario x2 ON x1.ASIEN = x2.ASIEN - WHERE x2.BASEEURO <> 0 + WHERE x2.BASEEURO <> 0 AND x1.id = vXDiarioFk )sub JOIN ClavesOperacion co ON co.Descripcion = 'Arrendamiento de locales de negocio' @@ -17067,8 +17067,8 @@ BEGIN mci.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', co.ClaveOperacionFactura_, mci.ClaveOperacionFactura), mci.BaseRetencion = IF (t.Retencion = 'ACTIVIDADES AGRICOLAS O GANADERAS', sub.taxableBase + sub.taxBase, sub.taxableBase), mci.PorRetencion = t.PorcentajeRetencion, - mci.ImporteRetencion = iit.taxableBase * - 1 - WHERE mci.id = vXDiarioFk + mci.ImporteRetencion = iit.taxableBase * - 1 + WHERE mci.id = vXDiarioFk AND e.name = 'Retenciones' AND id.id IS NULL; @@ -17091,10 +17091,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceIn_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas recibidas - * + * Traslada la info de contabilidad relacionada con las facturas recibidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17106,22 +17106,22 @@ BEGIN DECLARE vAccountTaxOutstanding VARCHAR(10); DECLARE vInvoiceTypeSended VARCHAR(1); DECLARE vCursor CURSOR FOR - SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, + SELECT IFNULL(x.CLAVE, x.FACTURA) invoiceInFk, x.id XDiarioFk - FROM vn.XDiario x + FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) FROM vn.XDiario x LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id - WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) - AND x.enlazadoSage = FALSE + WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8mb3_unicode_ci) + AND x.enlazadoSage = FALSE AND x.FECHA BETWEEN vDatedFrom AND vDatedTo - AND x.empresa_id = vCompanyFk + AND x.empresa_id = vCompanyFk ) sub ON sub.ASIEN = x.ASIEN WHERE x.CLAVE IS NOT NULL; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; @@ -17135,15 +17135,15 @@ BEGIN SELECT codeSage INTO vInvoiceTypeSended FROM invoiceType WHERE `code` ='sended'; - + DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua; CREATE TEMPORARY TABLE tmp.invoiceDua - SELECT x.id + SELECT x.id FROM vn.XDiario x JOIN vn.company c ON c.id = x.empresa_id JOIN (SELECT ASIEN - FROM vn.XDiario x - WHERE x.enlazadoSage = FALSE + FROM vn.XDiario x + WHERE x.enlazadoSage = FALSE AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8mb3_unicode_ci AND x.FECHA BETWEEN vDatedFrom AND vDatedTo )sub ON sub.ASIEN = x.ASIEN @@ -17161,7 +17161,7 @@ BEGIN FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo - UNION ALL + UNION ALL SELECT d.id, d.code, vSerialDua COLLATE utf8mb3_unicode_ci, @@ -17169,8 +17169,8 @@ BEGIN d.issued, FALSE, '' -- EUROS - FROM vn.dua d - WHERE d.issued IS NOT NULL + FROM vn.dua d + WHERE d.issued IS NOT NULL AND code IS NOT NULL; OPEN vCursor; @@ -17178,7 +17178,7 @@ BEGIN l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; CALL invoiceIn_add(vInvoiceFk, vXDiarioFk); @@ -17266,21 +17266,21 @@ BEGIN JOIN (SELECT x.ASIEN, x.id FROM vn.XDiario x JOIN(SELECT DISTINCT(x.ASIEN) ASIEN - FROM vn.XDiario x + FROM vn.XDiario x JOIN (SELECT DISTINCT(ASIEN) FROM vn.XDiario x - WHERE SUBCTA LIKE '472%' + WHERE SUBCTA LIKE '472%' AND x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo ) sub ON sub.ASIEN = x.ASIEN WHERE x.SUBCTA LIKE '477%' )sub2 ON sub2.ASIEN = x.ASIEN - WHERE x.CONTRA IS NOT NULL + WHERE x.CONTRA IS NOT NULL AND x.SUBCTA LIKE '477%' GROUP BY x.ASIEN )sub3 ON sub3.ASIEN = x.ASIEN; - + INSERT INTO movContaIVA (`id`, `CodigoDivisa`, @@ -17351,9 +17351,9 @@ BEGIN `FechaGrabacion`, `Intracomunitaria`, `moveData`) - SELECT * + SELECT * FROM tmp.movContaIVA; - + DROP TEMPORARY TABLE tmp.movContaIVA; END ;; @@ -17375,10 +17375,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_add`(IN vInvoiceOutFk INT, IN vXDiarioFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vMaxLengthName INT DEFAULT 35; @@ -17398,12 +17398,12 @@ BEGIN DECLARE vHasCustomsAccountingNote BOOL; DECLARE vCursor CURSOR FOR - SELECT oit.taxableBase, - oit.vat, - pgc.rate, - pgc.mod347, - pgcRE.rate, - oitRE.vat, + SELECT oit.taxableBase, + oit.vat, + pgc.rate, + pgc.mod347, + pgcRE.rate, + oitRE.vat, tc.transactionCode, tc.taxCode, tc.isIntracommunity, @@ -17412,7 +17412,7 @@ BEGIN JOIN vn.pgc ON pgc.code = oit.pgcFk LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk - LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk + LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk AND oitRE.pgcFk = e.equFk LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8mb3_unicode_ci' @@ -17428,12 +17428,12 @@ BEGIN WHERE ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioFk); SELECT codeSage INTO vInvoiceTypeSended - FROM invoiceType + FROM invoiceType WHERE code = IF(vHasCustomsAccountingNote, 'informative', 'sended'); - + DELETE FROM movContaIVA WHERE id = vXDiarioFk; - + INSERT INTO movContaIVA(id) VALUES (vXDiarioFk); OPEN vCursor; @@ -17450,13 +17450,13 @@ BEGIN vIsIntracommunity, vOperationCode; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; SET vCounter = vCounter + 1; - - CASE vCounter + + CASE vCounter WHEN 1 THEN UPDATE movContaIVA SET BaseIva1 = vBase, @@ -17497,7 +17497,7 @@ BEGIN CodigoTransaccion4 = vTransactionCode, CodigoIva4 = vTaxCode WHERE id = vXDiarioFk; - END CASE; + END CASE; UPDATE movContaIVA SET Exclusion347 = NOT vMod347, @@ -17508,7 +17508,7 @@ BEGIN END LOOP; CLOSE vCursor; - + UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutFk LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk @@ -17533,25 +17533,25 @@ BEGIN mci.MantenerAsiento = TRUE, mci.FechaFacturaOriginal = x.FECHA_EX WHERE mci.id = vXDiarioFk; - + SELECT correctedFk INTO vInvoiceOutCorrectedFk FROM vn.invoiceCorrection WHERE correctingFk = vInvoiceOutFk; - - IF vInvoiceOutCorrectedFk THEN + + IF vInvoiceOutCorrectedFk THEN UPDATE movContaIVA mci JOIN vn.invoiceOut i ON i.id = vInvoiceOutCorrectedFk JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk - JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, + JOIN (SELECT SUM(IF(IFNULL(e.vatFk, TRUE), iot.taxableBase, 0)) taxableBase, SUM(IF(IFNULL(e.vatFk, TRUE), iot.vat, 0)) vat, SUM(IF(IFNULL(e.vatFk, TRUE), 0, iot.vat)) equ FROM vn.invoiceOutTax iot - LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk + LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk ) tax JOIN ClavesOperacion co ON co.Descripcion = 'Factura rectificativa' SET mci.TipoRectificativa = 2, - mci.ClaseAbonoRectificativas = 1, + mci.ClaseAbonoRectificativas = 1, mci.FechaFacturaOriginal = i.issued, mci.FechaOperacion = i.issued, mci.BaseImponibleOriginal = tax.taxableBase, @@ -17582,10 +17582,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_manager`(vYear INT, vCompanyFk INT) BEGIN /** - * Traslada la info de contabilidad relacionada con las facturas emitidas - * + * Traslada la info de contabilidad relacionada con las facturas emitidas + * * @vYear Año contable del que se quiere trasladar la información - * @vCompany Empresa de la que se quiere trasladar datos + * @vCompany Empresa de la que se quiere trasladar datos */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -17602,7 +17602,7 @@ BEGIN JOIN (SELECT x.ASIEN, CONCAT(x.SERIE, x.FACTURA) refFk FROM vn.XDiario x WHERE x.enlazadoSage = FALSE - AND x.FACTURA + AND x.FACTURA AND x.empresa_id = vCompanyFk AND x.FECHA BETWEEN vDatedFrom AND vDatedTo GROUP BY refFk @@ -17611,19 +17611,19 @@ BEGIN )sub2 ON sub2.refFk = i.ref; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) INTO vDatedFrom, vDatedTo; - + OPEN vCursor; l: LOOP FETCH vCursor INTO vInvoiceFk, vXDiarioFk; - IF vDone THEN + IF vDone THEN LEAVE l; END IF; - + CALL invoiceOut_add(vInvoiceFk, vXDiarioFk); END LOOP; @@ -17649,7 +17649,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `pgc_add`(vCompanyFk INT) BEGIN /** - * Añade cuentas del plan general contable para exportarlos a Sage + * Añade cuentas del plan general contable para exportarlos a Sage * @vCompanyFk Empresa de la que se quiere trasladar datos */ TRUNCATE TABLE planCuentasPGC; @@ -17659,25 +17659,25 @@ BEGIN CodigoCuenta, Cuenta, ClienteOProveedor) - SELECT * + SELECT * FROM (SELECT company_getCode(vCompanyFk) companyFk, e.id accountFk, UCASE(e.name), '' FROM vn.expence e - UNION + UNION SELECT company_getCode(vCompanyFk), - b.account, + b.account, UCASE(b.bank), - '' + '' FROM vn.bank b WHERE b.isActive AND b.`account` - UNION + UNION SELECT CodigoEmpresa, CodigoCuenta, Nombre, - ClienteOProveedor + ClienteOProveedor FROM clientesProveedores)sub GROUP BY companyFk, accountFk; END ;; @@ -18026,7 +18026,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18150,7 +18150,7 @@ DELIMITER ;; BEGIN SET NEW.lack = NEW.quantity; SET NEW.isPicked = NEW.isPicked OR NEW.dated < util.VN_CURDATE(); - + CALL visible_log( NEW.isPicked, NEW.warehouseFk, @@ -18361,7 +18361,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSupplied = 0; OPEN vPicks; @@ -18377,7 +18377,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vSelf, vOutboundFk, vPickGranted, vPickQuantity); - + UPDATE outbound SET isSync = FALSE, lack = lack + vPickGranted @@ -18457,7 +18457,7 @@ BEGIN END IF; SET vSupplied = LEAST(vAvailable, vLack); - + IF vSupplied > 0 THEN SET vAvailable = vAvailable - vSupplied; UPDATE outbound @@ -18470,7 +18470,7 @@ BEGIN SET vSupplied = vSupplied + vSuppliedFromRequest; SET vAvailable = vAvailable - vSuppliedFromRequest; END IF; - + IF vSupplied > 0 THEN CALL inbound_addPick(vSelf, vOutboundFk, vSupplied); END IF; @@ -18599,7 +18599,7 @@ BEGIN DO RELEASE_LOCK('stock.log_sync'); RESIGNAL; END; - + IF !GET_LOCK('stock.log_sync', 30) THEN CALL util.throw('Lock timeout exceeded'); END IF; @@ -19070,7 +19070,7 @@ BEGIN SET vPickGranted = LEAST(vRequested - vSupplied, vPickQuantity); SET vSupplied = vSupplied + vPickGranted; CALL inbound_removePick(vInboundFk, vSelf, vPickGranted, vPickQuantity); - + UPDATE inbound SET isSync = FALSE, available = available + vPickGranted @@ -19510,11 +19510,11 @@ BEGIN WHILE vI < vLen DO SET vSpaceIni = vI; - + WHILE MID(vString, vI, 1) REGEXP '[[:space:]]' DO SET vI = vI + 1; END WHILE; - + SET vWordIni = vI; SET vI = vWordIni + 1; @@ -19551,11 +19551,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `crypt`(vText VARCHAR(255), vKey VARC BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.crypt(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19577,11 +19577,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `cryptOff`(vText VARCHAR(255), vKey V BEGIN DECLARE vResult VARCHAR(255); - + CALL vn.cryptOff(vText, vKey, vResult); RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19749,7 +19749,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `hasDateOverlapped`(vSarted1 DATE, vEnded1 DATE, vSarted2 DATE, vEnded2 DATE) RETURNS tinyint(1) DETERMINISTIC -BEGIN +BEGIN RETURN GREATEST(vSarted1, vSarted2) <= LEAST(vEnded1,vEnded2); @@ -19778,7 +19778,7 @@ BEGIN */ DECLARE vHashlen INT UNSIGNED; DECLARE vOpad, vIpad TINYBLOB; - + CASE vAlg WHEN 224 THEN SET vHashlen = 64; WHEN 256 THEN SET vHashlen = 64; @@ -19786,16 +19786,16 @@ BEGIN WHEN 512 THEN SET vHashlen = 128; ELSE CALL throw ('WRONG_ALGORYTHM_IDENTIFICATOR_USED'); END CASE; - + IF LENGTH(vKey) > vHashlen THEN SET vKey = UNHEX(SHA2(vKey, vAlg)); END IF; - + SET vKey = RPAD(vKey, vHashlen, 0x00); - + SET vIpad = stringXor(vKey, 0x36); SET vOpad = stringXor(vKey, 0x5C); - + RETURN SHA2(CONCAT(vOpad, UNHEX(SHA2(CONCAT(vIpad, vMsg), vAlg))), vAlg); END ;; DELIMITER ; @@ -19818,7 +19818,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `isLeapYear`(vYear INT) RETURNS tinyi BEGIN RETURN (DAYOFYEAR(CONCAT(vYear, "-02-29")) IS NOT NULL); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -19977,7 +19977,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `midnight`() RETURNS datetime READS SQL DATA BEGIN - + RETURN TIMESTAMP(util.VN_CURDATE(), '23:59:59'); END ;; @@ -20105,7 +20105,7 @@ BEGIN * modo 3. */ DECLARE vYear INT DEFAULT FLOOR(vYearWeek / 100); - + IF vYearWeek < YEARWEEK(CONCAT(vYear, '-12-31'), 3) THEN RETURN vYearWeek + 1; ELSE @@ -20211,16 +20211,16 @@ BEGIN */ DECLARE vLen, vPos INT UNSIGNED; DECLARE vResult MEDIUMBLOB; - + SET vLen = LENGTH(vString); SET vPos = 1; SET vResult = ''; - + WHILE vPos <= vLen DO SET vResult = CONCAT(vResult, LPAD(HEX( ORD(SUBSTR(vString, vPos, 1)) ^ vConst), 2, '0')); SET vPos = vPos + 1; END WHILE; - + RETURN UNHEX(vResult); END ;; DELIMITER ; @@ -20491,11 +20491,11 @@ BEGIN IF vYear = vCurYear THEN RETURN 'curYear'; END IF; - + IF vYear = vCurYear - 1 THEN RETURN 'lastYear'; END IF; - + IF vYear = vCurYear - 2 THEN RETURN 'twoYearsAgo'; END IF; @@ -20578,7 +20578,7 @@ BEGIN * @param vValue Valor de la variable */ DECLARE vIndex INT DEFAULT INSTR(USER(), '@'); - + INSERT INTO debug SET `connectionId` = CONNECTION_ID(), `user` = LEFT(USER(), vIndex - 1), @@ -20981,7 +20981,7 @@ BEGIN INSERT INTO tmp.time (dated) VALUES (vCurrentDate); SET vCurrentDate = DATE_ADD(vCurrentDate, INTERVAL 1 DAY); END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21375,11 +21375,11 @@ BEGIN END IF; IF NEW.isEqualizated IS NULL THEN - SELECT isEqualizated + SELECT isEqualizated INTO vIsEqualizated FROM client WHERE id = NEW.clientFk; - + SET NEW.isEqualizated = vIsEqualizated; END IF; END */;; @@ -21401,7 +21401,7 @@ DELIMITER ;; BEFORE UPDATE ON `address` FOR EACH ROW BEGIN - + SET NEW.editorFk = account.myUser_getId(); IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -21433,16 +21433,16 @@ DELIMITER ;; BEGIN -- Recargos de equivalencia distintos implican facturacion por consignatario IF NEW.isEqualizated != OLD.isEqualizated THEN - IF + IF (SELECT COUNT(*) FROM ( SELECT DISTINCT (isEqualizated = FALSE) as Equ - FROM address + FROM address WHERE clientFk = NEW.clientFk ) t1 ) > 1 - THEN - UPDATE client + THEN + UPDATE client SET hasToInvoiceByAddress = TRUE WHERE id = NEW.clientFk; END IF; @@ -21450,10 +21450,10 @@ BEGIN IF NEW.isDefaultAddress AND NEW.isActive = FALSE THEN CALL util.throw ('Cannot desactivate the default address'); END IF; - + IF NOT (NEW.isEqualizated <=> OLD.isEqualizated) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.addressFk = NEW.id AND t.refFk IS NULL; END IF; @@ -21870,8 +21870,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`autonomy_BI` BEFORE INSERT ON `autonomy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.geoFk = zoneGeo_new('autonomy', NEW.`name`, (SELECT geoFk FROM country WHERE id = NEW.countryFk)); END */;; @@ -21921,7 +21921,7 @@ DELIMITER ;; AFTER DELETE ON `autonomy` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21996,7 +21996,7 @@ DELIMITER ;; BEFORE INSERT ON `awb` FOR EACH ROW BEGIN - + SET NEW.year= year(util.VN_CURDATE()); @@ -22370,11 +22370,11 @@ DELIMITER ;; BEFORE INSERT ON `budgetNotes` FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -22468,7 +22468,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; @@ -22514,25 +22514,25 @@ BEGIN DECLARE isOverlapping BOOL; SET NEW.editorFk = account.myUser_getId(); - + IF NEW.ended IS NULL THEN SET NEW.payedHolidays = 0; END IF; IF !(OLD.started <=> NEW.started AND OLD.ended <=> NEW.ended) THEN - + SELECT COUNT(*) > 0 INTO isOverlapping FROM business b WHERE (util.hasDateOverlapped( - NEW.started, + NEW.started, IFNULL(NEW.ended, b.started), b.started, IFNULL(b.ended, NEW.started)) OR (NEW.ended <=> NULL AND b.ended <=> NULL)) AND b.id <> OLD.id AND workerFk = OLD.workerFk; - - IF isOverlapping THEN + + IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; @@ -22793,7 +22793,7 @@ trig: BEGIN END IF; END IF; IF NEW.quantity < 0 THEN - SET NEW.isIgnored = TRUE; + SET NEW.isIgnored = TRUE; END IF; END */;; DELIMITER ; @@ -22988,7 +22988,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`buy_beforeDelete` BEFORE DELETE ON buy FOR EACH ROW -BEGIN +BEGIN IF OLD.printedStickers <> 0 THEN CALL util.throw("it is not possible to delete buys with printed labels "); END IF; @@ -24192,7 +24192,7 @@ BEGIN END IF; SET NEW.accountingAccount = 4300000000 + NEW.id; - + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END */;; DELIMITER ; @@ -24217,7 +24217,7 @@ BEGIN DECLARE vPayMethodFk INT; SET NEW.editorFk = account.myUser_getId(); - + -- Comprueba que el formato de los teléfonos es válido IF !(NEW.phone <=> OLD.phone) AND (NEW.phone <> '') THEN @@ -24299,18 +24299,18 @@ BEGIN IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = 0 WHERE clientFk = NEW.id; - + UPDATE `address` SET isDefaultAddress = 1 - WHERE id = NEW.defaultAddressFk; + WHERE id = NEW.defaultAddressFk; END IF; IF NOT (NEW.provinceFk <=> OLD.provinceFk) OR NOT (NEW.isVies <=> OLD.isVies) THEN INSERT IGNORE INTO ticketRecalc (ticketFk) - SELECT id FROM ticket t + SELECT id FROM ticket t WHERE t.clientFk = NEW.id AND t.refFk IS NULL; END IF; - + IF NOT NEW.isActive THEN UPDATE account.`user` SET active = FALSE @@ -24506,15 +24506,15 @@ DELIMITER ;; AFTER INSERT ON clientCredit FOR EACH ROW BEGIN - + DECLARE vSender VARCHAR(50); SELECT u.name INTO vSender FROM account.`user` u WHERE u.id = NEW.workerFk; - + IF vSender IN ('juanvi','pepe') THEN - + CALL `vn`.`mail_insert`('pako@verdnatura.es', NULL, CONCAT('ClientCredit ',vSender, ' ', NEW.clientFk, ' ' , NEW.amount, ' €'), @@ -25095,7 +25095,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`cmr_beforeDelete` BEFORE DELETE ON `cmr` FOR EACH ROW -BEGIN +BEGIN IF NOT (OLD.companyFk <=> NULL AND OLD.addressFromFk <=> NULL AND OLD.packagesList <=> NULL) THEN CALL util.throw("Can not delete cmr, fields required not empty"); END IF; @@ -25226,39 +25226,39 @@ CREATE TABLE `collection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` - BEFORE UPDATE ON `collection` - FOR EACH ROW -BEGIN - - DECLARE vStateFk INT; - DECLARE vTotalLines INT; - DECLARE vPickedLines INT; - - IF NEW.saleTotalCount <= NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount - OR NEW.salePickedCount != OLD.salePickedCount) - THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'PREPARED'; - - SET NEW.stateFk = vStateFk; - - END IF; - - IF NEW.saleTotalCount > NEW.salePickedCount - AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN - - SELECT id INTO vStateFk - FROM vn.state - WHERE code = 'ON_PREPARATION'; - - SET NEW.stateFk = vStateFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`collection_BEFORE_UPDATE` + BEFORE UPDATE ON `collection` + FOR EACH ROW +BEGIN + + DECLARE vStateFk INT; + DECLARE vTotalLines INT; + DECLARE vPickedLines INT; + + IF NEW.saleTotalCount <= NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount + OR NEW.salePickedCount != OLD.salePickedCount) + THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'PREPARED'; + + SET NEW.stateFk = vStateFk; + + END IF; + + IF NEW.saleTotalCount > NEW.salePickedCount + AND (NEW.saleTotalCount != OLD.saleTotalCount OR NEW.salePickedCount != OLD.salePickedCount) THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE code = 'ON_PREPARATION'; + + SET NEW.stateFk = vStateFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26194,7 +26194,7 @@ BEGIN UPDATE `client` c JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26463,7 +26463,7 @@ BEGIN JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk WHERE b.departmentFk = OLD.id; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -26483,9 +26483,9 @@ DELIMITER ;; AFTER DELETE ON `department` FOR EACH ROW BEGIN - + UPDATE vn.department_recalc SET isChanged = TRUE; - + UPDATE vn.business b JOIN vn.department d ON d.id = b.departmentFk SET b.departmentFk = d.parentFk @@ -26556,6 +26556,7 @@ CREATE TABLE `deviceLog` ( `created` timestamp NOT NULL DEFAULT current_timestamp(), `nameApp` varchar(45) DEFAULT NULL, `versionApp` varchar(45) DEFAULT NULL, + `serialNumber` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), KEY `deviceLog_FK` (`userFk`), CONSTRAINT `deviceLog_FK` FOREIGN KEY (`userFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE @@ -26988,20 +26989,20 @@ DELIMITER ;; BEGIN DECLARE vHardCopyNumber INT; DECLARE vDmsTypeCode INT; - + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN CALL util.throw('this warehouse has not dms'); END IF; IF NEW.hasFile THEN - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms WHERE warehouseFk = NEW.warehouseFk; - + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); END IF; - - SELECT code INTO vDmsTypeCode + + SELECT code INTO vDmsTypeCode FROM dmsType WHERE NEW.dmsTypeFk = id; IF (vDmsTypeCode ='ticket') THEN UPDATE ticket SET isSigned = 1 WHERE id = NEW.reference; @@ -27021,31 +27022,31 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` - BEFORE UPDATE ON `dms` - FOR EACH ROW -BEGIN - DECLARE vHardCopyNumber INT; - - IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) - OR - (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN - - IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN - SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); - END IF; - - SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber - FROM dms - WHERE warehouseFk = NEW.warehouseFk; - - SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); - END IF; - - IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN - - SET NEW.hasFile = 0; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeUpdate` + BEFORE UPDATE ON `dms` + FOR EACH ROW +BEGIN + DECLARE vHardCopyNumber INT; + + IF (NEW.hasFile <> 0) AND (OLD.hasFile = 0) AND (NEW.hardCopyNumber IS NULL) + OR + (NEW.hardCopyNumber = OLD.hardCopyNumber AND OLD.warehouseFk <> NEW.warehouseFk) THEN + + IF (SELECT NOT hasDms FROM warehouse WHERE id = NEW.warehouseFk) THEN + SET NEW.warehouseFk = (SELECT id FROM warehouse WHERE name = 'Algemesi'); + END IF; + + SELECT 1 + MAX(hardCopyNumber) INTO vHardCopyNumber + FROM dms + WHERE warehouseFk = NEW.warehouseFk; + + SET NEW.hardCopyNumber = IFNULL(vHardCopyNumber,1); + END IF; + + IF ((NEW.hardCopyNumber = 0) OR NEW.hardCopyNumber IS NULL) AND (OLD.hardCopyNumber <> 0) THEN + + SET NEW.hasFile = 0; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -27064,14 +27065,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`dms_beforeDelete` BEFORE DELETE ON `dms` FOR EACH ROW -BEGIN +BEGIN DECLARE vCanNotBeDeleted INT; - SELECT COUNT(*) INTO vCanNotBeDeleted - FROM dmsType dt - WHERE NOT (code <=> 'trash') + SELECT COUNT(*) INTO vCanNotBeDeleted + FROM dmsType dt + WHERE NOT (code <=> 'trash') AND dt.id = OLD.dmsTypeFk; - - IF vCanNotBeDeleted THEN + + IF vCanNotBeDeleted THEN CALL util.throw('A dms can not be deleted'); END IF; END */;; @@ -27649,7 +27650,7 @@ BEGIN END IF; IF NOT (NEW.travelFk <=> OLD.travelFk) - OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN + OR NOT (NEW.currencyFk <=> OLD.currencyFk) THEN SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); END IF; END */;; @@ -28149,17 +28150,17 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id + SELECT IFNULL(MAX(counter),0) +1 INTO intcounter + FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticket = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; SET NEW.`counter` = intcounter; @@ -28186,9 +28187,9 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); IF NEW.counter <> OLD.counter THEN - IF (SELECT COUNT(*) FROM expedition e + IF (SELECT COUNT(*) FROM expedition e INNER JOIN ticket t1 ON e.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) WHERE t1.id = NEW.ticketFk AND counter = NEW.counter) > 0 THEN SET NEW.id = NULL; END IF; @@ -28212,11 +28213,11 @@ DELIMITER ;; BEFORE DELETE ON `expedition` FOR EACH ROW BEGIN - UPDATE ticket t - SET packages = (SELECT COUNT(counter)-1 + UPDATE ticket t + SET packages = (SELECT COUNT(counter)-1 FROM expedition e WHERE e.ticketFk = OLD.ticketFk and e.freightItemFk) - WHERE t.id = OLD.ticketFk; - + WHERE t.id = OLD.ticketFk; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28355,13 +28356,13 @@ DELIMITER ;; BEGIN DECLARE vNewPosition INT; - + SELECT MAX(position) + 1 INTO vNewPosition FROM vn.expeditionPallet WHERE truckFk = NEW.truckFk; - + SET NEW.position = IFNULL(vNewPosition,1); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28460,7 +28461,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28521,9 +28522,9 @@ DELIMITER ;; BEFORE INSERT ON expeditionState FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28547,7 +28548,7 @@ BEGIN UPDATE vn.expedition e SET e.stateTypeFk = NEW.typeFk WHERE e.id = NEW.expeditionFk; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29578,42 +29579,42 @@ BEGIN DECLARE vWithholdingSageFk INT; SET NEW.editorFk = account.myUser_getId(); - - SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + + SELECT withholdingSageFk INTO vWithholdingSageFk + FROM vn.supplier WHERE id = NEW.supplierFk; - SET NEW.withholdingSageFk = vWithholdingSageFk; - - SELECT countryFk, isActive INTO vIssuingCountry, vActive - FROM vn.supplier + SET NEW.withholdingSageFk = vWithholdingSageFk; + + SELECT countryFk, isActive INTO vIssuingCountry, vActive + FROM vn.supplier WHERE id = NEW.supplierFk; - - SELECT countryFk INTO vhostCountry - FROM vn.supplier + + SELECT countryFk INTO vhostCountry + FROM vn.supplier WHERE id = NEW.companyFk; IF vActive = 0 THEN CALL util.throw('INACTIVE_PROVIDER'); END IF; - - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) ) THEN CALL util.throw('reference duplicated'); END IF; - + SELECT CASE WHEN (SELECT account FROM vn.supplier where id = NEW.supplierFk) LIKE '___3______' THEN 'C' - WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + WHEN (SELECT vIssuingCountry=vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'R' - WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' + WHEN (SELECT vIssuingCountry <> vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry + where p1.CEE < 2 and p2.CEE < 2) = 1 THEN 'E' WHEN (SELECT vIssuingCountry<>vhostCountry from vn.country p1 join vn.country p2 ON p2.id = vhostCountry AND p1.id = vIssuingCountry - where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' + where NOT p1.CEE < 2 AND not p1.id = 1) = 1 THEN 'W' END INTO vSerie; - + SET NEW.serial = IFNULL(vSerie,'R'); END */;; @@ -29640,9 +29641,9 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); - IF (SELECT COUNT(*) FROM vn.invoiceIn - WHERE supplierRef = NEW.supplierRef - AND supplierFk = NEW.supplierFk + IF (SELECT COUNT(*) FROM vn.invoiceIn + WHERE supplierRef = NEW.supplierRef + AND supplierFk = NEW.supplierFk AND YEAR(issued) = YEAR(NEW.issued) AND id <> NEW.id ) THEN @@ -29652,7 +29653,7 @@ BEGIN IF NEW.supplierFk != OLD.supplierFk THEN CALL supplier_checkIsActive(NEW.supplierFk); SELECT withholdingSageFk INTO vWithholdingSageFk - FROM vn.supplier + FROM vn.supplier WHERE id = NEW.supplierFk; SET NEW.withholdingSageFk = vWithholdingSageFk; END IF; @@ -29677,23 +29678,23 @@ DELIMITER ;; FOR EACH ROW BEGIN - IF NEW.issued != OLD.issued + IF NEW.issued != OLD.issued OR NEW.currencyFk != OLD.currencyFk THEN UPDATE invoiceInTax iit JOIN invoiceIn ii ON ii.id = iit.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iit.taxableBase = IF(iit.foreignValue IS NULL, iit.taxableBase, iit.foreignValue / rr.value) WHERE ii.id = NEW.id; - + UPDATE invoiceInDueDay iidd JOIN invoiceIn ii ON ii.id = iidd.invoiceInFk LEFT JOIN referenceRate rr ON rr.dated = ii.issued - AND rr.currencyFk = ii.currencyFk + AND rr.currencyFk = ii.currencyFk SET iidd.amount = IF(iidd.foreignValue IS NULL, iidd.amount, iidd.foreignValue / rr.value) - WHERE ii.id = NEW.id; - + WHERE ii.id = NEW.id; + END IF; END */;; @@ -29787,13 +29788,13 @@ BEGIN DECLARE vIsNotified BOOLEAN; SET NEW.editorFk = account.myUser_getId(); - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -29801,12 +29802,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount, '€ en una fecha pasada en la recibida ', NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29829,13 +29830,13 @@ BEGIN DECLARE vIsNotified BOOLEAN; SET NEW.editorFk = account.myUser_getId(); - - SELECT isNotified INTO vIsNotified - FROM vn.invoiceIn ii + + SELECT isNotified INTO vIsNotified + FROM vn.invoiceIn ii JOIN vn.supplier s ON s.id = ii.supplierFk JOIN vn.payMethod pm ON pm.id = s.payMethodFk WHERE ii.id = NEW.invoiceInFk; - + IF (NEW.dueDated <= util.VN_CURDATE() AND vIsNotified) THEN CALL mail_insert( @@ -29843,12 +29844,12 @@ BEGIN 'begonya@verdnatura.es', 'Añadido vencimiento en el pasado', CONCAT( - account.myUser_getName(), ' ha añadido un vencimiento de ', + account.myUser_getName(), ' ha añadido un vencimiento de ', NEW.amount,'€ en una fecha pasada en la recibida ',NEW.invoiceInFk ) ); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -30433,6 +30434,7 @@ CREATE TABLE `item` ( `editorFk` int(10) unsigned DEFAULT NULL, `recycledPlastic` int(11) DEFAULT NULL, `nonRecycledPlastic` int(11) DEFAULT NULL, + `minQuantity` int(10) unsigned DEFAULT NULL COMMENT 'Cantidad mínima para una línea de venta', PRIMARY KEY (`id`), UNIQUE KEY `item_supplyResponseFk_idx` (`supplyResponseFk`), KEY `Color` (`inkFk`), @@ -30984,15 +30986,15 @@ BEGIN IF NEW.itemFk IN (95, 98) THEN SET NEW.cm3 = 0; END IF; - + IF !(NEW.cm3delivery <=> OLD.cm3delivery) THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.itemCost ic JOIN vn.sale s ON s.itemFk = ic.itemFk - JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk + JOIN vn.ticket t ON t.id = s.ticketFk AND t.warehouseFk = ic.warehouseFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND ic.itemFk = NEW.itemFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -31312,10 +31314,10 @@ DELIMITER ;; BEFORE INSERT ON `itemShelving` FOR EACH ROW BEGIN - + SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31424,8 +31426,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_BEFORE_DELETE` BEFORE DELETE ON `itemShelving` FOR EACH ROW -INSERT INTO vn.itemShelvingLog(itemShelvingFk, - workerFk, +INSERT INTO vn.itemShelvingLog(itemShelvingFk, + workerFk, accion, shelvingFk, itemFk) @@ -31609,7 +31611,7 @@ DELIMITER ;; BEGIN UPDATE vn.sale - SET isPicked = TRUE + SET isPicked = TRUE WHERE id = NEW.saleFk; END */;; @@ -31799,9 +31801,9 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemTag_beforeUpdate` BEFORE UPDATE ON `itemTag` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF !(OLD.`value` <=> NEW.`value`) OR !(OLD.intValue <=> NEW.intValue) THEN SET NEW.intValue = itemTag_getIntValue(NEW.`value`); @@ -31834,7 +31836,7 @@ trig: BEGIN IF @isTriggerDisabled OR visTriggerDisabled THEN LEAVE trig; END IF; - + SET vItemFk = NEW.itemFk; DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item @@ -32341,7 +32343,7 @@ DELIMITER ;; BEFORE INSERT ON `machine` FOR EACH ROW BEGIN - + SET NEW.workerFk = vn.getUser(); END */;; @@ -32475,9 +32477,9 @@ DELIMITER ;; BEGIN IF NEW.sender IS NOT NULL THEN - + SET NEW.receiver = NEW.sender; - + END IF; END */;; @@ -32540,8 +32542,8 @@ DELIMITER ;; FOR EACH ROW BEGIN IF (NEW.code IS NULL) THEN - SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT - FROM information_schema.TABLES + SET NEW.code=CONCAT(NEW.clientFk,'-',(SELECT AUTO_INCREMENT + FROM information_schema.TABLES WHERE TABLE_SCHEMA='vn' and TABLE_NAME='mandate')); END IF; END */;; @@ -33535,7 +33537,7 @@ DELIMITER ;; BEGIN -- SET new.`code` = CONCAT(new.`column`,' - ',new.`row`) ; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33660,13 +33662,13 @@ BEGIN SELECT account INTO cuenta_banco FROM bank WHERE id = NEW.bankFk; - + SELECT account INTO cuenta_proveedor FROM supplier WHERE id = NEW.supplierFk; - + CALL vn.ledger_next(vNewBookEntry); - + INSERT INTO XDiario ( ASIEN, FECHA, SUBCTA, @@ -33692,7 +33694,7 @@ BEGIN cuenta_banco CONTRA, NEW.amount EURODEBE, 0 EUROHABER) gf; - + IF NEW.bankingFees <> 0 THEN INSERT INTO XDiario ( ASIEN, FECHA, @@ -33714,7 +33716,7 @@ BEGIN FROM supplier s JOIN country c ON s.countryFk = c.id WHERE s.id = NEW.supplierFk; - END IF; + END IF; END IF; SET NEW.dueDated = IFNULL(NEW.dueDated, NEW.received); @@ -33722,15 +33724,15 @@ BEGIN SELECT isActive INTO isSupplierActive FROM supplier WHERE id = NEW.supplierFk; - + IF isSupplierActive = FALSE THEN CALL util.throw('SUPPLIER_INACTIVE'); END IF; - + IF ISNULL(NEW.workerFk) THEN SET NEW.workerFk = account.myUser_getId(); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33752,12 +33754,12 @@ DELIMITER ;; BEGIN DECLARE vIsPayMethodChecked BOOLEAN; DECLARE vEmail VARCHAR(150); - + SELECT isPayMethodChecked INTO vIsPayMethodChecked FROM supplier WHERE id = NEW.supplierFk; - - + + IF vIsPayMethodChecked = FALSE THEN SELECT notificationEmail INTO vEmail @@ -34639,11 +34641,11 @@ DELIMITER ;; BEFORE INSERT ON projectNotes FOR EACH ROW BEGIN - + IF ISNULL(NEW.userFk) THEN - + SET NEW.userFk = account.myUser_getId(); - + END IF; END */;; @@ -34804,10 +34806,10 @@ DELIMITER ;; BEFORE INSERT ON `province` FOR EACH ROW BEGIN - + SET NEW.geoFk = zoneGeo_new('province', NEW.`name`, (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END */;; @@ -34828,14 +34830,14 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_beforeUpdate` BEFORE UPDATE ON `province` FOR EACH ROW -BEGIN - +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - + SET NEW.countryFk = (SELECT a.countryFk FROM vn.autonomy a WHERE a.id = NEW.autonomyFk); END IF; - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34851,19 +34853,19 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` - AFTER UPDATE ON `province` - FOR EACH ROW -BEGIN - IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN - CALL zoneGeo_setParent(NEW.geoFk, - (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); - END IF; - - IF !(OLD.`name` <=> NEW.`name`) THEN - UPDATE zoneGeo SET `name` = NEW.`name` - WHERE id = NEW.geoFk; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`province_afterUpdate` + AFTER UPDATE ON `province` + FOR EACH ROW +BEGIN + IF !(OLD.autonomyFk <=> NEW.autonomyFk) THEN + CALL zoneGeo_setParent(NEW.geoFk, + (SELECT geoFk FROM autonomy WHERE id = NEW.autonomyFk)); + END IF; + + IF !(OLD.`name` <=> NEW.`name`) THEN + UPDATE zoneGeo SET `name` = NEW.`name` + WHERE id = NEW.geoFk; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34883,7 +34885,7 @@ DELIMITER ;; AFTER DELETE ON `province` FOR EACH ROW BEGIN - CALL zoneGeo_delete(OLD.geoFk); + CALL zoneGeo_delete(OLD.geoFk); END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35107,20 +35109,20 @@ CREATE TABLE `receipt` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` - BEFORE INSERT ON `receipt` - FOR EACH ROW -BEGIN - DECLARE vIsAutoConciliated BOOLEAN; - - IF NEW.isConciliate = FALSE THEN - SELECT isAutoConciliated INTO vIsAutoConciliated - FROM accounting a - JOIN accountingType at2 ON at2.id = a.accountingTypeFk - WHERE a.id = NEW.bankFk; - - SET NEW.isConciliate = vIsAutoConciliated; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_beforeInsert` + BEFORE INSERT ON `receipt` + FOR EACH ROW +BEGIN + DECLARE vIsAutoConciliated BOOLEAN; + + IF NEW.isConciliate = FALSE THEN + SELECT isAutoConciliated INTO vIsAutoConciliated + FROM accounting a + JOIN accountingType at2 ON at2.id = a.accountingTypeFk + WHERE a.id = NEW.bankFk; + + SET NEW.isConciliate = vIsAutoConciliated; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35176,18 +35178,18 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` - AFTER UPDATE ON `receipt` - FOR EACH ROW -BEGIN - IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN - CALL mail_insert( - 'finanzas@verdnatura.es', - NULL, - CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), - CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) - ); - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`receipt_afterUpdate` + AFTER UPDATE ON `receipt` + FOR EACH ROW +BEGIN + IF NEW.isConciliate = FALSE AND NEW.payed > OLD.payed THEN + CALL mail_insert( + 'finanzas@verdnatura.es', + NULL, + CONCAT('Cambios de recibos del cliente: ', NEW.clientFk), + CONCAT('Se ha cambiado el recibo: ', NEW.Id, ' de ', OLD.payed, ' a ', NEW.payed) + ); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35535,7 +35537,7 @@ BEGIN DECLARE vDefaultAgencyModeFk INT; SET NEW.editorFk = account.myUser_getId(); - + SET NEW.commissionWorkCenterFk = ( SELECT IFNULL(b.workCenterFK, r.defaultWorkCenterFk) FROM vn.routeConfig r @@ -35569,7 +35571,7 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterInsert` AFTER INSERT ON `route` FOR EACH ROW -BEGIN +BEGIN CALL route_calcCommission(NEW.id); END */;; DELIMITER ; @@ -35591,16 +35593,16 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vKmMax INT; - + SET NEW.editorFk = account.myUser_getId(); - + IF NEW.isOk <> FALSE AND OLD.isOk = FALSE THEN - SET NEW.m3 = ( SELECT SUM(litros)/1000 - FROM vn.saleVolume s - JOIN vn.ticket t ON s.ticketFk = t.id + SET NEW.m3 = ( SELECT SUM(litros)/1000 + FROM vn.saleVolume s + JOIN vn.ticket t ON s.ticketFk = t.id WHERE t.routeFk = NEW.id); END IF; - + IF NEW.kmEnd < NEW.kmStart AND NEW.kmEnd <> 0 THEN CALL util.throw ('KmEnd menor que kmStart'); END IF; @@ -35630,18 +35632,18 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`route_afterUpdate` AFTER UPDATE ON `route` FOR EACH ROW -BEGIN +BEGIN IF IFNULL(NEW.gestdocFk,0) <> IFNULL(OLD.gestdocFk,0) AND NEW.gestdocFk > 0 THEN -- JGF 09/09/14 cuando se añade un gestdoc a una ruta, se le asigna automagicamente a todos sus Tickets - + -- Inserta el gestdoc en todos los tickets de la ruta INSERT INTO ticketDms(ticketFk,dmsFk) SELECT id, NEW.gestdocFk FROM ticket WHERE routeFk = NEW.id ON DUPLICATE KEY UPDATE dmsFk = NEW.gestdocFk; - -- Update del firmado - UPDATE ticket t - JOIN ticketDms tg ON t.id = tg.ticketFk + -- Update del firmado + UPDATE ticket t + JOIN ticketDms tg ON t.id = tg.ticketFk SET isSigned = 1 WHERE t.routeFk = NEW.id; END IF; @@ -36099,20 +36101,20 @@ DELIMITER ;; BEFORE UPDATE ON `sale` FOR EACH ROW BEGIN -/* +/* IF (SELECT COUNT(*) from item i WHERE id = NEW.itemFk AND family = 'SER') THEN CALL util.throw('Cannot insert a service item into a ticket'); END IF; */ SET NEW.editorFk = account.myUser_getId(); - + IF NEW.discount > 100 THEN SET NEW.discount = 0; END IF; IF old.discount > 0 AND NEW.discount = 0 THEN INSERT INTO ticketLog - SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = NEW.ticketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Cambio de descuento del item :', ' ', new.itemFk, ' de ', old.discount ,' a 0 '); END IF; END */;; @@ -36244,11 +36246,11 @@ DELIMITER ;; BEGIN IF OLD.quantity > 0 THEN INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + SELECT r.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND s.id = OLD.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -36350,10 +36352,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`BEFORE_INSERT` BEFORE INSERT ON `saleBuy` FOR EACH ROW -BEGIN - +BEGIN + SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36372,13 +36374,13 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`saleBuy_AI` AFTER INSERT ON `saleBuy` FOR EACH ROW -BEGIN +BEGIN /* Activar de nuevo cuando volvamos a vender fruta y verdura - * + * UPDATE vn.sale s SET s.concept = CONCAT(s.concept, ' Lote: ', NEW.buyFk) WHERE s.id = NEW.saleFk; -*/ +*/ END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36644,14 +36646,14 @@ DELIMITER ;; AFTER INSERT ON `saleTracking` FOR EACH ROW BEGIN - - IF NEW.isChecked THEN - + + IF NEW.isChecked THEN + UPDATE vn.sale s - SET s.isPicked = TRUE + SET s.isPicked = TRUE WHERE s.id = NEW.saleFk AND s.isPicked = 0; - + END IF; END */;; @@ -37037,9 +37039,9 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; END */;; @@ -37064,14 +37066,14 @@ BEGIN IF NEW.workerFk = NEW.workerSubstitute THEN CALL util.throw ('worker and workerSubstitute must be different'); ELSE - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; - - INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) - SELECT NEW.workerFk, NEW.workerSubstitute, dated - FROM time + + INSERT IGNORE INTO sharingCartDaily (ownerFk, substituteFk, dated) + SELECT NEW.workerFk, NEW.workerSubstitute, dated + FROM time WHERE dated BETWEEN NEW.started AND NEW.ended; END IF; @@ -37094,9 +37096,9 @@ DELIMITER ;; BEFORE DELETE ON `sharingCart` FOR EACH ROW BEGIN - DELETE sc FROM sharingCartDaily sc - WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND - sc.ownerFk = OLD.workerFk AND + DELETE sc FROM sharingCartDaily sc + WHERE sc.dated BETWEEN OLD.started AND OLD.ended AND + sc.ownerFk = OLD.workerFk AND sc.substituteFk = OLD.workerSubstitute; END */;; DELIMITER ; @@ -37478,7 +37480,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance; END */;; @@ -37502,12 +37504,12 @@ DELIMITER ;; BEGIN IF NEW.dateLeaving IS NOT NULL THEN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; ELSE UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance; END IF; @@ -37531,7 +37533,7 @@ DELIMITER ;; FOR EACH ROW BEGIN UPDATE vn2008.Clientes c - JOIN creditClassification cc ON c.Id_Cliente = cc.client + JOIN creditClassification cc ON c.Id_Cliente = cc.client JOIN creditInsurance ci ON ci.creditClassification = cc.id SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance; END */;; @@ -38743,7 +38745,7 @@ DELIMITER ;; AFTER INSERT ON `ticket` FOR EACH ROW BEGIN - + DECLARE vClientType VARCHAR(255); DECLARE vStateCode VARCHAR(255); DECLARE vTransferorFirstShipped DATE; @@ -38771,7 +38773,7 @@ BEGIN INSERT INTO bs.clientNewBorn(clientFk, firstShipped, lastShipped) VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, util.VN_CURDATE()), util.VN_CURDATE()) ON DUPLICATE KEY UPDATE lastShipped = util.VN_CURDATE(); - + END IF; END */;; @@ -38798,10 +38800,10 @@ BEGIN SET NEW.editorFk = account.myUser_getId(); IF !(NEW.routeFk <=> OLD.routeFk) THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id IN (OLD.routeFk,NEW.routeFk) AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38818,13 +38820,13 @@ BEGIN END IF; END IF; - + IF !(NEW.isDeleted <=> OLD.isDeleted) AND NEW.isDeleted THEN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.ticket t JOIN vn.route r ON r.id = t.routeFk - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND t.id = NEW.id AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38834,7 +38836,7 @@ BEGIN SET NEW.zoneFk = NULL; END IF; - IF NEW.routeFk AND NEW.isDeleted THEN + IF NEW.routeFk AND NEW.isDeleted THEN CALL util.throw ('This ticket is deleted'); END IF; @@ -38843,12 +38845,12 @@ BEGIN FROM vn.ticket WHERE routeFk = NEW.routeFk HAVING MAX(TIME(shipped)) > TIME(NEW.shipped); - + IF vNewTime THEN SET NEW.shipped = TIMESTAMP(DATE(NEW.shipped), vNewTime); END IF; INSERT IGNORE INTO zoneAgencyMode (agencyModeFk,zoneFk) - SELECT r.agencyModeFk, NEW.zoneFk FROM route r + SELECT r.agencyModeFk, NEW.zoneFk FROM route r WHERE r.id = NEW.routeFk; CALL vn.routeUpdateM3(NEW.routeFk); @@ -38886,7 +38888,7 @@ BEGIN END IF; IF NEW.routeFk <> OLD.routeFk THEN - UPDATE expedition + UPDATE expedition SET hasNewRoute = TRUE WHERE ticketFk = NEW.id; END IF; @@ -38909,11 +38911,11 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`ticket_beforeDelete` BEFORE DELETE ON `ticket` FOR EACH ROW -BEGIN - INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) - SELECT r.id +BEGIN + INSERT IGNORE INTO `vn`.`routeRecalc` (`routeFk`) + SELECT r.id FROM vn.route r - WHERE r.isOk = FALSE + WHERE r.isOk = FALSE AND r.id = OLD.routeFk AND r.created >= util.VN_CURDATE() GROUP BY r.id; @@ -38990,31 +38992,31 @@ CREATE TABLE `ticketCollection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete -AFTER DELETE -ON ticketCollection FOR EACH ROW -BEGIN - - DECLARE vSalesRemaining INT; - - SELECT count(*) INTO vSalesRemaining - FROM vn.ticketCollection tc - JOIN sale s ON s.ticketFk = tc.ticketFk - WHERE collectionFk = OLD.collectionFk - AND tc.id != OLD.id; - - IF NOT vSalesRemaining THEN - - DELETE FROM vn.collection WHERE id = OLD.collectionFk; - - ELSE - - UPDATE vn.collection - SET saleTotalCount = vSalesRemaining - WHERE id = OLD.collectionFk; - - END IF; - +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete +AFTER DELETE +ON ticketCollection FOR EACH ROW +BEGIN + + DECLARE vSalesRemaining INT; + + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk + WHERE collectionFk = OLD.collectionFk + AND tc.id != OLD.id; + + IF NOT vSalesRemaining THEN + + DELETE FROM vn.collection WHERE id = OLD.collectionFk; + + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39112,13 +39114,13 @@ DELIMITER ;; BEFORE DELETE ON `ticketDms` FOR EACH ROW BEGIN - UPDATE dms - SET dmsTypeFk = (SELECT id - FROM dmsType + UPDATE dms + SET dmsTypeFk = (SELECT id + FROM dmsType WHERE `code` = 'trash' ) - WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) - FROM ticketDms + WHERE id = OLD.dmsFk AND ( SELECT IF(COUNT(*) > 0, FALSE, TRUE) + FROM ticketDms WHERE dmsFk = OLD.dmsFk ) ; END */;; @@ -39594,7 +39596,7 @@ DELIMITER ;; BEGIN SET NEW.workerFk = vn.getUser(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39922,7 +39924,7 @@ DELIMITER ;; BEGIN CALL ticket_requestRecalc(NEW.ticketFk); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39992,7 +39994,7 @@ BEGIN `changedModel` = 'TicketService', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - + CALL ticket_requestRecalc(OLD.ticketFk); END */;; @@ -40143,11 +40145,11 @@ DELIMITER ;; FOR EACH ROW BEGIN DECLARE vNumTicketsPrepared INT; - + REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state - WHERE id = NEW.stateFk; + WHERE id = NEW.stateFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40190,21 +40192,21 @@ BEGIN DECLARE vTicketFk INT; DECLARE vTicketTrackingFk INT; DECLARE vStateName VARCHAR(15); - + IF NEW.stateFk <> OLD.stateFk THEN REPLACE vn.ticketLastState(ticketFk, ticketTrackingFk, name) SELECT NEW.ticketFk, NEW.id, `name` FROM state WHERE id = NEW.stateFk; END IF; - + IF NEW.ticketFk <> OLD.ticketFk THEN SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = NEW.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = NEW.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -40246,18 +40248,18 @@ BEGIN `changedModel` = 'TicketTracking', `changedModelId` = OLD.id, `userFk` = account.myUser_getId(); - + CALL util.debugAdd('deletedState', CONCAT('interFk: ', OLD.id, ' ticketFk: ', OLD.ticketFk, ' stateFk: ', OLD.stateFk)); SELECT i.ticketFk, i.id, s.`name` - INTO vTicketFk, vTicketTrackingFk, vStateName - FROM ticketTracking i - JOIN state s ON i.stateFk = s.id - WHERE ticketFk = OLD.ticketFk - ORDER BY created DESC + INTO vTicketFk, vTicketTrackingFk, vStateName + FROM ticketTracking i + JOIN state s ON i.stateFk = s.id + WHERE ticketFk = OLD.ticketFk + ORDER BY created DESC LIMIT 1; IF vTicketFk > 0 THEN @@ -40449,13 +40451,13 @@ CREATE TABLE `till` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` - BEFORE INSERT ON `till` - FOR EACH ROW -BEGIN - IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN - SET NEW.concept = 'SIN DETALLE'; - END IF; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`till_beforeInsert` + BEFORE INSERT ON `till` + FOR EACH ROW +BEGIN + IF NEW.concept IS NULL OR NEW.concept REGEXP '^[[:space:]]*$' THEN + SET NEW.concept = 'SIN DETALLE'; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -40878,7 +40880,7 @@ DELIMITER ;; FOR EACH ROW BEGIN SET NEW.editorFk = account.myUser_getId(); - + IF NOT (NEW.landed <=> OLD.landed) OR NOT (NEW.shipped <=> OLD.shipped) THEN CALL travel_checkDates(NEW.shipped, NEW.landed); @@ -40920,7 +40922,7 @@ BEGIN CALL stock.log_add('travel', NEW.id, OLD.id); IF !(NEW.shipped <=> OLD.shipped) THEN - UPDATE entry + UPDATE entry SET commission = entry_getCommission(travelFk, currencyFk,supplierFk) WHERE travelFk = NEW.id; END IF; @@ -42634,9 +42636,9 @@ DELIMITER ;; AFTER INSERT ON `workerTimeControl` FOR EACH ROW BEGIN - IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN + IF NEW.timed > DATE_ADD(util.VN_NOW(), INTERVAL 1 DAY) THEN CALL util.throw('date in the future'); - END IF; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43168,10 +43170,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BI` BEFORE INSERT ON `zoneExclusion` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43190,10 +43192,10 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`zoneExclusion_BU` BEFORE UPDATE ON `zoneExclusion` FOR EACH ROW -BEGIN +BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43590,8 +43592,8 @@ DELIMITER ;; FROM client c LEFT JOIN ticket t ON t.clientFk = c.id WHERE c.salesPersonFk IS NOT NULL - OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH - OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH + OR t.created > util.VN_CURDATE() - INTERVAL 2 MONTH + OR shipped > util.VN_CURDATE() - INTERVAL 2 MONTH ); END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; @@ -44057,7 +44059,7 @@ BEGIN DECLARE vGeoFk INT; SELECT p.geoFk INTO vGeoFk - FROM address a + FROM address a JOIN town t ON t.provinceFk = a.provinceFk JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode WHERE a.id = vSelf @@ -44084,12 +44086,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `barcodeToItem`(vBarcode VARCHAR(22)) RETURNS int(11) DETERMINISTIC BEGIN - + /** * Obtiene el id del artículo * * @param vBarcode código de barras - * + * * return id del item */ @@ -44099,35 +44101,35 @@ BEGIN FROM vn.item WHERE id = vBarcode OR comment = vBarcode LIMIT 1; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT itemFk INTO vItemFk - FROM buy + SELECT itemFk INTO vItemFk + FROM buy WHERE id = vBarcode; - - IF vItemFk THEN - RETURN vItemFk; - END IF; - - SELECT itemFk INTO vItemFk - FROM itemBarcode - WHERE code = vBarcode; - - IF vItemFk THEN + + IF vItemFk THEN RETURN vItemFk; END IF; - SELECT i.id INTO vItemFk + SELECT itemFk INTO vItemFk + FROM itemBarcode + WHERE code = vBarcode; + + IF vItemFk THEN + RETURN vItemFk; + END IF; + + SELECT i.id INTO vItemFk FROM vn.item i WHERE i.name LIKE CONCAT('%',vBarcode,'%') ORDER BY i.id ASC LIMIT 1; - + RETURN vItemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -44150,9 +44152,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `botanicExport_isUpdatable`(vEdiGenus DETERMINISTIC BEGIN DECLARE vIsUpdatable INTEGER; - SELECT COUNT(*) INTO vIsUpdatable - FROM botanicExport - WHERE ediGenusFk = vEdiGenusFk + SELECT COUNT(*) INTO vIsUpdatable + FROM botanicExport + WHERE ediGenusFk = vEdiGenusFk AND (vEdiSpecieFk = ediSpecieFk OR IFNULL(vEdiSpecieFk,ediSpecieFk) IS NULL) AND vRestriction = restriction; RETURN vIsUpdatable; @@ -44248,16 +44250,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `catalog_componentReverse`(vWarehouse DETERMINISTIC BEGIN /* Calcula los componentes para un cliente a partir de un coste y volumen - * @param vWarehouse + * @param vWarehouse * @param vCost Valor de coste del articulo * @param vM3 m3 del articulo - * @param vAddressFk + * @param vAddressFk * @param vZoneFk - * @return vRetailedPrice precio de venta sin iva + * @return vRetailedPrice precio de venta sin iva * @return tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) */ - - DECLARE vBoxVolume BIGINT; + + DECLARE vBoxVolume BIGINT; DECLARE vCustomer INT; DECLARE vComponentRecovery INT DEFAULT 17; DECLARE vComponentMana INT DEFAULT 39; @@ -44266,11 +44268,11 @@ BEGIN DECLARE vComponentCost INT DEFAULT 28; DECLARE vRetailedPrice DECIMAL(10,2); DECLARE vItem INT DEFAULT 98; - + SELECT volume INTO vBoxVolume FROM vn.packaging WHERE id = '94'; - + SELECT clientFk INTO vCustomer FROM address WHERE id = vAddressFk; DROP TEMPORARY TABLE IF EXISTS tmp.catalog_component; @@ -44294,7 +44296,7 @@ BEGIN -- Margen -- No se aplica margen, cau 12589 /* INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost + SELECT vWarehouse, vItem, vComponentMargin, (vCost / ((100 - rate2) / 100)) - vCost FROM vn.rate WHERE dated <= util.VN_CURDATE() AND warehouseFk = vWarehouse @@ -44303,7 +44305,7 @@ BEGIN */ -- Recobro INSERT INTO tmp.catalog_component (warehouseFk, itemFk, componentFk, cost) - SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) + SELECT vWarehouse, vItem, vComponentRecovery, ROUND(LEAST(recobro,0.25), 3) FROM bi.claims_ratio WHERE Id_Cliente = vCustomer AND recobro > 0.009; @@ -44320,7 +44322,7 @@ BEGIN ROUND( vM3 * (z.price - z.bonus) - * z.inflation + * z.inflation / vBoxVolume, 4 ) FROM zone z @@ -44363,30 +44365,30 @@ BEGIN DECLARE vAutoManaComponent INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; - + SELECT COUNT(*) INTO vHasMana FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasMana THEN RETURN 0; END IF; - + SELECT max(dated) INTO vFromDated FROM clientManaCache; SELECT sum(mana) INTO vMana - FROM + FROM ( SELECT mana FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated + AND dated = vFromDated UNION ALL SELECT s.quantity * value FROM ticket t @@ -44394,7 +44396,7 @@ BEGIN JOIN sale s on s.ticketFk = t.id JOIN saleComponent sc on sc.saleFk = s.id WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated + AND t.shipped > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,util.VN_CURDATE()) AND a.clientFk = vClient UNION ALL @@ -44458,7 +44460,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `clientTaxArea`(vClientId INT, vCompa READS SQL DATA BEGIN /** -* Devuelve el area de un cliente, +* Devuelve el area de un cliente, * intracomunitario, extracomunitario o nacional. * * @param vClient Id del cliente @@ -44505,7 +44507,7 @@ BEGIN SELECT COUNT(*) INTO vHasDebt FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; - + IF NOT vHasDebt THEN RETURN 0; END IF; @@ -44593,8 +44595,8 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `client_getSalesPerson`(vClientFk INT DETERMINISTIC BEGIN /** - * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo - * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de + * Dado un id cliente y una fecha, devuelve su comercial para ese dia, teniendo + * en cuenta la jerarquía de las tablas: 1º la de sharingclient, 2º la de * sharingcart y tercero la de clientes. * * @param vClientFk El id del cliente @@ -44632,29 +44634,29 @@ BEGIN l: LOOP SELECT workerSubstitute INTO vWorkerSubstituteFk - FROM sharingCart + FROM sharingCart WHERE util.VN_CURDATE() BETWEEN started AND ended AND workerFk = vSalesPersonFk ORDER BY id LIMIT 1; - + IF vWorkerSubstituteFk IS NULL THEN LEAVE l; END IF; - + SELECT COUNT(*) > 0 INTO vLoop FROM tmp.stack WHERE substitute = vWorkerSubstituteFk; IF vLoop THEN LEAVE l; END IF; - + INSERT INTO tmp.stack SET substitute = vWorkerSubstituteFk; - + SET vSalesPersonFk = vWorkerSubstituteFk; END LOOP; - + DROP TEMPORARY TABLE tmp.stack; END IF; @@ -44688,11 +44690,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPerson(vClientFk, vDated); END ;; DELIMITER ; @@ -44723,12 +44725,12 @@ BEGIN **/ DECLARE vWorkerCode CHAR(3); DECLARE vSalesPersonFk INT; - + SET vSalesPersonFk = client_getSalesPerson(vClientFk, vDated); SELECT code INTO vWorkerCode - FROM worker + FROM worker WHERE id = vSalesPersonFk; RETURN vWorkerCode; @@ -44761,11 +44763,11 @@ BEGIN **/ DECLARE vClientFk INT; DECLARE vDated DATE; - + SELECT clientFk, shipped INTO vClientFk, vDated FROM ticket WHERE id = vTicketFk; - + RETURN client_getSalesPersonCode(vClientFk, vDated); END ;; DELIMITER ; @@ -44857,7 +44859,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `currentRate`(vCurrencyFk INT, vDated BEGIN DECLARE curRate DECIMAL(10,4); - + SELECT value INTO curRate FROM referenceRate WHERE dated <= vDated @@ -44888,23 +44890,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `deviceProductionUser_accessGranted`( BEGIN /* * Comprueba si el usuario puede entrar en la aplicacion de almacen con ese movil - * + * * */ - + /*DECLARE vIsGranted BOOLEAN; DECLARE vDeviceProductionFk INT(11) DEFAULT NULL; - SELECT dp.id INTO vDeviceProductionFk - FROM vn.deviceProduction dp + SELECT dp.id INTO vDeviceProductionFk + FROM vn.deviceProduction dp WHERE dp.android_id = android_id; IF vDeviceProductionFk THEN - - SELECT COUNT(*) INTO vIsGranted - FROM vn.deviceProductionUser dpu - WHERE dpu.userFk = vUserFK + + SELECT COUNT(*) INTO vIsGranted + FROM vn.deviceProductionUser dpu + WHERE dpu.userFk = vUserFK AND dpu.deviceProductionFk = vDeviceProductionFk; - + RETURN vIsGranted; END IF;*/ RETURN TRUE; @@ -44928,16 +44930,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `duaTax_getRate`(vDua INT, vTaxClass DETERMINISTIC BEGIN DECLARE vCountryFk INTEGER; - + SELECT s.countryFk INTO vCountryFk FROM dua d JOIN supplier s ON s.id = d.companyFk WHERE d.id = vDua; - + RETURN (SELECT rate FROM (SELECT taxClassFk, rate - FROM invoiceInTaxBookingAccount + FROM invoiceInTaxBookingAccount WHERE effectived <= util.VN_CURDATE() AND countryFk = vCountryFk AND taxClassFk = vTaxClass @@ -44965,24 +44967,24 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getEntry`(vEktFk INT) RETURNS in READS SQL DATA BEGIN /** - * Devuelve el numero de entrada para el ekt - * + * Devuelve el numero de entrada para el ekt + * * @param vEktFk Identificador de edi.ekt - */ + */ DECLARE vTravelFk INT; DECLARE vEntryFk INT DEFAULT 0; DECLARE vEntryAssignFk INT; - SELECT ea.id + SELECT ea.id INTO vEntryAssignFk FROM edi.ekt e - JOIN vn.ektEntryAssign ea ON + JOIN vn.ektEntryAssign ea ON IFNULL(ea.sub, e.sub) <=> e.sub AND IFNULL(ea.kop, e.kop) <=> e.kop AND IFNULL(ea.pro, e.pro) <=> e.pro AND IFNULL(ea.auction, e.auction) <=> e.auction WHERE e.id = vEktFk - ORDER BY + ORDER BY IF(ea.sub,1,0) * 1000 + IF(ea.kop,1,0) * 100 + IF(ea.pro,1,0) * 10 + @@ -44993,7 +44995,7 @@ BEGIN IF vTravelFk THEN - SELECT MAX(e.id) + SELECT MAX(e.id) INTO vEntryFk FROM vn.entry e JOIN vn.ektEntryAssign ea ON ea.id = vEntryAssignFk @@ -45008,13 +45010,13 @@ BEGIN INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk, kop, sub, reference, pro, auction) SELECT vTravelFk, ea.supplierFk, ea.companyFk, cu.id, ea.kop, ea.sub, ea.ref, ea.pro, ea.auction FROM vn.ektEntryAssign ea - JOIN vn.currency cu ON cu.code = 'EUR' + JOIN vn.currency cu ON cu.code = 'EUR' WHERE ea.id = vEntryAssignFk; SET vEntryFk = LAST_INSERT_ID(); END IF; - UPDATE vn.ektEntryAssign + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vEntryAssignFk; @@ -45048,7 +45050,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ekt_getTravel`(vEntryAssignFk INT, v BEGIN /** * Devuelve un vn.travel.id - * + * * @param vEntryAssignFk Identificador de vn.entryAssign */ DECLARE vTravelFk INT; @@ -45109,36 +45111,36 @@ BEGIN DECLARE vCurrentCommission INT; DECLARE vIsCurrencyUsd INT; DECLARE vLastEntryFk INT; - + SELECT count(*) INTO vIsCurrencyUsd FROM currency c WHERE c.code = 'USD' AND id = vCurrencyFk; - + IF NOT vIsCurrencyUsd THEN - + SELECT e.id INTO vLastEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk WHERE e.supplierFk = vSupplierFk ORDER BY tr.landed DESC LIMIT 1; - + IF vLastEntryFk THEN - + SELECT commission INTO vCurrentCommission FROM vn.entry WHERE id = vLastEntryFk; - + ELSE - + SELECT commission INTO vCurrentCommission FROM supplier s WHERE s.id = vSupplierFk; - + END IF; - + RETURN vCurrentCommission; - + ELSE SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission @@ -45147,11 +45149,11 @@ BEGIN WHERE t.id = vTravelFk ORDER BY r.`dated` DESC LIMIT 1; - + RETURN IFNULL(vCommission, 0); - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45202,10 +45204,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `entry_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve una entrada para Logiflora. Si no existe la crea. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -45213,51 +45215,51 @@ BEGIN DECLARE vTravelFk INT; DECLARE vEntryFk INT; DECLARE previousEntryFk INT; - + SET vTravelFk = vn.travel_getForLogiflora(vLanded, vWarehouseFk); - + IF vLanded THEN - - SELECT IFNULL(MAX(id),0) INTO vEntryFk + + SELECT IFNULL(MAX(id),0) INTO vEntryFk FROM vn.entry - WHERE travelFk = vTravelFk + WHERE travelFk = vTravelFk AND isRaid; IF NOT vEntryFk THEN - + INSERT INTO vn.entry(travelFk, supplierFk, commission, companyFk, currencyFk, isRaid) SELECT vTravelFk, s.id, 4, c.id, cu.id, TRUE FROM vn.supplier s JOIN vn.company c ON c.code = 'VNL' JOIN vn.currency cu ON cu.code = 'EUR' WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - - END IF; - - END IF; - SELECT entryFk INTO previousEntryFk + END IF; + + END IF; + + SELECT entryFk INTO previousEntryFk FROM edi.warehouseFloramondo wf WHERE wf.warehouseFk = vWarehouseFk; - + IF IFNULL(previousEntryFk,0) != vEntryFk THEN - - UPDATE buy b - SET b.printedStickers = 0 + + UPDATE buy b + SET b.printedStickers = 0 WHERE entryFk = previousEntryFk; DELETE FROM buy WHERE entryFk = previousEntryFk; - + DELETE FROM entry WHERE id = previousEntryFk; - + END IF; - + RETURN vEntryFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45290,21 +45292,21 @@ BEGIN SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id INTO vIsUeeSupplier, vSupplierCountry - FROM entry e - JOIN supplier s ON s.id = e.supplierFk - JOIN country c ON c.id = s.countryFk + FROM entry e + JOIN supplier s ON s.id = e.supplierFk + JOIN country c ON c.id = s.countryFk LEFT JOIN province p ON p.id = s.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk WHERE e.id = vSelf; - + SELECT IFNULL(a.isUeeMember, c.isUeeMember), c.id INTO vIsUeeCompany, vCompanyCountry - FROM entry e - JOIN supplier s ON s.id = e.companyFk - JOIN country c ON c.id = s.countryFk + FROM entry e + JOIN supplier s ON s.id = e.companyFk + JOIN country c ON c.id = s.countryFk LEFT JOIN province p ON p.id = s.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk - WHERE e.id = vSelf; + WHERE e.id = vSelf; RETURN vIsUeeCompany AND vIsUeeSupplier AND (vSupplierCountry <> vCompanyCountry); @@ -45369,17 +45371,17 @@ BEGIN DECLARE vHasDistinctRoutes BOOL; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) > 0 INTO vHasDistinctRoutes FROM vn.expeditionScan es JOIN vn.expedition e ON es.expeditionFk = e.id JOIN vn.ticket t ON e.ticketFk = t.id WHERE es.palletFk = vPalletFk AND t.routeFk <> vRouteFk; - + RETURN vHasDistinctRoutes; END ;; @@ -45440,27 +45442,27 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - + SELECT am.deliveryMethodFk - INTO vDeliveryType + INTO vDeliveryType FROM ticket t JOIN agencyMode am ON am.id = t.agencyModeFk WHERE t.id = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT MIN(t.warehouseFk <> w.id) INTO isWaitingForPickUp - FROM ticket t + FROM ticket t LEFT JOIN warehouse w ON w.pickUpagencyModeFk = t.agencyModeFk WHERE t.id = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -45490,28 +45492,28 @@ BEGIN DECLARE vDeliveryType INTEGER DEFAULT 0; DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE; DECLARE vCode VARCHAR(45); - - SELECT + + SELECT a.Vista - INTO vDeliveryType + INTO vDeliveryType FROM vn2008.Tickets t JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia WHERE Id_Ticket = vTicket; - + CASE vDeliveryType WHEN 1 THEN -- AGENCIAS SET vCode = 'DELIVERED'; - + WHEN 2 THEN -- REPARTO SET vCode = 'ON_DELIVERY'; - + ELSE -- MERCADO, OTROS SELECT t.warehouse_id <> w.warehouse_id INTO isWaitingForPickUp - FROM vn2008.Tickets t - LEFT JOIN vn2008.warehouse_pickup w + FROM vn2008.Tickets t + LEFT JOIN vn2008.warehouse_pickup w ON w.agency_id = t.Id_Agencia AND w.warehouse_id = t.warehouse_id WHERE t.Id_Ticket = vTicket; - + IF isWaitingForPickUp THEN SET vCode = 'WAITING_FOR_PICKUP'; ELSE @@ -45619,16 +45621,16 @@ BEGIN DECLARE vReturn DATE; DECLARE vDuaDate DATE; DECLARE vDuaDateDay INT; - + SELECT TIMESTAMPADD(DAY, vGapDays, vDated) INTO vDuaDate; IF vDuaDate = CONCAT(YEAR(vDuaDate), '-03-01') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); + SET vDuaDate = TIMESTAMPADD (DAY , -1, vDuaDate); ELSEIF vDuaDate = CONCAT(YEAR(vDuaDate), '-02-29') THEN - SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); + SET vDuaDate = TIMESTAMPADD (DAY , -2, vDuaDate); END IF; - IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN + IF MONTH(vDuaDate) = 2 AND vPayDay = 30 THEN IF util.isLeapYear(YEAR(vDuaDate)) THEN SET vPayDay = 29; ELSE @@ -45636,7 +45638,7 @@ BEGIN END IF; END IF; - SELECT DAY(vDuaDate) INTO vDuaDateDay; + SELECT DAY(vDuaDate) INTO vDuaDateDay; RETURN TIMESTAMPADD(MONTH, (vDuaDateDay > vPayDay), DATE_FORMAT(vDuaDate, CONCAT('%y/%m/', vPayDay))); END ;; DELIMITER ; @@ -45658,11 +45660,11 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getShipmentHour`(vTicket INT) RETURN READS SQL DATA BEGIN DECLARE vShipmentHour INT; - + SELECT HOUR(shipped) INTO vShipmentHour FROM ticket WHERE id = vTicket; - + IF vShipmentHour = 0 THEN DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer; @@ -45677,11 +45679,11 @@ BEGIN JOIN agencyMode am on am.id = t.agencyModeFk JOIN address a on a.id = t.addressFk WHERE t.id = vTicket; - - SELECT Hora INTO vShipmentHour + + SELECT Hora INTO vShipmentHour FROM tmp.production_buffer; END IF; - + RETURN vShipmentHour; END ;; DELIMITER ; @@ -45706,12 +45708,12 @@ BEGIN SELECT rate3 INTO price FROM vn.priceFixed - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND util.VN_CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1; - SELECT `value` INTO price + SELECT `value` INTO price FROM vn.specialPrice - WHERE itemFk = vItemFk + WHERE itemFk = vItemFk AND clientFk = vClientFk ; RETURN price; END ;; @@ -45735,7 +45737,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `getTicketTrolleyLabelCount`(vTicket BEGIN DECLARE vLabelCount INT DEFAULT 0; - SELECT labelCount INTO vLabelCount + SELECT labelCount INTO vLabelCount FROM ticketTrolley WHERE ticket = vTicket; @@ -45865,17 +45867,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `hasItemsInSector`(vTicketFk INT, vSe BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45898,7 +45900,7 @@ BEGIN DECLARE vCountry INT; DECLARE hasSomeNegativeBase BOOLEAN; - SELECT s.countryFk + SELECT s.countryFk INTO vCountry FROM supplier s JOIN ticket t ON t.companyFk = s.id @@ -45907,9 +45909,9 @@ BEGIN SELECT COUNT(*) INTO hasSomeNegativeBase FROM ( SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = vCountry WHERE s.ticketFk = vTicket GROUP BY itc.taxClassFk @@ -45939,12 +45941,12 @@ BEGIN DECLARE totalAmount DECIMAL(10,2); SELECT SUM(vat) INTO totalAmount - FROM ( + FROM ( SELECT iot.vat FROM invoiceOutTax iot JOIN invoiceOut io ON io.id = iot.invoiceOutFk WHERE io.ref = vInvoiceRef - UNION ALL + UNION ALL SELECT ioe.amount FROM invoiceOutExpence ioe JOIN invoiceOut io ON io.id = ioe.invoiceOutFk @@ -45975,23 +45977,23 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceOut_getMaxIssued`(vSerial VAR READS SQL DATA BEGIN /** - * Retorna la fecha a partir de la cual es válido emitir una factura + * Retorna la fecha a partir de la cual es válido emitir una factura * - * @param vSerial Serie de facturación + * @param vSerial Serie de facturación * @param vCompanyFk Empresa factura emitida * @param vYear Año contable * @return vInvoiceOutIssued fecha factura válida */ DECLARE vInvoiceOutIssued DATE; DECLARE vFirstDayOfYear DATE; - + SET vFirstDayOfYear := MAKEDATE(vYear, 1); - SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued + SELECT IFNULL(MAX(io.issued), vFirstDayOfYear) INTO vInvoiceOutIssued FROM invoiceOut io WHERE io.serial = vSerial AND io.companyFk = vCompanyFk - AND io.issued BETWEEN vFirstDayOfYear + AND io.issued BETWEEN vFirstDayOfYear AND util.lastDayOfYear(vFirstDayOfYear); RETURN vInvoiceOutIssued; @@ -46017,7 +46019,7 @@ BEGIN DECLARE vIssued DATE; DECLARE vSerial VARCHAR(15); - SELECT issued, ref + SELECT issued, ref INTO vIssued, vSerial FROM invoiceOut WHERE id = vSelf; @@ -46089,9 +46091,9 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `invoiceSerial`(vClientFk INT, vCompa DETERMINISTIC BEGIN /** - * Obtiene la serie de de una factura + * Obtiene la serie de de una factura * dependiendo del area del cliente. - * + * * @param vClientFk Id del cliente * @param vCompanyFk Id de la empresa * @param vType Tipo de factura ["R", "M", "G"] @@ -46172,18 +46174,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `isLogifloraDay`(vShipped DATE, vWarehouse INT) RETURNS tinyint(1) DETERMINISTIC BEGIN - + DECLARE vIsLogifloraDay BOOLEAN; SELECT COUNT(*) INTO vIsLogifloraDay FROM edi.warehouseFloramondo wf - JOIN vn.floramondoConfig fc + JOIN vn.floramondoConfig fc WHERE wf.warehouseFk = vWarehouse AND vShipped BETWEEN DATE(TIMESTAMPADD(DAY, wf.travellingDays , fc.nextLanded)) AND DATE(TIMESTAMPADD(DAY, wf.travellingDays + wf.dayRange , fc.nextLanded)); - + RETURN vIsLogifloraDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46220,7 +46222,7 @@ BEGIN WHERE sl.scan_id = vScanId AND t.Id_Ruta ) t1; - + RETURN vDistinctRoutesInThePallet = 1; END ;; DELIMITER ; @@ -46244,20 +46246,20 @@ BEGIN DECLARE vPacking INTEGER DEFAULT 0; DECLARE vItemFk INTEGER; - + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - - SELECT IFNULL(packing,0) INTO vPacking - FROM vn.buy + + SELECT IFNULL(packing,0) INTO vPacking + FROM vn.buy WHERE id = CAST(vBarcode AS DECIMAL(18,0)); - - - - + + + + IF NOT vPacking THEN CALL cache.last_buy_refresh(FALSE); SELECT IFNULL(packing,1) INTO vPacking - FROM + FROM (SELECT packing , created FROM vn.itemShelving WHERE itemFk = vItemFk @@ -46270,11 +46272,11 @@ BEGIN ) packings ORDER BY created desc LIMIT 1; - + END IF; - + RETURN vPacking; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46299,11 +46301,11 @@ BEGIN DECLARE vColumn INT; DECLARE vClosestParkingFk INT; DECLARE vSectorFk INT; - + SELECT p.column, sectorFk INTO vColumn, vSectorFk FROM vn.parking p WHERE p.id = vParkingFk; - + SELECT itemShelvingFk INTO vClosestParkingFk FROM ( @@ -46313,12 +46315,12 @@ BEGIN JOIN vn.itemPlacementSupplyList ipsl ON ipsl.sectorFk = ispss.sectorFk AND ipsl.itemFk = ispss.itemFk WHERE p.sectorFk = vSectorFk AND ipsl.saldo > 0 - ) sub + ) sub ORDER BY distance LIMIT 1; - + RETURN vClosestParkingFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46340,17 +46342,17 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `itemsInSector_get`(vTicketFk INT, vS BEGIN DECLARE vItemCount INT; - + SELECT count(*) INTO vItemCount - FROM vn.sale s + FROM vn.sale s JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk JOIN vn.shelving sh ON sh.code = ish.shelvingFk JOIN vn.parking p ON p.id = sh.parkingFk WHERE s.ticketFk = vTicketFk AND p.sectorFk = vSectorFk; - + RETURN vItemCount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46423,29 +46425,29 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `item_getPackage`(vItemFk INT) RETURNS varchar(50) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + DECLARE vDiameter INT; DECLARE vPackageFk VARCHAR(50); DECLARE vCoeficient DOUBLE DEFAULT 1.08; - + SELECT MAX(LEFT(value,3)) INTO vDiameter - FROM vn.itemTag it + FROM vn.itemTag it JOIN vn.tag t ON t.id = it.tagFk WHERE it.itemFk = vItemFk AND t.overwrite = 'diameter'; - + SELECT 8000 + FLOOR(vc.ccLength * vc.ccWidth / (vCoeficient * PI() * (vDiameter / 2) * (vDiameter / 2))) INTO vPackageFk FROM vn.volumeConfig vc; - + INSERT IGNORE INTO vn.packaging(id, width, `depth`) - SELECT vPackageFk, - FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), + SELECT vPackageFk, + FLOOR(vc.ccWidth / FLOOR(vc.ccWidth / vDiameter)), FLOOR(vc.ccLength / FLOOR(vc.ccLength / vDiameter)) FROM vn.volumeConfig vc; - + RETURN vPackageFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46482,7 +46484,7 @@ BEGIN FROM packaging p JOIN item i ON i.id = vSelf WHERE p.id = vPackaging; - + RETURN vVolume; END ;; @@ -46503,7 +46505,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `lastDayOfWeek`(vYear INT, vWeek INT) RETURNS date DETERMINISTIC -BEGIN +BEGIN /** * Returns the date of the last day of the week * @@ -46542,16 +46544,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `machine_checkPlate`(vPlate VARCHAR(1 BEGIN /** * Comprueba si existe matrícula - * + * * @param vPlate matrícula del vehículo * @return Devuelve TRUE en caso de que exista - * + * */ - + IF (SELECT COUNT(*) - FROM machine m + FROM machine m WHERE m.plate = vPlate - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -46578,9 +46580,9 @@ BEGIN DECLARE result INT; DECLARE vSenderFk INT; - SELECT id INTO vSenderFk + SELECT id INTO vSenderFk FROM account.user WHERE `name` = account.myUser_getName(); - + RETURN (SELECT messageSendWithUser(vSenderFk, vRecipient, vMessage)); END ;; DELIMITER ; @@ -46607,9 +46609,9 @@ BEGIN DECLARE vSendDate DATETIME DEFAULT util.VN_NOW(); DECLARE vSender VARCHAR(255) CHARSET utf8; - SELECT `name` INTO vSender + SELECT `name` INTO vSender FROM account.user WHERE id = vSenderFK; - + SET vRecipient = LOWER(vRecipient); DROP TEMPORARY TABLE IF EXISTS tRecipients; @@ -46630,7 +46632,7 @@ BEGIN IF vCount = 0 THEN RETURN vCount; - END IF; + END IF; SET vUuid = UUID(); @@ -46641,7 +46643,7 @@ BEGIN message = vMessage, sendDate = vSendDate; - INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) + INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) SELECT vUuid, vSender, vRecipient, finalRecipient, vMessage, vSendDate FROM tRecipients; @@ -46715,7 +46717,7 @@ BEGIN -- Devuelte el volumen total de la orden sumada DECLARE vWarehouseId INTEGER; DECLARE vVolume DECIMAL(10,3); - + SELECT IFNULL(SUM(o.amount * ic.cm3delivery)/1000000,0) INTO vVolume FROM hedera.orderRow o JOIN item i ON i.id = o.itemFk @@ -46792,7 +46794,7 @@ BEGIN WHERE cb.id = packagingReturnFk; SET vValue = IF (vAmount IS NULL, - IFNULL(base,0), + IFNULL(base,0), vAmount / IFNULL(upload, 0) + IFNULL(base, 0)); ELSE SET vValue = IFNULL(price, 0) + IFNULL(base, 0); @@ -46819,7 +46821,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `phytoPassport`(vRef VARCHAR(15)) RET DETERMINISTIC BEGIN DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci; -SELECT +SELECT GROUP_CONCAT(i.id, ':', ppa.denomination, @@ -46908,20 +46910,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -46929,16 +46931,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -46950,7 +46952,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -46975,9 +46977,9 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; DECLARE vShipped DATETIME; - + SELECT addressFk, date(shipped) INTO vAddressFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; SELECT routeFk INTO vRouteFk @@ -46991,7 +46993,7 @@ BEGIN ORDER BY friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -47015,20 +47017,20 @@ BEGIN DECLARE vRouteFk INT; DECLARE vAddressFk INT; - + DECLARE vLanded DATE; DECLARE vZoneFk INT; DECLARE vSignificativeFriendship INT DEFAULT 6; DECLARE vVolumeMax DECIMAL(5,1) DEFAULT 10; - + SELECT addressFk, zoneFk, landed INTO vAddressFk, vZoneFk, vLanded - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; - + -- Se inicia la selección de rutas posibles con aquellas cuyas agencias alguna vez han estado asociadas con nuestra zona DROP TEMPORARY TABLE IF EXISTS tmp.route; CREATE TEMPORARY TABLE tmp.route - SELECT r.id routeFk, + SELECT r.id routeFk, zf.friendship zoneFriendship FROM vn.route r JOIN cache.zoneAgencyFriendship zf ON zf.agencyModeFk = r.agencyModeFk @@ -47036,16 +47038,16 @@ BEGIN AND zf.zoneFk = vZoneFk AND r.created = vLanded ORDER BY friendship; - + -- Se eliminan aquellas que superan el volumen máximo DELETE r.* - FROM tmp.route r + FROM tmp.route r JOIN (SELECT routeFk, sum(volume) volume FROM vn.saleVolume WHERE landed = vLanded GROUP BY routeFk) sub ON sub.routeFk = r.routeFk WHERE sub.volume > vVolumeMax; - + -- Se ordenan las que quedan en función con la afinidad del resto de consignatarios de cada ruta SELECT routeFk INTO vRouteFk FROM @@ -47057,7 +47059,7 @@ BEGIN ORDER BY zoneFriendship DESC, friendshipSum DESC ) sub LIMIT 1; - + RETURN vRouteFk; END ;; DELIMITER ; @@ -47078,26 +47080,26 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `specie_IsForbidden`(vItemFk INT, vAddressFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN - + DECLARE vIsForbbiden BOOL; DECLARE vLeft INT; SELECT zg.lft INTO vLeft - FROM vn.address a - JOIN vn.zoneGeo zg ON zg.name = a.postalCode + FROM vn.address a + JOIN vn.zoneGeo zg ON zg.name = a.postalCode WHERE a.id = vAddressFk; - + SELECT sgi.isForbidden INTO vIsForbbiden - FROM vn.specieGeoInvasive sgi - JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk + FROM vn.specieGeoInvasive sgi + JOIN vn.zoneGeo zg ON zg.id = sgi.zoneGeofk JOIN vn.itemBotanical ib ON ib.genusFk = sgi.genusFk AND sgi.specieFk IN ('sp.',ib.specieFk) WHERE vLeft BETWEEN zg.lft AND zg.rgt AND ib.itemFk = vItemFk - ORDER BY zg.`depth` DESC + ORDER BY zg.`depth` DESC LIMIT 1; RETURN IFNULL(vIsForbbiden, FALSE); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47117,7 +47119,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testCIF`(vCIF VARCHAR(9)) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + DECLARE vLetraInicial VARCHAR(1); DECLARE vLetraFinal VARCHAR(1); DECLARE vParteNumerica VARCHAR(7); @@ -47129,60 +47131,60 @@ BEGIN SET vLetraInicial = SUBSTR(vCIF, 1, 1); SET vLetraFinal = SUBSTR(vCIF, 9, 1); SET vParteNumerica = SUBSTR(vCIF, 2, 7); - - WHILE i < 7 DO - + + WHILE i < 7 DO + SET i = i + 1; - + SET vNumero = CAST(SUBSTR(vParteNumerica, i, 1) AS DECIMAL(1,0)); - + IF i MOD 2 THEN - + SET vNumero = vNumero * 2; SET vNumero = vNumero MOD 10 + FLOOR(vNumero/10); - + END IF; - + SET vSuma = vSuma + vNumero; - + END WHILE; - + SET vSuma = vSuma MOD 10; - + IF vSuma > 0 THEN - + SET vSuma = 10 - vSuma; - + END IF; - + -- Comprobación de dígito de control IF CAST(vLetraFinal AS DECIMAL(1,0)) = vSuma THEN - + SET vResult = TRUE; - + END IF; - + IF vSuma = 0 THEN - + SET vSuma = 10; - + END IF; - + IF CHAR(64 + vSuma) = vLetraFinal THEN - + SET vResult = TRUE; - + END IF; - + -- Sólo se aceptan letras como caracter inicial IF ASCII(vLetraInicial) < 65 OR ASCII(vLetraInicial) > 87 THEN -- Ha de ser entre la A y la W - + SET vResult = FALSE; - + END IF; - + RETURN vResult; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47202,7 +47204,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `testNIE`(vNIE VARCHAR(9)) RETURNS tinyint(1) DETERMINISTIC BEGIN - + DECLARE vIndice INT; DECLARE vNumero VARCHAR(7); DECLARE vOperador VARCHAR(9); @@ -47211,45 +47213,45 @@ BEGIN DECLARE vLetraFinal VARCHAR(1); DECLARE vLetrasFinalesPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; DECLARE vLetraInicialEsIncorrecta BOOL DEFAULT FALSE; - + SET vLetraInicial = SUBSTR(vNIE, 1, 1); SET vLetraFinal = SUBSTR(vNIE, 9, 1); SET vNumero = SUBSTR(vNIE, 2, 7); CASE vLetraInicial - + WHEN 'X' THEN - + SET vOperador = "0"; - + WHEN 'Y' THEN - + SET vOperador = "1"; - + WHEN 'Z' THEN - + SET vOperador = "2"; - + ELSE - + SET vLetraInicialEsIncorrecta = TRUE; - + END CASE; - + SET vOperador = CONCAT(vOperador, vNumero); SET vParteNumerica = CAST(vOperador AS DECIMAL(8,0)); SET vIndice = Round(vParteNumerica Mod 23, 0) + 1; IF SUBSTR(vLetrasFinalesPosibles, vIndice, 1) = vLetraFinal AND vLetraInicialEsIncorrecta = FALSE THEN - + RETURN TRUE; - + ELSE - + RETURN FALSE; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47274,23 +47276,23 @@ BEGIN DECLARE vParteNumerica DECIMAL(8,0); DECLARE vLetra VARCHAR(1); DECLARE vLetrasPosibles VARCHAR(24) DEFAULT "TRWAGMYFPDXBNJZSQVHLCKE"; - + SET vLetra = SUBSTRING(vNIF, 9, 1); - + SET vParteNumerica = CAST(SUBSTRING(vNIF, 1, 8) AS DECIMAL(8,0)); - + SET vIndice = Round(vParteNumerica MOD 23, 0) + 1; - + If SUBSTRING(vLetrasPosibles, vIndice, 1) = vLetra Then - + RETURN TRUE; - + ELSE - + RETURN FALSE; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47310,21 +47312,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketCollection_getNoPacked`(vCollectionFk INT) RETURNS varchar(100) CHARSET utf8mb3 COLLATE utf8mb3_unicode_ci DETERMINISTIC BEGIN - + /* * return message with tickets and collection if there is tickets of a collection without expeditions - * + * * @param vCollectionFk the collection to check * @return an array with collection and tickets without expeditions - * + * */ - + DECLARE vAnswer VARCHAR(100) DEFAULT ''; IF collection_isPacked(vCollectionFk) = FALSE THEN SELECT CONCAT('Colección: ',tc.collectionFk,' Tickets: ' , GROUP_CONCAT(tc.ticketFk) ) INTO vAnswer FROM vn.ticketCollection tc - LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk + LEFT JOIN vn.expedition e ON e.ticketFk = tc.ticketFk WHERE tc.collectionFk = vCollectionFk AND ISNULL(e.id); END IF; @@ -47370,9 +47372,9 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, tmp.ticketTotal; - + RETURN vTotal; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47392,7 +47394,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8mb3 COLLATE utf8mb3_general_ci DETERMINISTIC BEGIN - + DECLARE vRestTicketsMaxOrder INT; DECLARE vRestTicketsMinOrder INT; DECLARE vRestTicketsPacking INT; @@ -47404,7 +47406,7 @@ BEGIN DECLARE vExpeditionsCount INT; DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE; -SELECT `order` +SELECT `order` INTO PACKING_ORDER FROM state WHERE code = 'PACKING'; @@ -47415,7 +47417,7 @@ SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0) LEFT JOIN ticketState ts on ts.ticket = t.id WHERE t.id = vTicketId; -SELECT (ag.`name` = 'VN_VALENCIA') +SELECT (ag.`name` = 'VN_VALENCIA') INTO vIsValenciaPath FROM vn2008.Rutas r JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia @@ -47429,7 +47431,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia FROM expedition e JOIN ticket t ON t.id = e.ticketFk WHERE t.routeFk = vMyPath; - + SELECT MAX(ts.productionOrder), MIN(ts.productionOrder) INTO vRestTicketsMaxOrder, vRestTicketsMinOrder FROM ticket t @@ -47438,7 +47440,7 @@ IF vIsValenciaPath THEN -- Rutas Valencia AND t.warehouseFk = vMyWarehouse AND t.id != vTicketid; - SELECT COUNT(*) + SELECT COUNT(*) INTO vRestTicketsPacking FROM ticket t LEFT JOIN ticketState ts on t.id = ts.ticket @@ -47493,9 +47495,9 @@ BEGIN LEFT JOIN vn2008.movement_label l ON l.Id_Movimiento = s.id WHERE ticketFk = vTicketFk ) sub; - + RETURN IFNULL(vSplitCounter,'--'); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47544,21 +47546,21 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticketTotalVolumeBoxes`(vTicketId IN DETERMINISTIC BEGIN -/* +/* * Devuelve el volumen estimado del ticket sumado, en cajas * * vTicketId Numero de ticket - * + * */ DECLARE vVolumeBoxM3 DOUBLE; DECLARE vTicketTotalVolumeBoxes DECIMAL(10,1); DECLARE vVnBoxId VARCHAR(10) DEFAULT '94'; - + SELECT volume / 1000000 INTO vVolumeBoxM3 FROM packaging WHERE id = vVnBoxId; - + SET vTicketTotalVolumeBoxes = ticketTotalVolume(vTicketId) / vVolumeBoxM3; - + RETURN vTicketTotalVolumeBoxes; END ;; @@ -47583,7 +47585,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM ticket + FROM ticket WHERE id = vTicketFk; RETURN vWarehouseFk; @@ -47606,18 +47608,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_CC_volume`(vTicketFk INT) RETURNS decimal(10,1) READS SQL DATA BEGIN - + DECLARE vCC DECIMAL(10,1); SELECT sum(sv.volume * IF(i.itemPackingTypeFk = 'H', vc.dutchCompressionRate, 1)) / (p.volume / 1000000) INTO vCC - FROM vn.saleVolume sv - JOIN vn.sale s ON s.id = sv.saleFk - JOIN vn.item i ON i.id = s.itemFk + FROM vn.saleVolume sv + JOIN vn.sale s ON s.id = sv.saleFk + JOIN vn.item i ON i.id = s.itemFk JOIN vn.packaging p ON p.id = 'CC' - JOIN vn.volumeConfig vc + JOIN vn.volumeConfig vc WHERE sv.ticketFk = vTicketFk; - + RETURN vCC; END ;; @@ -47639,44 +47641,44 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_get`(vParamFk INT) RETURNS int(11) READS SQL DATA proc:BEGIN - + /* Devuelve el número de ticket o collection consultando en varias tablas posibles - * + * * @param vParamFk Número a validar * @return vValidFk Identificador validado */ - + DECLARE vValidFk INT; -- Tabla vn.saleGroup SELECT s.ticketFk INTO vValidFk FROM vn.sale s JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id - JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk + JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk WHERE sg.id = vParamFk AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) LIMIT 1; - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.collection SELECT c.id INTO vValidFk - FROM vn.collection c + FROM vn.collection c WHERE c.id = vParamFk AND c.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; -- Tabla vn.ticket @@ -47684,17 +47686,17 @@ proc:BEGIN FROM vn.ticket t WHERE t.id = vParamFk AND t.shipped > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()); - + IF vValidFk THEN - + RETURN vValidFk; - + LEAVE proc; - + END IF; RETURN NULL; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -47720,8 +47722,8 @@ BEGIN * @vTicketFk Id del ticket a calcular */ DECLARE deliveryPrice DECIMAL (10,2); - - IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id + + IF (SELECT isVolumetric FROM ticket t JOIN zone z ON t.zoneFk = z.id WHERE t.id = vTicketFk) THEN SELECT SUM(sv.freight) INTO deliveryPrice FROM vn.saleVolume sv @@ -47732,7 +47734,7 @@ BEGIN LEFT JOIN expedition e ON e.ticketFk = t.id JOIN expeditionBoxVol ebv ON ebv.boxFk = e.freightItemFk WHERE t.id = vTicketFk; - + END IF; RETURN deliveryPrice; END ;; @@ -47756,16 +47758,16 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_getWeight`(vTicketFk INT) RET BEGIN /** * Devuelve el peso total del ticket - * + * * @return Total peso */ - + DECLARE vWeight DECIMAL(10,3); SELECT sum(weight) INTO vWeight FROM saleVolume WHERE ticketFk = vTicketFk; - + RETURN vWeight; END ;; @@ -47787,15 +47789,15 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `ticket_HasUbication`(vTicketFk INT) RETURNS tinyint(1) READS SQL DATA BEGIN - + DECLARE hasUbication BOOL; SELECT COUNT(*) INTO hasUbication FROM vn.ticket t JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - WHERE rm.beachFk + WHERE rm.beachFk AND t.id = vTicketFk; - + RETURN hasUbication; END ;; @@ -47944,7 +47946,7 @@ CREATE DEFINER=`root`@`localhost` FUNCTION `timeWorkerControl_getDirection`(vUse READS SQL DATA BEGIN /** - * Verifica la dirección de la fichada + * Verifica la dirección de la fichada * @param vUserFk Identificador del trabajador * @param vTimed Hora de la fichada * @return Retorna sentido de la fichada 'in, out, middle' @@ -47957,40 +47959,40 @@ BEGIN DECLARE vDayStayMax INT; DECLARE vTimedSeconds INT; DECLARE vLastTimeIn INT; - + SELECT UNIX_TIMESTAMP(vTimed) INTO vTimedSeconds; - + SELECT dayStayMax INTO vDayStayMax FROM vn.workerTimeControlParams; SELECT timed, direction INTO vNext,vNextDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed > vTimed ORDER BY timed ASC LIMIT 1; - + SELECT timed, direction INTO vPrevious, vPreviousDirection - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction IN ('in','out') AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - - IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN + LIMIT 1; + + IF (vTimedSeconds - UNIX_TIMESTAMP(vPrevious) + UNIX_TIMESTAMP(vNext) - vTimedSeconds)<= vDayStayMax AND vPreviousDirection = 'in' AND vNextDirection = 'out' THEN RETURN 'middle'; END IF; - - + + IF (vTimedSeconds> UNIX_TIMESTAMP(vPrevious)) THEN - IF vPreviousDirection = 'in' THEN + IF vPreviousDirection = 'in' THEN RETURN 'out'; ELSE SELECT UNIX_TIMESTAMP(MAX(timed)) INTO vLastTimeIn - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND direction ='in' AND timed < vPrevious; IF vTimedSeconds - vLastTimeIn <= vDayStayMax THEN @@ -48044,11 +48046,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` FUNCTION `travel_getForLogiflora`(vLanded DATE, vWarehouseFk INT) RETURNS int(11) READS SQL DATA BEGIN - + /** * Devuelve un número de travel para compras de Logiflora a partir de la fecha de llegada y del almacén. * Si no existe lo genera. - * + * * @param vLanded Fecha de llegada al almacén * @param vWarehouseFk Identificador de vn.warehouse */ @@ -48056,8 +48058,8 @@ BEGIN DECLARE vTravelFk INT; IF vLanded THEN - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -48068,14 +48070,14 @@ BEGIN AND landed = vLanded; IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) - SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id - FROM vn.warehouse wOut + SELECT vLanded, util.VN_CURDATE(), vWarehouseFk, wOut.id, am.id + FROM vn.warehouse wOut JOIN vn.agencyMode am ON am.name = 'LOGIFLORA' WHERE wOut.name = 'Holanda'; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse wIn ON wIn.id = tr.warehouseInFk JOIN vn.warehouse wOut ON wOut.id = tr.warehouseOutFk @@ -48083,11 +48085,11 @@ BEGIN AND wOut.name = 'Holanda' AND landed = vLanded; END IF; - + END IF; - + RETURN vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48114,21 +48116,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48155,21 +48157,21 @@ BEGIN DECLARE vChar INT; SET vLength = length(vString); - + WHILE vLength > 0 DO - + SET vChar = MID(vString,vLength,1); - + SET vSeed = vSeed + ASCII(vChar); - + SET vLength = vLength - 1; - + END WHILE; SET vCode = FLOOR(SQRT(vSeed)*1000000) mod 1000; RETURN vCode; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48230,15 +48232,15 @@ BEGIN * @param vTimeOut * @return vNigthlyHours */ - DECLARE vNigthlyHours DECIMAL(5,2); + DECLARE vNigthlyHours DECIMAL(5,2); DECLARE vSecondsPerHour INT(4) DEFAULT 3600; - + SELECT GREATEST(0, TIMESTAMPDIFF(SECOND, - IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeIn), ' ', startNightlyHours), + IF(TIME(vTimeIn) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeIn), ' ', startNightlyHours), vTimeIn), - IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, - CONCAT(DATE(vTimeOut), ' ', endNightlyHours), + IF(TIME(vTimeOut) BETWEEN endNightlyHours AND startNightlyHours, + CONCAT(DATE(vTimeOut), ' ', endNightlyHours), vTimeOut))) / vSecondsPerHour INTO vNigthlyHours FROM vn.workerTimeControlConfig; @@ -48270,47 +48272,47 @@ BEGIN SELECT dayStayMax INTO vDayStayMax FROM workerTimeControlParams; - + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN - + SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vLastIn AND vTimed; - + ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); END IF; END IF; - + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - + SET vLastInsertedId = LAST_INSERT_ID(); - + CALL workerTimeControlSOWP(vUserFk, vTimed); - + RETURN vLastInsertedId; END ;; DELIMITER ; @@ -48339,47 +48341,47 @@ BEGIN SELECT dayStayMax INTO vDayStayMax FROM workerTimeControlParams; - + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN - + SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vLastIn AND vTimed; - + ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut + + SELECT COUNT(*) INTO vHasDirectionOut FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); + AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); END IF; END IF; - + INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - + SET vLastInsertedId = LAST_INSERT_ID(); - + CALL workerTimeControlSOWP(vUserFk, vTimed); - + RETURN vLastInsertedId; END ;; DELIMITER ; @@ -48490,17 +48492,17 @@ BEGIN * @return Devuelve TRUE en caso de que este trabajando. Si se encuentra en un descanso devolverá FALSE */ DECLARE vLastIn DATETIME ; - + SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM vn.workerTimeControl WHERE userFk = vWorkerFk AND direction = 'in'; - IF (SELECT MOD(COUNT(*),2) - FROM vn.workerTimeControl - WHERE userFk = vWorkerFk AND + IF (SELECT MOD(COUNT(*),2) + FROM vn.workerTimeControl + WHERE userFk = vWorkerFk AND timed >= vLastIn - ) THEN + ) THEN RETURN TRUE; ELSE RETURN FALSE; @@ -48594,7 +48596,7 @@ BEGIN SET `type` = vType, `name` = vName, parentFk = vParentFk; - + SET vSelf = LAST_INSERT_ID(); UPDATE zoneGeoRecalc SET isChanged = TRUE; @@ -48618,7 +48620,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `addNoteFromDelivery`(idTicket INT,nota TEXT) BEGIN - + DECLARE observationTypeFk INT DEFAULT 3; /*3 = REPARTIDOR*/ INSERT INTO ticketObservation(ticketFk,observationTypeFk,description) @@ -48646,23 +48648,23 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `addressTaxArea`() READS SQL DATA BEGIN /** - * Devuelve el taxArea para un conjunto de Consignatarios y empresas, + * Devuelve el taxArea para un conjunto de Consignatarios y empresas, * * @table tmp.addressCompany(addressFk, companyFk) valores a calcular * @return tmp.addressTaxArea(addressFk,companyFk) */ - + DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; CREATE TEMPORARY TABLE tmp.addressTaxArea (PRIMARY KEY (addressFk, companyFk)) ENGINE = MEMORY - SELECT CASE - WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember) - AND NOT (auSupplier.id <=> auClient.id) THEN + SELECT CASE + WHEN (NOT IFNULL(auClient.isUeeMember, cClient.isUeeMember) OR NOT cSupplier.isUeeMember) + AND NOT (auSupplier.id <=> auClient.id) THEN 'WORLD' - WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN + WHEN cClient.isUeeMember AND cSupplier.isUeeMember AND c.countryFk != s.countryFk AND c.isVies THEN 'CEE' - WHEN a.isEqualizated AND cClient.code = 'ES' THEN + WHEN a.isEqualizated AND cClient.code = 'ES' THEN 'EQU' ELSE 'NATIONAL' @@ -48703,27 +48705,27 @@ BEGIN * @param vAddress id de la direccion * @param vWarehouse id del warehouse * @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida -*/ +*/ DECLARE vAgency INT; DECLARE vShipped DATE; DECLARE vLanded DATE DEFAULT util.VN_CURDATE(); SELECT agencyFk INTO vAgency FROM agencyMode WHERE id= vAgencyMode; l: LOOP - + CALL agencyHourGetShipped(vLanded,vAddress,vAgency); - SELECT shipped INTO vShipped + SELECT shipped INTO vShipped FROM tmp.agencyHourGetShipped WHERE warehouseFk = vWarehouse LIMIT 1; - + IF vShipped THEN LEAVE l; END IF; - + SET vLanded = DATE_ADD(vLanded, INTERVAL +1 DAY); - + END LOOP; - + SELECT vShipped,vLanded; END ;; DELIMITER ; @@ -48774,7 +48776,7 @@ BEGIN LIMIT 1 ) t WHERE IF(vDated = util.VN_CURDATE(), t.maxHour > HOUR(util.VN_NOW()), TRUE) AND t.substractDay < 225; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48797,14 +48799,14 @@ BEGIN * DEPRECATED usar zoneGetWarehouse * Devuelve el listado de agencias disponibles para la fecha, * dirección y warehouuse pasadas - * + * * @param vAddress no puede ser NULL * @param vWarehouse warehouse donde comprobaremos las agencias y fecha * @param vDate Fecha de recogida * @table agencyModeWarehouseList Listado de agencias disponibles */ DECLARE vAgency INT; - DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vDone BOOL DEFAULT FALSE; DECLARE vCur CURSOR FOR SELECT DISTINCT a.id FROM agency a @@ -48828,13 +48830,13 @@ BEGIN PRIMARY KEY(id) ) ENGINE = MEMORY; - + OPEN vCur; FETCH vCur INTO vAgency; WHILE NOT vDone DO - + INSERT INTO tmp.agencyModeWarehouseList SELECT am.id, am.name, am.description,am.deliveryMethodFk, TIMESTAMPADD(DAY, -ah.substractDay, vDate), w.name FROM agencyHour ah @@ -48863,7 +48865,7 @@ BEGIN END WHILE; CLOSE vCur; - + SELECT * FROM tmp.agencyModeWarehouseList; DROP TEMPORARY TABLE tmp.agencyModeWarehouseList; END ;; @@ -48889,9 +48891,9 @@ BEGIN CALL vn.agencyHourGetShipped(vDate, vAddress, vAgency); SELECT * FROM tmp.agencyHourGetShipped; - + DROP TEMPORARY TABLE IF EXISTS tmp.agencyHourGetShipped; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48929,7 +48931,7 @@ BEGIN DECLARE cWarehouses CURSOR FOR SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -48938,7 +48940,7 @@ BEGIN CALL vn.zone_getShipped (vDate, vAddress, vAgencyMode, FALSE); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( + CREATE TEMPORARY TABLE tmp.availableCalc( calcFk INT UNSIGNED, PRIMARY KEY (calcFk) ) @@ -48949,7 +48951,7 @@ BEGIN l: LOOP SET vDone = FALSE; FETCH cWarehouses INTO vWarehouse, vShipment; - + IF vDone THEN LEAVE l; END IF; @@ -48982,7 +48984,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `bankEntity_checkBic`(vBic VARCHAR(2 BEGIN /** * If the bic length is Incorrect throw exception - * + * * @param vBic bic code */ @@ -48990,7 +48992,7 @@ BEGIN SELECT bicLength INTO vConfigBicLenght FROM vn.bankEntityConfig bec; - + IF LENGTH(vBic) <> vConfigBicLenght THEN CALL util.throw(CONCAT('bic must be of length ', vConfigBicLenght )); END IF; @@ -49017,14 +49019,14 @@ BEGIN * Manda correo cuando caduca un seguro * de los leasing * -*/ +*/ INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'administracion@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') subject, CONCAT('El seguro de la poliza ',b.id,' ',b.bank,' ha finalizado.') body - FROM vn.bankPolicy bp - LEFT JOIN vn.supplier s + FROM vn.bankPolicy bp + LEFT JOIN vn.supplier s ON s.id = bp.supplierFk LEFT JOIN vn.bank b ON b.id = bp.bankFk @@ -49253,19 +49255,19 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - - SELECT b.entryFk, - b.itemFk, - i.packingOut, - ic.merchandise, + + SELECT b.entryFk, + b.itemFk, + i.packingOut, + ic.merchandise, vc.standardFlowerBox, b.weight, - b.packing - INTO - vEntryFk, - vItemFk, - vPackingOut, - vIsMerchandise, + b.packing + INTO + vEntryFk, + vItemFk, + vPackingOut, + vIsMerchandise, vStandardFlowerBox, vWeight, vPacking @@ -49273,7 +49275,7 @@ BEGIN LEFT JOIN item i ON i.id = b.itemFk LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox + LEFT JOIN packaging p ON p.id = b.packageFk AND NOT p.isBox JOIN volumeConfig vc ON TRUE WHERE b.id = vSelf; @@ -49290,7 +49292,7 @@ BEGIN warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), cm3Delivery = IFNULL((vStandardFlowerBox * 1000) / vPackingOut, buy_getUnitVolume(vSelf)); - + IF vWeight AND vPacking THEN UPDATE itemCost SET grams = vWeight * 1000 / vPacking @@ -49311,7 +49313,7 @@ BEGIN WHERE b.id = vSelf; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49358,10 +49360,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getSplit`(vSelf INT, vDated DATE) BEGIN /** - * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de - * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen + * Devuelve tantos registros como etiquetas se necesitan para cada uno de los cubos o cajas de + * las ventas correspondientes a la compra que se pasa como parámetro, en los almacenes que tienen * habilitada la venta de productos con stock virtual, aunque los productos pueden ser de cualquier tipo. - * + * * @param vSelf Identificador de vn.buy * @param vDated Fecha de preparación de las ventas que queremos etiquetar */ @@ -49436,7 +49438,7 @@ BEGIN WHILE vLabels >= vCounter DO INSERT INTO tmp.split SET - id = vSaleFk, + id = vSaleFk, labels = vLabels, counter = vCounter; @@ -49458,11 +49460,11 @@ BEGIN -- Devuelve los splits creados SELECT CONCAT(sp.counter,'/',sp.labels) labels, COALESCE(sfc.nickname, sfa.nickname, a.nickname) destination, - s.itemFk, - i.longName, - i.`size`, - vn.ticketSplitCounter(t.id) counter, - IF(sfa.id OR sfc.id, + s.itemFk, + i.longName, + i.`size`, + vn.ticketSplitCounter(t.id) counter, + IF(sfa.id OR sfc.id, a.nickname, CONCAT(a.id, ' ', p.`name`,' (', c.`code`,')')) destination2 FROM tmp.split sp @@ -49507,12 +49509,12 @@ BEGIN item_getVolume(b.itemFk, b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) carros , CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * item_getVolume(b.itemFk, b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) espais - FROM buy b + FROM buy b JOIN tmp.buy tb ON tb.buyFk = b.id JOIN volumeConfig vc JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk - LEFT JOIN temperature t ON t.code = it.temperatureFk + LEFT JOIN temperature t ON t.code = it.temperatureFk GROUP BY Temp; END ;; DELIMITER ; @@ -49532,21 +49534,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByAgency`(vDated DATE, vAgencyFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - INSERT INTO tmp.buy + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed = vDated AND t.agencyModeFk IN (0, vAgencyFk); CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49565,19 +49567,19 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_getVolumeByEntry`(vEntryFk INT) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.buy; CREATE TEMPORARY TABLE tmp.buy (buyFk INT NOT NULL, PRIMARY KEY (buyFk)) ENGINE = MEMORY; - - INSERT INTO tmp.buy + + INSERT INTO tmp.buy SELECT b.id - FROM buy b - JOIN entry e ON e.id = b.entryFk + FROM buy b + JOIN entry e ON e.id = b.entryFk WHERE e.id = vEntryFk; CALL buy_getVolume(); DROP TEMPORARY TABLE tmp.buy; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -49665,12 +49667,12 @@ BEGIN * inserta en tmp.buyRecalc las compras de un awb * * @param awbFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk @@ -49702,7 +49704,7 @@ BEGIN * Recalcula los precios de una compra * * @param vBuyFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc @@ -49733,12 +49735,12 @@ BEGIN * Recalcula los precios de una entrada * * @param vEntryFk - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; CREATE TEMPORARY TABLE tmp.buyRecalc SELECT b.id - FROM buy b + FROM buy b WHERE b.entryFk = vEntryFk; CALL buy_recalcPrices(); @@ -49778,12 +49780,12 @@ BEGIN LIMIT 0; INSERT INTO tBuy(buyFk) - SELECT b.id + SELECT b.id FROM buy b JOIN tmp.ekt t ON t.ektFk = b.ektFk JOIN vn.entry en ON en.id = b.entryFk JOIN vn.travel tr ON tr.id = en.travelFk - JOIN vn.warehouse w ON w.id = tr.warehouseInFk + JOIN vn.warehouse w ON w.id = tr.warehouseInFk JOIN vn.country c ON c.id = w.countryFk AND c.code = 'NL'; SELECT b.id buy, i.doPhoto do_photo, b.stickers - CAST(b.printedStickers AS INT) stickersToPrint @@ -49849,7 +49851,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_updatePacking`(vWarehouseFk INT, vItemFk INT, vPacking INT) BEGIN /** - * Actualiza packing + * Actualiza packing * * @param vWarehouseFk warehouse del item * @param vItemFk id del item @@ -49859,8 +49861,8 @@ BEGIN UPDATE buy b JOIN tmp.buyUltimate bu ON b.id = bu.buyFk - SET b.packing = vPacking - WHERE bu.warehouseFk = vWarehouseFk + SET b.packing = vPacking + WHERE bu.warehouseFk = vWarehouseFk AND bu.itemFk = vItemFk; DROP TEMPORARY TABLE tmp.buyUltimate; @@ -49899,7 +49901,7 @@ BEGIN */ DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY + ENGINE = MEMORY SELECT vItemFk itemFk; CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); @@ -49921,7 +49923,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_calculate`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN +BEGIN /** * Calcula los articulos disponibles y sus precios * @@ -49929,7 +49931,7 @@ BEGIN * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, + * @return tmp.ticketCalculateItem(itemFk, available, producer, * item, size, stems, category, inkFk, image, origin, price) * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) * @return tmp.ticketComponent @@ -49964,22 +49966,22 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; CREATE TEMPORARY TABLE tmp.ticketCalculateItem( - itemFk INT(11) NOT NULL, + itemFk INT(11) NOT NULL, available INT(11), - producer VARCHAR(50), - item VARCHAR(50), - size INT(10) UNSIGNED, - stems INT(11), - category VARCHAR(3), - inkFk VARCHAR(3), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), image VARCHAR(50), - origin VARCHAR(3), + origin VARCHAR(3), price DECIMAL(10,2), priceKg DECIMAL(10,2), `grouping` INT(10) UNSIGNED, PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; - + OPEN cTravelTree; l: LOOP @@ -50001,20 +50003,20 @@ BEGIN bu.buyFk, vZoneFk FROM `cache`.available a - LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id + LEFT JOIN cache.availableNoRaids anr ON anr.item_id = a.item_id AND anr.calc_id = vAvailableNoRaidsCalc JOIN tmp.item i ON i.itemFk = a.item_id JOIN vn.item it ON it.id = i.itemFk JOIN vn.`zone` z ON z.id = vZoneFk - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id - LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk - LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + LEFT JOIN edi.supplyResponse sr ON sr.ID = it.supplyResponseFk + LEFT JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID LEFT JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID LEFT JOIN (SELECT isVNHSupplier, isEarlyBird, TRUE AS itemAllowed FROM vn.addressFilter af - JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed - FROM vn.address ad - JOIN vn.province p ON p.id = ad.provinceFk + JOIN (SELECT ad.provinceFk, p.countryFk, ad.isLogifloraAllowed + FROM vn.address ad + JOIN vn.province p ON p.id = ad.provinceFk WHERE ad.id = vAddressFk ) sub2 ON sub2.provinceFk <=> IFNULL(af.provinceFk, sub2.provinceFk) AND sub2.countryFk <=> IFNULL(af.countryFk, sub2.countryFk) @@ -50031,13 +50033,13 @@ BEGIN JOIN vn.itemType itt ON itt.id = it.typeFk JOIN vn.itemCategory itc on itc.id = itt.categoryFk JOIN vn.address ad ON ad.id = vAddressFk - LEFT JOIN vn.clientItemType cit + LEFT JOIN vn.clientItemType cit ON cit.clientFk = ad.clientFk AND cit.itemTypeFk = itt.id - LEFT JOIN vn.zoneItemType zit + LEFT JOIN vn.zoneItemType zit ON zit.zoneFk = vZoneFk AND zit.itemTypeFk = itt.id - LEFT JOIN vn.agencyModeItemType ait + LEFT JOIN vn.agencyModeItemType ait ON ait.agencyModeFk = vAgencyModeFk AND ait.itemTypeFk = itt.id WHERE a.calc_id = vAvailableCalc @@ -50130,7 +50132,7 @@ BEGIN * Calcula los componentes de los articulos de tmp.ticketLot * * @param vZoneFk para calcular el transporte - * @param vAddressFk Consignatario + * @param vAddressFk Consignatario * @param vShipped dia de salida del pedido * @param vWarehouseFk warehouse de salida del pedido * @table tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) @@ -50144,7 +50146,7 @@ BEGIN SELECT clientFk INTO vClientFK FROM address WHERE id = vAddressFk; - + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentCalculate (PRIMARY KEY (itemFk, warehouseFk)) ENGINE = MEMORY @@ -50156,7 +50158,7 @@ BEGIN IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, IFNULL(pf.`grouping`, b.`grouping`) `grouping`, ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, + tl.buyFk, i.typeFk, IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping FROM tmp.ticketLot tl @@ -50164,7 +50166,7 @@ BEGIN JOIN item i ON i.id = tl.itemFk JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( @@ -50183,7 +50185,7 @@ BEGIN LIMIT 10000000000000000000 ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.merchandise @@ -50215,10 +50217,10 @@ BEGIN FROM tmp.ticketComponent tc JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk GROUP BY tc.itemFk, warehouseFk; - + -- RECOBRO INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcb.warehouseFk, tcb.itemFk, c2.id, + SELECT tcb.warehouseFk, tcb.itemFk, c2.id, ROUND(tcb.base * LEAST( MAX(GREATEST(IFNULL(cr.priceIncreasing,0), @@ -50249,29 +50251,29 @@ BEGIN ROUND(base * (0.01 + wm.pricesModifierRate), 3) manaAuto FROM tmp.ticketComponentBase tcb JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk JOIN vn.component c2 ON c2.code = 'autoMana' WHERE wm.isPricesModifierActivated HAVING manaAuto <> 0; - + -- Precios especiales INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, c2.id, GREATEST( - IFNULL(ROUND(tcb.base * c2.tax, 4), 0), + IFNULL(ROUND(tcb.base * c2.tax, 4), 0), IF(i.hasMinPrice, i.minPrice,0) - tcc.rate3 ) cost FROM tmp.ticketComponentBase tcb JOIN vn.component c2 ON c2.code = 'lastUnitsDiscount' - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk JOIN vn.item i ON i.id = tcb.itemFk WHERE sp.value IS NULL AND i.supplyResponseFk IS NULL; - -- Individual + -- Individual INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, @@ -50282,10 +50284,10 @@ BEGIN JOIN vn.client c ON c.id = vClientFk JOIN vn.businessType bt ON bt.code = c.businessTypeFk WHERE bt.code = 'individual'; - + -- Venta por paquetes INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) - SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 + SELECT tcc.warehouseFk, tcc.itemFk, c2.id, tcc.rate2 - tcc.rate3 FROM tmp.ticketComponentCalculate tcc JOIN vn.component c2 ON c2.code = 'salePerPackage' JOIN buy b ON b.id = tcc.buyFk @@ -50297,7 +50299,7 @@ BEGIN SELECT vZoneFk id; CALL zone_getOptionsForShipment(vShipped, TRUE); - + -- Reparto INSERT INTO tmp.ticketComponent SELECT tcc.warehouseFK, @@ -50311,7 +50313,7 @@ BEGIN JOIN agencyMode am ON am.id = z.agencyModeFk JOIN vn.volumeConfig vc JOIN vn.component c2 ON c2.code = 'delivery' - LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk + LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk AND ic.itemFk = tcc.itemFk HAVING cost <> 0; @@ -50364,9 +50366,9 @@ BEGIN CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 + WHERE IFNULL(tcs.classRate, 1) = 1 AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) GROUP BY tcs.warehouseFk, tcs.itemFk; @@ -50403,7 +50405,7 @@ BEGIN SELECT * FROM tmp.ticketComponentRate ORDER BY price LIMIT 10000000000000000000 ) t GROUP BY itemFk, warehouseFk, `grouping`; - + DROP TEMPORARY TABLE tmp.ticketComponentCalculate, tmp.ticketComponentSum, @@ -50428,7 +50430,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPrepare`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; CREATE TEMPORARY TABLE tmp.ticketComponent ( `warehouseFk` INT UNSIGNED NOT NULL, @@ -50438,9 +50440,9 @@ BEGIN INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC) )ENGINE=MEMORY DEFAULT CHARSET=utf8; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ( `warehouseFk` INT UNSIGNED NOT NULL, `itemFk` INT NOT NULL, `rate` INT NOT NULL, @@ -50449,7 +50451,7 @@ BEGIN `priceKg` DECIMAL(10,4), INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), UNIQUE `fkItemWarehouseRate` (`itemFk` ASC, `warehouseFk` ASC, `rate` ASC) - )ENGINE=MEMORY DEFAULT CHARSET=utf8; + )ENGINE=MEMORY DEFAULT CHARSET=utf8; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50468,7 +50470,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `catalog_componentPurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketComponentPrice, tmp.ticketComponent, tmp.ticketLot; @@ -50523,7 +50525,7 @@ BEGIN DELETE FROM sms WHERE created < v18Month; DELETE FROM saleTracking WHERE created < vOneYearAgo; DELETE FROM ticketTracking WHERE created < v18Month; - DELETE tobs FROM ticketObservation tobs + DELETE tobs FROM ticketObservation tobs JOIN ticket t ON tobs.ticketFk = t.id WHERE t.shipped < TIMESTAMPADD(YEAR,-2,util.VN_CURDATE()); DELETE sc.* FROM saleCloned sc JOIN sale s ON s.id = sc.saleClonedFk JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped < vOneYearAgo; DELETE FROM sharingCart where ended < vDateShort; @@ -50597,12 +50599,12 @@ BEGIN FROM vn.travel t LEFT JOIN vn.entry e ON e.travelFk = t.id WHERE t.shipped < TIMESTAMPADD(MONTH, -3, util.VN_CURDATE()) AND e.travelFk IS NULL; - + UPDATE dms d - JOIN dmsType dt ON dt.id = d.dmsTypeFk - SET d.dmsTypeFk = vTrashId + JOIN dmsType dt ON dt.id = d.dmsTypeFk + SET d.dmsTypeFk = vTrashId WHERE created < TIMESTAMPADD(MONTH, -dt.monthToDelete, util.VN_CURDATE()); - + -- borrar entradas sin compras DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; CREATE TEMPORARY TABLE tmp.entryToDelete @@ -50621,7 +50623,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.routeToDelete SELECT * FROM vn.route r - WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); + WHERE created < TIMESTAMPADD(YEAR,-4,util.VN_CURDATE()); UPDATE tmp.routeToDelete tmp JOIN vn.dms d ON d.id = tmp.gestdocFk @@ -50804,21 +50806,21 @@ BEGIN */ DECLARE vClientDebt DOUBLE; - + SELECT vn.client_getDebt(vClientFk, util.VN_CURDATE()) INTO vClientDebt; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) VALUES (vClientFk, 'Saldo pendiente', vClientDebt, util.VN_CURDATE(), 5); - + CALL vn.clientGreugeSpray(vClientFk, TRUE, '', TRUE); - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, greugeTypeFk) SELECT vClientFk, 'Liquidación cliente', sum(amount), util.VN_CURDATE(), 5 FROM vn.greuge WHERE clientFk = vClientFk; - - UPDATE vn.client - SET salesPersonFk = NULL + + UPDATE vn.client + SET salesPersonFk = NULL WHERE id = vClientFk; END ;; @@ -50908,33 +50910,33 @@ BEGIN DECLARE vIssued DATETIME; DECLARE vBalance DOUBLE DEFAULT 0.00; DECLARE cur CURSOR FOR - SELECT - created, - issued, + SELECT + created, + issued, ROUND(amount, 2) AS balance FROM invoiceOut - WHERE clientFk = vClientFk AND companyFk = vCompanyFk - UNION ALL - SELECT - created, - payed, + WHERE clientFk = vClientFk AND companyFk = vCompanyFk + UNION ALL + SELECT + created, + payed, ROUND(-1 * amountPaid, 2) AS balance - FROM receipt + FROM receipt WHERE clientFk = vClientFk AND companyFk = vCompanyFk ORDER BY issued, created; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN cur; - + proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCreated, vIssued, vBalance; IF vDate IS NULL THEN SET vDate=vIssued; END IF; - + IF vDone THEN LEAVE proc; END IF; @@ -50946,66 +50948,66 @@ BEGIN SET vDone = TRUE; END IF; END LOOP; - + CLOSE cur; - - SELECT - issued, - CAST(debtOut AS DECIMAL(10,2)) debtOut, + + SELECT + issued, + CAST(debtOut AS DECIMAL(10,2)) debtOut, CAST(debtIn AS DECIMAL(10,2)) debtIn, - ref, - companyFk, + ref, + companyFk, priority FROM - (SELECT - NULL AS issued, - SUM(amountUnpaid) AS debtOut, - NULL AS debtIn, - 'Saldo Anterior' AS ref, + (SELECT + NULL AS issued, + SUM(amountUnpaid) AS debtOut, + NULL AS debtIn, + 'Saldo Anterior' AS ref, companyFk, - 0 as priority - FROM - (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 + 0 as priority + FROM + (SELECT SUM(amount) AS amountUnpaid, companyFk, 0 FROM invoiceOut - WHERE clientFk = vClientFK - AND issued < vDate - GROUP BY companyFk - - UNION ALL - - SELECT SUM(-1 * amountPaid), companyFk, 0 - FROM receipt - WHERE clientFk = vClientFK - AND payed < vDate - GROUP BY companyFk) AS transactions - GROUP BY companyFk - - UNION ALL - - SELECT - issued, - amount as debtOut, - NULL AS debtIn, + WHERE clientFk = vClientFK + AND issued < vDate + GROUP BY companyFk + + UNION ALL + + SELECT SUM(-1 * amountPaid), companyFk, 0 + FROM receipt + WHERE clientFk = vClientFK + AND payed < vDate + GROUP BY companyFk) AS transactions + GROUP BY companyFk + + UNION ALL + + SELECT + issued, + amount as debtOut, + NULL AS debtIn, ref, companyFk, - 1 - FROM invoiceOut - WHERE clientFk = vClientFK + 1 + FROM invoiceOut + WHERE clientFk = vClientFK AND issued >= vDate - UNION ALL - - SELECT - r.payed, - NULL as debtOut, - r.amountPaid, - r.invoiceFk, + UNION ALL + + SELECT + r.payed, + NULL as debtOut, + r.amountPaid, + r.invoiceFk, r.companyFk, - 0 + 0 FROM receipt r - WHERE r.clientFk = vClientFK - AND r.payed >= vDate) t - INNER JOIN `client` c ON c.id = vClientFK - HAVING debtOut <> 0 OR debtIn <> 0 + WHERE r.clientFk = vClientFK + AND r.payed >= vDate) t + INNER JOIN `client` c ON c.id = vClientFK + HAVING debtOut <> 0 OR debtIn <> 0 ORDER BY issued, priority DESC, debtIn; END ;; DELIMITER ; @@ -51063,13 +51065,13 @@ BEGIN WHERE id = vClientFk; ELSE - + SELECT id INTO vOwner FROM vn.worker WHERE code = vWorkerCode COLLATE utf8_general_ci; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.clientList; CREATE TEMPORARY TABLE tmp.clientList SELECT DISTINCT t.clientFk, floor(cr.yearSale / 12) monthSale @@ -51081,7 +51083,7 @@ BEGIN AND t.shipped >= TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) AND c.id != vClientFk HAVING monthSale > 100; - + SELECT SUM(monthSale) INTO vTotalSale FROM tmp.clientList; @@ -51092,7 +51094,7 @@ BEGIN SELECT vClientFk, 'Reparto greuge', -vGreuge, util.VN_CURDATE(), vGreugeTypeFk; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51287,11 +51289,11 @@ BEGIN LEFT JOIN clientProtected cp ON cp.clientFk = cd.id JOIN client c ON c.id = cd.id JOIN province p ON p.id = c.provinceFk - LEFT JOIN autonomy a ON a.id = p.autonomyFk + LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk WHERE cd.Aviso = 'TERCER AVISO' AND cp.clientFk IS NULL - AND co.code NOT IN ('PT') + AND co.code NOT IN ('PT') AND a.name <> 'Canarias' AND c.salesPersonFk IS NOT NULL; @@ -51402,7 +51404,7 @@ BEGIN JOIN client c ON c.accountingAccount = lc.account WHERE lc.`date` BETWEEN vDateFrom AND vDateTo )sub - GROUP BY companyFk, clientFk + GROUP BY companyFk, clientFk ) sub1 ON sub1.clientFk = c.id JOIN supplier s ON s.id = sub1.companyFk JOIN company co ON co.id = sub1.companyFk @@ -51546,13 +51548,13 @@ BEGIN SET vEnded = TIMESTAMP(IFNULL(vDate, util.VN_CURDATE()), '23:59:59'); DROP TEMPORARY TABLE IF EXISTS tClientRisk; - CREATE TEMPORARY TABLE tClientRisk + CREATE TEMPORARY TABLE tClientRisk ENGINE = MEMORY SELECT cr.clientFk, SUM(cr.amount) amount FROM clientRisk cr JOIN tmp.clientGetDebt c ON c.clientFk = cr.clientFk GROUP BY cr.clientFk; - + INSERT INTO tClientRisk SELECT c.clientFk, SUM(r.amountPaid) FROM receipt r @@ -51567,7 +51569,7 @@ BEGIN WHERE t.receiptFk IS NULL AND t.status = 'ok' GROUP BY t.clientFk; - + INSERT INTO tClientRisk SELECT t.clientFk, totalWithVat FROM ticket t @@ -51583,7 +51585,7 @@ BEGIN FROM client c JOIN tClientRisk cr ON cr.clientFk = c.id GROUP BY c.id; - + DROP TEMPORARY TABLE tClientRisk; END ;; DELIMITER ; @@ -51607,9 +51609,9 @@ BEGIN DECLARE i INT DEFAULT 0; DECLARE c INT DEFAULT 0; DECLARE maxClientFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmp.client; - + CREATE TEMPORARY TABLE tmp.`client` (id INT AUTO_INCREMENT, clientFk INT, @@ -51617,40 +51619,40 @@ BEGIN PRIMARY KEY(id), UNIQUE KEY clientFk (clientFk)) ENGINE = MEMORY; - + INSERT INTO tmp.client(clientFk) SELECT DISTINCT clientFk FROM vn.invoiceOut WHERE issued > TIMESTAMPADD(MONTH, -2, util.VN_CURDATE()); - + SELECT max(id) INTO maxClientFk FROM tmp.client; - - + + WHILE i < vNumber DO - + SET i = i + 1; - + WHILE c = 0 DO - + SELECT id INTO c FROM tmp.client WHERE id = floor(RAND() * maxClientFk) + 1 AND isSelected = FALSE LIMIT 1; - + END WHILE; - + -- SELECT i, maxClientFk, c; - - UPDATE tmp.client - SET isSelected = TRUE + + UPDATE tmp.client + SET isSelected = TRUE WHERE id = c; - + SET c = 0; - + END WHILE; - + SELECT c.id, c.name FROM tmp.client tc JOIN vn.client c ON c.id = tc.clientFk WHERE isSelected @@ -51791,35 +51793,35 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cmr_getByTicket`(vTicketFk INT) BEGIN DECLARE vLanded DATE; - + SELECT DATE_ADD(util.VN_CURDATE(), INTERVAL landingDays DAY) INTO vLanded FROM vn.cmrConfig; IF vTicketFk THEN - + IF (SELECT count(ticketFk) FROM vn.cmr WHERE ticketFk = vTicketFk) THEN - + SELECT id FROM vn.cmr WHERE ticketFk = vTicketFk; - + ELSE - + INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, ead) SELECT vTicketFk, t.companyFk, a.id, t.addressFk, vLanded FROM vn.ticket t - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.address a ON a.id = w.addressFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.address a ON a.id = w.addressFk WHERE t.id = vTicketFk; - + SELECT LAST_INSERT_ID(); - + END IF; - + ELSE - + INSERT INTO vn.cmr(ead) VALUES(vLanded); - + SELECT LAST_INSERT_ID(); - + END IF; END ;; DELIMITER ; @@ -51842,7 +51844,7 @@ BEGIN /** * Insert the monthly CMR summary in vn.mail on the 5th of each month. */ - + SET SESSION group_concat_max_len = 1000000; -- IF (DAY(util.VN_CURDATE()) = 5) THEN INSERT INTO @@ -51870,7 +51872,7 @@ BEGIN CMR Ticket ' - , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), + , GROUP_CONCAT(' ', c.id, ' ', c.ticketFk, ' ' ORDER BY c.id SEPARATOR '' ), '

@@ -51888,7 +51890,7 @@ BEGIN -- Actualizamos el estado a 'Enviado' UPDATE vn.cmr c SET c.state = 'Sent' - WHERE c.state = 'Pending' + WHERE c.state = 'Pending' AND MONTH(c.created) = MONTH(util.VN_CURDATE() - INTERVAL 1 MONTH) AND YEAR(c.created) = YEAR(util.VN_CURDATE() - INTERVAL 1 MONTH); -- END IF; @@ -52101,15 +52103,15 @@ BEGIN DATE_FORMAT(util.VN_NOW(), '%H:%i' ), ' ', i.name - ) INTO vConcept + ) INTO vConcept FROM item i WHERE i.id = vItemFk; SELECT name INTO vItemName FROM item WHERE id = vBarccodeFk; - SELECT CONCAT('Añadido articulo ', + SELECT CONCAT('Añadido articulo ', vItemName, - ' cantidad:', + ' cantidad:', vQuantity ) INTO vDescription; @@ -52146,7 +52148,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_assign`(vUserFk INT, OUT vCollectionFk INT) -proc:BEGIN +proc:BEGIN /* Comprueba si existen colecciones libres que se ajustan al perfil del usuario * y le asigna la más antigua. * Añade un registro al semillero de colecciones @@ -52179,14 +52181,14 @@ proc:BEGIN FROM vn.collection c JOIN vn.ticketCollection tc ON tc.collectionFk = c.id JOIN vn.state s ON s.code = 'PRINTED_AUTO' - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* FROM vn.collection c - JOIN vn.productionConfig pc - WHERE c.workerFk IS NULL + JOIN vn.productionConfig pc + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; -- Se a�ade registro al semillero @@ -52196,8 +52198,8 @@ proc:BEGIN -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion SELECT MIN(c.id) INTO vCollectionFk - FROM vn.collection c - JOIN vn.operator o + FROM vn.collection c + JOIN vn.operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk OR c.itemPackingTypeFk IS NULL) AND o.numberOfWagons = c.wagons AND o.trainFk = c.trainFk @@ -52244,18 +52246,18 @@ BEGIN SELECT c.id collectionFk, date(c.created) created, COUNT(DISTINCT tc.ticketFk) ticketTotalCount - FROM collection c - JOIN ticketCollection tc ON tc.collectionFk = c.id - JOIN sale s ON s.ticketFk = tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN sale s ON s.ticketFk = tc.ticketFk JOIN ticketState ts ON ts.ticketFk = tc.ticketFk JOIN state s2 ON s2.id = ts.stateFk JOIN productionConfig pc JOIN vn.state ss on ss.code = 'PREPARED' LEFT JOIN vn.saleTracking st on st.saleFk = s.id AND st.stateFk = ss.id - WHERE c.workerFk = vWorkerFk + WHERE c.workerFk = vWorkerFk AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder + AND s2.order < pc.pendingCollectionsOrder GROUP BY c.id HAVING COUNT(*) > COUNT(DISTINCT st.id); @@ -52282,15 +52284,15 @@ BEGIN * Selecciona los tickets de una colección/ticket * @param vParamFk ticketFk/collectionFk * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones - */ + */ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores son los de pruebas, pinta los colores SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + FROM vn.collection WHERE id = vParamFk; - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, am.name agencyName, t.warehouseFk, @@ -52300,20 +52302,20 @@ BEGIN FROM vn.ticket t LEFT JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk + WHERE t.id = vParamFk AND t.shipped >= util.yesterday() UNION ALL - SELECT t.id ticketFk, + SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, @@ -52323,15 +52325,15 @@ BEGIN FROM vn.ticket t JOIN vn.ticketCollection tc ON t.id = tc.ticketFk LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk -- PAK 23/12/21 - LEFT JOIN vn.collectionColors cc - ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk LEFT JOIN vn.client c ON c.id = t.clientFk LEFT JOIN vn.worker w ON w.id = c.salesPersonFk - LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id + LEFT JOIN vn.ticketObservation tob ON tob.ticketFk = t.id AND tob.observationTypeFk = 1 WHERE tc.collectionFk = vParamFk; @@ -52694,8 +52696,8 @@ proc:BEGIN -- Se anulan el resto de carros libres para que sólo uno lleve un pedido excesivo DELETE tt.* FROM tTrain tt - LEFT JOIN (SELECT DISTINCT wagon - FROM tTrain + LEFT JOIN (SELECT DISTINCT wagon + FROM tTrain WHERE ticketFk IS NOT NULL ) nn ON nn.wagon = tt.wagon WHERE nn.wagon IS NULL; @@ -52863,7 +52865,7 @@ BEGIN DECLARE vDone INT DEFAULT FALSE; DECLARE vCursor CURSOR FOR SELECT DISTINCT ticketFk - FROM ticketCollection tc + FROM ticketCollection tc WHERE tc.collectionFk = vSelf; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -52910,25 +52912,25 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `company_getFiscaldata`(workerFk INT) BEGIN - + DECLARE vCompanyFk INT; - - SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) + + SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) INTO vCompanyFk FROM vn.routeConfig rc LEFT JOIN userConfig uc ON uc.userFk = workerFk; - - + + SELECT s.name AS name , s.NIF AS nif , s.street AS street , s.city AS city , - s.postCode AS postCode - - FROM vn.company c + s.postCode AS postCode + + FROM vn.company c JOIN vn.worker w ON w.id = c.workerManagerFk - JOIN vn.supplier s ON s.id = c.id + JOIN vn.supplier s ON s.id = c.id WHERE c.id = vCompanyFk; END ;; DELIMITER ; @@ -52985,7 +52987,7 @@ BEGIN IF (p.currencyFk = vCurrencyEuroFk, p.amount, p.divisa) AS amount, p.dueDated < vStartingDate isBeforeStarting, p.currencyFk - FROM payment p + FROM payment p WHERE p.received > vStartDate AND p.companyFk = vSelf UNION ALL @@ -52993,9 +52995,9 @@ BEGIN r.companyFk, - IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue) AS Total, rv.dueDated < vStartingDate isBeforeStarting, - r.currencyFk - FROM invoiceIn r - INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk + r.currencyFk + FROM invoiceIn r + INNER JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE r.issued > vStartDate AND r.isBooked AND r.companyFk = vSelf @@ -53047,11 +53049,11 @@ BEGIN -IF (r.currencyFk = vCurrencyEuroFk, rv.amount, rv.foreignValue), r.currencyFk, FALSE isPayment, - TRUE - FROM invoiceIn r + TRUE + FROM invoiceIn r LEFT JOIN tOpeningBalances si ON r.companyFk = si.companyFk AND r.supplierFk = si.supplierFk - AND r.currencyFk = si.currencyFk + AND r.currencyFk = si.currencyFk JOIN invoiceInDueDay rv ON r.id = rv.invoiceInFk WHERE rv.dueDated >= vStartingDate AND (si.closingBalances IS NULL OR si.closingBalances <> 0) @@ -53106,7 +53108,7 @@ BEGIN FROM tPendingDuedates WHERE balance < vInvalidBalances AND balance > - vInvalidBalances; - + DELETE vp.* FROM tPendingDuedates vp JOIN tRowsToDelete rd ON ( @@ -53134,9 +53136,9 @@ BEGIN FROM tPendingDuedates vp LEFT JOIN supplier s ON s.id = vp.supplierFk LEFT JOIN client c ON c.fi = s.nif - LEFT JOIN clientRisk cr ON cr.clientFk = c.id + LEFT JOIN clientRisk cr ON cr.clientFk = c.id AND cr.companyFk = vp.companyFk; - + DROP TEMPORARY TABLE tOpeningBalances; DROP TEMPORARY TABLE tPendingDuedates; DROP TEMPORARY TABLE tRowsToDelete; @@ -53159,7 +53161,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `conveyorExpedition_Add`(vStarted DATETIME, vEnded DATETIME) BEGIN - + DECLARE startingMinute INT; TRUNCATE vn.conveyorExpedition; @@ -53176,23 +53178,23 @@ BEGIN conveyorBuildingClassFk) SELECT e.id, e.created, - 10 * p.depth as depth, + 10 * p.depth as depth, 10 * p.width as width, 10 * p.height as height, IFNULL(t.routeFk,am.agencyFk) routeFk, hour(e.created) * 60 + minute(e.created), IFNULL(et.description , a.name), IFNULL(t.routeFk,am.agencyFk) criterion, - IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) + IFNULL(p.conveyorBuildingClassFk , pc.defaultConveyorBuildingClass) FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.packaging p ON p.id = e.packagingFk LEFT JOIN vn.zone z ON z.id = t.zoneFk LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN vn.agency a ON a.id = am.agencyFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk - JOIN vn.packagingConfig pc + LEFT JOIN vn.agency a ON a.id = am.agencyFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded AND p.height < 140 @@ -53201,8 +53203,8 @@ BEGIN SELECT MIN(productionMinute) INTO startingMinute FROM vn.conveyorExpedition ce ; - - UPDATE vn.conveyorExpedition + + UPDATE vn.conveyorExpedition SET productionMinute = productionMinute - startingMinute; END ;; @@ -53271,7 +53273,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `createPedidoInterno`(vItemFk INT,vQuantity INT) BEGIN - + UPDATE vn.item SET upToDown = vQuantity WHERE id = vItemFk; END ;; @@ -53294,52 +53296,52 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `crypt`(vText VARCHAR(255), vKey VAR BEGIN DECLARE vEncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vEncryptedChar VARCHAR(1); DECLARE vEncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - + DECLARE vInvalidadChars VARCHAR(255) DEFAULT ''; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vInvalidadChars = IF(vChainTextPosition, vInvalidadChars, CONCAT(vInvalidadChars,vTextChar)); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vEncryptedCharPosition = vChainTextPosition + vChainKeyPosition; - + IF vEncryptedCharPosition > vChainLength THEN - + SET vEncryptedCharPosition = vEncryptedCharPosition - vChainLength; - + END IF; - + SET vEncryptedChar = MID(vChain, vEncryptedCharPosition,1); - + SET vEncryptedText = CONCAT(vEncryptedText, vEncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = IF(LENGTH(vInvalidadChars), CONCAT('Caracteres no válidos: ',vInvalidadChars),vEncryptedText); @@ -53364,49 +53366,49 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `cryptOff`(vText VARCHAR(255), vKey BEGIN DECLARE vUncryptedText VARCHAR(255) DEFAULT ''; - + DECLARE vKeyLength INT; DECLARE vKeyPosition INT DEFAULT 1; DECLARE vKeyChar VARCHAR(1); - + DECLARE vTextLength INT; DECLARE vTextPosition INT DEFAULT 1; DECLARE vTextChar VARCHAR(1); - + DECLARE vUncryptedChar VARCHAR(1); DECLARE vUncryptedCharPosition INT; - + DECLARE vChain VARCHAR(255) DEFAULT '#$.-_0123456789abcdefghijklmnopqrstuvwxyz'; DECLARE vChainTextPosition INT; DECLARE vChainKeyPosition INT; DECLARE vChainLength INT; - - SET vTextLength = LENGTH(vText); + + SET vTextLength = LENGTH(vText); SET vKeyLength = LENGTH(vKey); SET vChainLength = LENGTH(vChain); - + WHILE vTextPosition <= vTextLength DO - + SET vTextChar = MID(vText,vTextPosition,1); SET vKeyChar = MID(vKey,vKeyPosition,1); - + SET vChainTextPosition = LOCATE(vTextChar, vChain); SET vChainKeyPosition = LOCATE(vKeyChar, vChain); SET vUncryptedCharPosition = vChainTextPosition - vChainKeyPosition; - + IF vUncryptedCharPosition < 1 THEN - + SET vUncryptedCharPosition = vUncryptedCharPosition + vChainLength; - + END IF; - + SET vUncryptedChar = MID(vChain, vUncryptedCharPosition,1); - + SET vUncryptedText = CONCAT(vUncryptedText, vUncryptedChar); - + SET vKeyPosition = IF(vKeyPosition = vKeyLength, 1,vKeyPosition + 1); SET vTextPosition = vTextPosition + 1; - + END WHILE; SET vResult = vUncryptedText; @@ -53502,7 +53504,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -53513,11 +53515,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL department_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -53572,7 +53574,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM department_recalc; - + IF vIsChanged THEN UPDATE department_recalc SET isChanged = FALSE; CALL vn.department_calcTree; @@ -53597,17 +53599,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `department_getHasMistake`() BEGIN - + /** * Obtiene los sectores a los cuales les ponemos errores * */ - + SELECT id, name FROM department WHERE hasToMistake <> FALSE; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53666,19 +53668,19 @@ BEGIN FROM department g JOIN tChilds c ON c.id = g.id WHERE g.parentFk IS NOT NULL; - + INSERT IGNORE INTO tNodes SELECT id FROM tParents; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; - + DELETE FROM tChilds; INSERT INTO tChilds SELECT id FROM tParents; END LOOP; - + DROP TEMPORARY TABLE tChilds, tParents; @@ -53745,12 +53747,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `deviceProductionUser_exists`(vUserFk INT) BEGIN - + /* SELECT COUNT(*) AS UserExists - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu WHERE dpu.userFk = vUserFk;*/ SELECT TRUE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53822,10 +53824,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `device_checkLogin`(vUserFk INT, vAndroidID VARCHAR(50)) BEGIN - + /* * Comprueba si está registrado el dispositivo mediante su androidId - * + * * @param vUSerFk el id del user * @param vAndroidID es el identificador android_id del dispositivo */ @@ -53837,20 +53839,20 @@ BEGIN SELECT dpc.isAllUsersallowed INTO vIsAllUsersAllowed FROM vn.deviceProductionConfig dpc; - IF NOT vIsAllUsersAllowed THEN - + IF NOT vIsAllUsersAllowed THEN + SELECT COUNT(*) INTO vIsDepartment - FROM vn.workerDepartment dp + FROM vn.workerDepartment dp JOIN department d ON d.id = dp.departmentFk WHERE dp.workerFk = vUserFk AND d.hasToCheckLogin; - + IF vIsDepartment THEN SELECT COUNT(*) INTO vIsAuthorized - FROM vn.deviceProductionUser dpu + FROM vn.deviceProductionUser dpu JOIN vn.deviceProduction dp ON dp.id = dpu.deviceProductionFk WHERE dpu.userFk = vUserFk AND dp.android_id = vAndroidID; - + IF NOT vIsAuthorized THEN SET vMessage = 'Usuario no autorizado'; END IF; @@ -53880,15 +53882,15 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaEntryValueUpdate`(vDuaFk INT) BEGIN UPDATE duaEntry de - JOIN + JOIN ( SELECT b.entryFk, sum(b.quantity * b.buyingValue) as total FROM buy b JOIN duaEntry de ON de.entryFk = b.entryFk WHERE duaFk = vDuaFk GROUP BY b.entryFk ) sub ON sub.entryFk = de.entryFk - - LEFT JOIN + + LEFT JOIN (SELECT e.id, sum(iit.taxableBase) as euros FROM entry e JOIN invoiceInTax iit ON iit.invoiceInFk = e.invoiceInFk @@ -53896,11 +53898,11 @@ BEGIN WHERE de.duaFk = vDuaFk GROUP BY e.id ) sub2 ON sub2.id = de.entryFk - + SET de.value = sub.total, de.euroValue = sub2.euros WHERE duaFk = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53924,7 +53926,7 @@ BEGIN DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; DECLARE vCounter INT DEFAULT 0; - + DECLARE rs CURSOR FOR SELECT e.invoiceInFk FROM entry e @@ -53937,7 +53939,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN rs; - + UPDATE invoiceIn ii JOIN entry e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id @@ -53949,41 +53951,41 @@ BEGIN ii.bookEntried = IFNULL(ii.bookEntried,d.bookEntried), e.isConfirmed = TRUE WHERE d.id = vDuaFk; - + SELECT IFNULL(ASIEN,0) INTO vASIEN FROM dua WHERE id = vDuaFk; - + FETCH rs INTO vInvoiceFk; - + WHILE NOT done DO CALL invoiceIn_booking(vInvoiceFk); - + IF vCounter > 0 OR vASIEN > 0 THEN - + UPDATE vn2008.XDiario x JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN SET x.ASIEN = vASIEN; - + ELSE - + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; - + END IF; - + SET vCounter = vCounter + 1; - + FETCH rs INTO vInvoiceFk; END WHILE; - + CLOSE rs; - - UPDATE dua + + UPDATE dua SET ASIEN = vASIEN WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54009,9 +54011,9 @@ BEGIN SELECT awbFk,companyFk FROM dua WHERE id = vDuaFk; - + SELECT LAST_INSERT_ID() INTO vNewDuaFk; - + INSERT INTO duaEntry(duaFk, entryFk, value, customsValue) SELECT vNewDuaFk, entryFk, value, value - customsValue FROM duaEntry @@ -54040,11 +54042,11 @@ BEGIN DECLARE vBookDated DATE; DECLARE vDiff DECIMAL(10,2); DECLARE vApunte BIGINT; - + SELECT ASIEN, IFNULL(bookEntried, util.VN_CURDATE()) INTO vBookNumber, vBookDated - FROM dua + FROM dua WHERE id = vDuaFk; - + IF vBookNumber IS NULL OR NOT vBookNumber THEN CALL ledger_next(vBookNumber); END IF; @@ -54055,14 +54057,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONCEPTO, + CONCEPTO, EUROHABER, SERIE, empresa_id, CLAVE, FACTURA) - SELECT + SELECT vBookNumber, d.bookEntried, '4700000999', @@ -54075,20 +54077,20 @@ BEGIN FROM duaTax dt JOIN dua d ON d.id = dt.duaFk WHERE dt.duaFk = vDuaFk; - + -- Apuntes por tipo de IVA y proveedor - + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, - CONCEPTO, - FACTURA, + CONCEPTO, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, FECHA_EX, FECHA_OP, @@ -54108,17 +54110,17 @@ BEGIN FECREGCON ) - SELECT + SELECT vBookNumber ASIEN, vBookDated FECHA, tr.account SUBCTA, '4330002067' CONTRA, sum(dt.tax) EURODEBE, - sum(dt.base) BASEEURO, + sum(dt.base) BASEEURO, CONCAT('DUA nº',d.code) CONCEPTO, d.id FACTURA, dt.rate IVA, - '*' AUXILIAR, + '*' AUXILIAR, 'D' SERIE, d.issued FECHA_EX, d.operated FECHA_OP, @@ -54145,10 +54147,10 @@ BEGIN WHERE ta.effectived <= vBookDated AND taxAreaFk = 'WORLD' ORDER BY ta.effectived DESC - LIMIT 10000000000000000000 + LIMIT 10000000000000000000 ) tba GROUP BY rate - ) tr ON tr.rate = dt.rate + ) tr ON tr.rate = dt.rate JOIN supplier s ON s.id = d.companyFk JOIN country c ON c.id = s.countryFk WHERE d.id = vDuaFk @@ -54157,16 +54159,16 @@ BEGIN SELECT SUM(EURODEBE) -SUM(EUROHABER), MAX(id) INTO vDiff, vApunte FROM XDiario WHERE ASIEN = vBookNumber; - + UPDATE XDiario SET BASEEURO = 100 * (EURODEBE - vDiff) / IVA, - EURODEBE = EURODEBE - vDiff + EURODEBE = EURODEBE - vDiff WHERE id = vApunte; UPDATE dua SET ASIEN = vBookNumber WHERE id = vDuaFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54187,21 +54189,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `duaTax_doRecalc`(vDuaFk INT) BEGIN /** * Borra los valores de duaTax y los vuelve a crear en base a la tabla duaEntry - * + * * @param vDuaFk Id del dua a recalcular **/ DELETE FROM duaTax WHERE duaFk = vDuaFk; - - INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) + + INSERT INTO duaTax(duaFk, supplierFk, taxClassFk, base) SELECT vDuaFk, supplierFk, taxClassFk, sum(sub.Base) as Base FROM intrastat ist JOIN (SELECT - e.supplierFk, + e.supplierFk, i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) * di.amount/ tei.Base AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id @@ -54209,15 +54211,15 @@ BEGIN ( SELECT i.intrastatFk, CAST(sum(b.quantity * b.buyingValue * de.customsValue / de.value) AS DECIMAL(10,2)) as Base - FROM buy b + FROM buy b JOIN item i ON i.id = b.itemFk JOIN entry e ON e.id = b.entryFk JOIN duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk GROUP BY i.intrastatFk - + ) tei ON tei.intrastatFk = i.intrastatFk - JOIN + JOIN ( SELECT intrastatFk, sum(amount) as amount FROM duaIntrastat @@ -54226,7 +54228,7 @@ BEGIN ) di ON di.intrastatFk = i.intrastatFk WHERE de.duaFk = vDuaFk GROUP BY e.supplierFk, i.intrastatFk - HAVING Base + HAVING Base ) sub ON ist.id = sub.intrastatFk GROUP BY ist.taxClassFk, sub.supplierFk; END ;; @@ -54247,13 +54249,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ediTables_Update`() BEGIN - - INSERT IGNORE INTO vn.genus(name) + + INSERT IGNORE INTO vn.genus(name) SELECT latin_genus_name FROM edi.genus ; - INSERT IGNORE INTO vn.specie(name) - SELECT LCASE(latin_species_name) + INSERT IGNORE INTO vn.specie(name) + SELECT LCASE(latin_species_name) FROM edi.specie ; END ;; DELIMITER ; @@ -54293,71 +54295,71 @@ DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; OPEN cur1; read_loop: LOOP - + SET done = FALSE; SET vEntryFk = 0; - + FETCH cur1 INTO vId; - + IF done THEN LEAVE read_loop; END IF; - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk AND ea.supplierFk = e.supplierFk WHERE ea.id = vId AND tr.landed = vLanded LIMIT 1; - + IF NOT vEntryFk THEN - + SELECT IFNULL(e.id,0) INTO vEntryFk FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded AND ea.supplierFk IS NULL LIMIT 1; - + END IF; - + IF NOT vEntryFk THEN - + SET vTravelFk = 0; - - SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk + + SELECT IFNULL(MAX(tr.id),0) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyModeFk WHERE ea.id = vId AND tr.landed = vLanded; - + IF NOT vTravelFk THEN - + INSERT INTO vn.travel(landed, shipped, warehouseInFk, warehouseOutFk, agencyModeFk) SELECT vLanded, vLanded, warehouseInFk, warehouseOutFk, agencyModeFk - FROM vn.ektEntryAssign + FROM vn.ektEntryAssign WHERE id = vId; - - SELECT MAX(tr.id) INTO vTravelFk + + SELECT MAX(tr.id) INTO vTravelFk FROM vn.travel tr - JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk + JOIN vn.ektEntryAssign ea ON ea.warehouseOutFk = tr.warehouseOutFk AND ea.warehouseInFk = tr.warehouseInFk AND ea.agencyModeFk = tr.agencyFk WHERE ea.id = vId AND tr.landed = vLanded; - + END IF; - + INSERT INTO vn.entry(travelFk, supplierFk, companyFk, currencyFk) SELECT vTravelFk, IFNULL(ea.supplierFk,s.id), c.id, cu.id FROM vn.supplier s @@ -54365,13 +54367,13 @@ OPEN cur1; JOIN vn.currency cu ON cu.code = 'EUR' JOIN vn.ektEntryAssign ea ON ea.id = vId WHERE s.name = 'KONINKLIJE COOPERATIEVE BLOEMENVEILING FLORAHOLLAN'; - - SELECT MAX(id) INTO vEntryFk + + SELECT MAX(id) INTO vEntryFk FROM vn.entry WHERE travelFk = vTravelFk; - + END IF; - + UPDATE vn.ektEntryAssign SET entryFk = vEntryFk WHERE id = vId; @@ -54379,7 +54381,7 @@ OPEN cur1; END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -54399,18 +54401,18 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `energyMeter_record`(vInput INT, vActiveTime INT) BEGIN DECLARE vConsumption INT; - + SELECT consumption INTO vConsumption FROM energyInput WHERE input = vInput; - INSERT INTO vn.energyMeter - SET - `input` = vInput, - `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), + INSERT INTO vn.energyMeter + SET + `input` = vInput, + `period` = DATE_FORMAT(util.VN_NOW(), '%Y-%m-%d %H:00:00'), `activeTime` = vActiveTime, `consumption` = CAST(IFNULL((vConsumption / 3600) * vActiveTime, 0) AS DECIMAL(10,2)) - ON DUPLICATE KEY UPDATE + ON DUPLICATE KEY UPDATE `activeTime` = `activeTime` + vActiveTime, `consumption` = `consumption` + CAST(VALUES(`consumption`) AS DECIMAL(10,2)); END ;; @@ -54433,28 +54435,28 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entryDelivered`(vDated DATE, vEntry BEGIN DECLARE vTravelFk INT; - + SELECT travelFk INTO vTravelFk - FROM vn.entry + FROM vn.entry WHERE id = vEntryFk; - + IF (SELECT COUNT(*) FROM vn.entry WHERE travelFk = vTravelFk) = 1 THEN - + UPDATE vn.travel SET shipped = LEAST(shipped, vDated), landed = vDated WHERE id = vTravelFk; - + ELSE - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, ref, isDelivered, isReceived) SELECT LEAST(shipped, vDated), vDated, warehouseInFk, warehouseOutFk, agencyModeFk, CONCAT(account.myUser_getName(),' ', vEntryFk), TRUE, TRUE FROM vn.travel WHERE id = vTravelFk; - + SELECT LAST_INSERT_ID() INTO vTravelFk; - - UPDATE vn.entry - SET travelFk = vTravelFk + + UPDATE vn.entry + SET travelFk = vTravelFk WHERE id = vEntryFk; - + END IF; END ;; @@ -54480,29 +54482,29 @@ BEGIN DECLARE vEntry INT; DECLARE vBucket VARCHAR(10); DECLARE vSupplierFk INT; - + SET vSupplierFk = IF (vLandingWarehouse = 1, 850, 963); -- seleccionamos travel SELECT t.id, e.id INTO vTravel, vEntry FROM travel t LEFT JOIN entry e ON t.id = e.travelFk - WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse + WHERE t.landed = vInOutDate AND t.shipped = vInOutDate AND t.warehouseOutFk = vShipmentWarehouse AND t.warehouseInFk = vLandingWarehouse AND t.agencyModeFk IS NULL AND e.supplierFk = vSupplierFk - LIMIT 1; - + LIMIT 1; + -- creamos el travel si es necesario IF IFNULL(vTravel, FALSE) = FALSE THEN INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk) VALUES (vInOutDate, vInOutDate, vLandingWarehouse, vShipmentWarehouse); SELECT LAST_INSERT_ID() INTO vTravel; END IF; - + -- creamos la Entrada si es necesario IF IFNULL(vEntry, FALSE) = FALSE THEN INSERT INTO entry (supplierFk, travelFk) VALUES (vSupplierFk, vTravel); -- proveedor 'CONFECCION ARTIFICIAL' SELECT LAST_INSERT_ID() INTO vEntry; END IF; - + -- creamos el cubo si es necesario SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; IF vBucket IS NULL THEN @@ -54512,7 +54514,7 @@ BEGIN SELECT id INTO vBucket FROM packaging WHERE volume = vVolume LIMIT 1; END IF; - INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) + INSERT INTO buy(itemFk,quantity, entryFk, packageFk, packing, stickers, buyingValue, price2, price3) SELECT itemFk, quantity, vEntry, @@ -54544,7 +54546,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_checkPackaging`(vEntryFk INT) BEGIN /** * Comprueba que los campos package y packaging no sean nulos - * + * * @param vEntryFk Id de entrada */ DECLARE vpackageOrPackingNull INT; @@ -54846,7 +54848,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_getRate`(vSelf INT) BEGIN /** - * Prepara una tabla con las tarifas aplicables en funcion de la fecha + * Prepara una tabla con las tarifas aplicables en funcion de la fecha * y el almacén * * @param vSelf Id de la tabla entry @@ -54856,7 +54858,7 @@ BEGIN DECLARE vWarehouseFk INT; SELECT t.landed, t.warehouseInFk INTO vDated, vWarehouseFk - FROM entry e + FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.id = vSelf; @@ -54986,7 +54988,7 @@ BEGIN FROM buy b WHERE b.entryFk = vSelf AND b.printedStickers != b.stickers; - + IF vChangeEntry THEN UPDATE buy SET stickers = printedStickers, @@ -54998,7 +55000,7 @@ BEGIN FROM item i WHERE i.description = 'MISFIT' LIMIT 1; - + INSERT INTO buy(entryFk, itemFk, quantity, @@ -55065,7 +55067,7 @@ BEGIN UPDATE entry SET gestDocFk = (SELECT gestDocFk FROM entry WHERE id = vSelf LIMIT 1) WHERE id = vNewEntryFk; - + INSERT INTO duaEntry (duaFk, entryFk) SELECT duaFk, vNewEntryFk FROM duaEntry WHERE entryFk = vSelf LIMIT 1; END ;; @@ -55139,12 +55141,12 @@ BEGIN */ DECLARE v_done BOOL DEFAULT FALSE; DECLARE vEntryFk INTEGER; - + DECLARE vCur CURSOR FOR SELECT id FROM tmp.recalcEntryCommision; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; OPEN vCur; @@ -55155,7 +55157,7 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + CALL vn2008.buy_tarifas_entry(vEntryFk); END LOOP; @@ -55180,7 +55182,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitByShelving`(vShelvingFk BEGIN /** * Divide las compras entre dos entradas de acuerdo con lo ubicado en una matr�cula - * + * * @param vShelvingFk Identificador de vn.shelving * @param vFromEntryFk Entrada origen * @param vToEntryFk Entrada destino @@ -55190,49 +55192,49 @@ BEGIN DECLARE vBuyStickers INT; DECLARE vDone BOOLEAN DEFAULT FALSE; - DECLARE cur CURSOR FOR + DECLARE cur CURSOR FOR SELECT bb.id buyFk, FLOOR(ish.visible / ish.packing) ishStickers, bb.stickers buyStickers FROM vn.itemShelving ish - JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC - LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk + LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk AND bb.stickers >= FLOOR(ish.visible / ish.packing) WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci GROUP BY ish.id; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Cantidades de la matrícula que exceden la de las entradas - SELECT ish.itemFk, - i.longName, + + -- Cantidades de la matrícula que exceden la de las entradas + SELECT ish.itemFk, + i.longName, FLOOR(ish.visible / ish.packing) AS etiEnMatricula, bb.stickers etiEnEntrada FROM vn.itemShelving ish - JOIN vn.item i ON i.id = ish.itemFk - LEFT JOIN (SELECT b.id, b.itemFk, b.stickers - FROM vn.buy b + JOIN vn.item i ON i.id = ish.itemFk + LEFT JOIN (SELECT b.id, b.itemFk, b.stickers + FROM vn.buy b WHERE b.entryFk = vFromEntryFk ORDER BY b.stickers DESC LIMIT 10000000000000000000) bb ON bb.itemFk = ish.itemFk WHERE shelvingFk = vShelvingFk COLLATE utf8_general_ci AND IFNULL(bb.stickers,0) < FLOOR(ish.visible / ish.packing) GROUP BY ish.id; - + OPEN cur; read_loop: LOOP SET vDone = FALSE; - + FETCH cur INTO vBuyFk, vIshStickers, vBuyStickers; - + IF vDone THEN LEAVE read_loop; END IF; - + IF vIshStickers = vBuyStickers THEN UPDATE vn.buy SET entryFk = vToEntryFk @@ -55240,9 +55242,9 @@ BEGIN ELSE UPDATE vn.buy SET stickers = stickers - vIshStickers, - quantity = stickers * packing + quantity = stickers * packing WHERE id = vBuyFk; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, @@ -55322,16 +55324,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `entry_splitMisfit`(vSelf INT) BEGIN - + /* Divide una entrada, pasando los registros que ha insertado vn.entry_fixMisfit de la entrada original * a la nueva */ - + DECLARE vNewEntryFk INT; DECLARE vBuyFk INT; SELECT MAX(b.id) INTO vBuyFk - FROM vn.buy b + FROM vn.buy b JOIN vn.item i ON i.id = b.itemFk WHERE b.entryFk = vSelf AND i.description = 'MISFIT'; @@ -55340,17 +55342,17 @@ BEGIN SELECT supplierFk, dated, travelFk, currencyFk, companyFk FROM vn.entry e WHERE e.id = vSelf; - - SET vNewEntryFk = LAST_INSERT_ID(); - UPDATE vn.buy b + SET vNewEntryFk = LAST_INSERT_ID(); + + UPDATE vn.buy b SET b.entryFk = vNewEntryFk WHERE b.entryFk = vSelf AND b.id > vBuyFk; - + SELECT vNewEntryFk; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55373,7 +55375,7 @@ BEGIN * Unlock the indicated entry * @vSelf params entry id */ - UPDATE `entry` + UPDATE `entry` SET lockerUserFk = NULL, locked = NULL WHERE id = vSelf; @@ -55404,21 +55406,21 @@ BEGIN DECLARE vComission INT; CREATE OR REPLACE TEMPORARY TABLE tmp.recalcEntryCommision - SELECT e.id + SELECT e.id FROM vn.entry e JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse w ON w.id = t.warehouseInFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk WHERE t.shipped >= util.VN_CURDATE() AND e.currencyFk = vCurrency; SET vComission = currency_getCommission(vCurrency); - UPDATE vn.entry e + UPDATE vn.entry e JOIN tmp.recalcEntryCommision tmp ON tmp.id = e.id SET e.commission = vComission; - SELECT `name` INTO vCurrencyName - FROM currency + SELECT `name` INTO vCurrencyName + FROM currency WHERE id = vCurrency; CALL entry_recalc(); @@ -55507,7 +55509,7 @@ BEGIN WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND cr.description = vDepartment GROUP BY cd.workerFk; - + CREATE OR REPLACE TEMPORARY TABLE volume ENGINE = MEMORY SELECT SUM(w.volume) volume, @@ -55518,15 +55520,15 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE errorsByChecker ENGINE = MEMORY - SELECT sub1.workerFk, COUNT(id) errors + SELECT sub1.workerFk, COUNT(id) errors FROM ( SELECT st.workerFk, t.id FROM saleMistake sm JOIN saleTracking st ON sm.saleFk = st.saleFk JOIN `state` s2 ON s2.id = st.stateFk - JOIN sale s ON s.id = sm.saleFk - JOIN ticket t on t.id = s.ticketFk + JOIN sale s ON s.id = sm.saleFk + JOIN ticket t on t.id = s.ticketFk WHERE (t.shipped BETWEEN vDatedFrom AND vDatedTo) AND s2.code IN ('OK','PREVIOUS_PREPARATION','PREPARED','CHECKED') ) sub1 @@ -55537,13 +55539,13 @@ BEGIN SELECT COUNT(t.id) errors, e.workerFk FROM vn.expeditionMistake pm - JOIN vn.expedition e ON e.id = pm.expeditionFk + JOIN vn.expedition e ON e.id = pm.expeditionFk JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo GROUP BY e.workerFk; IF (vDepartment = 'Sacadores') THEN - + INSERT INTO errorProduction(userFk, firstname, lastname, @@ -55576,12 +55578,12 @@ BEGIN LEFT JOIN errorsByChecker ec2 ON ec2.workerFk = t.workerFk JOIN (SELECT DISTINCT w.id -- Verificamos que son sacadores FROM vn.collection c - JOIN vn.state s ON s.id = c.stateFk + JOIN vn.state s ON s.id = c.stateFk JOIN vn.train tn ON tn.id = c.trainFk - JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.worker w ON w.id = c.workerFk WHERE c.created BETWEEN vDatedFrom AND vDatedTo) sub ON sub.id = w.id GROUP BY w.id; - + CREATE OR REPLACE TEMPORARY TABLE itemPickerErrors -- Errores de los sacadores, derivadores de los revisadores ENGINE = MEMORY SELECT COUNT(c.ticketFk) errors, @@ -55601,7 +55603,7 @@ BEGIN JOIN itemPickerErrors ipe ON ipe.workerFk = ep.userFk SET ep.error = ep.error + ipe.errors WHERE vDatedFrom = ep.dated AND ep.rol = 'Sacadores'; - + DROP TEMPORARY TABLE itemPickerErrors; ELSE INSERT INTO errorProduction(userFk, @@ -55637,7 +55639,7 @@ BEGIN LEFT JOIN expeditionErrors pe ON pe.workerFk = t.workerFk GROUP BY w.id; END IF; - + DROP TEMPORARY TABLE total, errorsByClaim, volume, @@ -55663,7 +55665,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `errorProduction_addLauncher`() BEGIN DECLARE vDatedFrom DATETIME; DECLARE vDatedTo DATETIME; - + SELECT DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(),INTERVAL 1 DAY),' 23:59:59') INTO vDatedFrom, vDatedTo; CALL vn.errorProduction_add('SACAR', vDatedFrom, vDatedTo); @@ -55694,7 +55696,7 @@ BEGIN DECLARE vRouteFk INT DEFAULT 0; SELECT t.routeFk INTO vRouteFk - FROM vn.expedition exp + FROM vn.expedition exp INNER JOIN ticket t on t.id = exp.ticketFk WHERE exp.id = vExpeditionFk; @@ -55897,14 +55899,14 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vSelf expeditioPallet id. */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; @@ -55971,22 +55973,22 @@ BEGIN DECLARE vTotal INT DEFAULT 0; IF vPalletFk = 0 THEN -- Nuevo pallet - - INSERT INTO vn.expeditionPallet(truckFk) + + INSERT INTO vn.expeditionPallet(truckFk) VALUES(vTruckFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END IF; - + SELECT COUNT(expeditionFk) INTO vTotal FROM vn.expeditionScan WHERE palletFk = vPalletFk; - + IF vTotal <> 0 THEN - SELECT expeditionFk, + SELECT expeditionFk, palletFk - FROM vn.expeditionScan + FROM vn.expeditionScan WHERE palletFk = vPalletFk; - ELSE + ELSE SELECT 0 expeditionFk,vPalletFk palletFk; END IF; END ;; @@ -56059,12 +56061,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionScan_Put`(vPalletFk INT, vExpeditionFk INT) BEGIN - - REPLACE vn.expeditionScan(expeditionFk, palletFk) + + REPLACE vn.expeditionScan(expeditionFk, palletFk) VALUES(vExpeditionFk, vPalletFk); - + SELECT LAST_INSERT_ID() INTO vPalletFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56083,32 +56085,32 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_add`(vParam INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, segun el parámetro - * + * * @param vParam Identificador de vn.expedition o de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + IF (SELECT COUNT(*) FROM vn.route r WHERE r.id = vParam) THEN - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vParam; - + ELSE - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vParam, est.id FROM vn.expeditionStateType est WHERE est.code = vStateCode; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56140,7 +56142,7 @@ BEGIN SELECT e.id, est.id FROM vn.expedition e JOIN vn.expeditionStateType est ON est.code = vStateCode - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.addressFk = vAdressFk AND t.routeFk = vRouteFk; END ;; @@ -56161,14 +56163,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByExpedition`(vExpeditionFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vExpeditionFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT vExpeditionFk, est.id FROM vn.expeditionStateType est @@ -56194,7 +56196,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByPallet`(vPalle BEGIN /** * Inserta nuevos registros en la tabla vn.expeditionState - * + * * @param vPalletFk Identificador de vn.expedition * @param vStateCode Corresponde a vn.expeditionStateType.code */ @@ -56211,7 +56213,7 @@ BEGIN IF NOT hasExpeditions THEN DROP TEMPORARY TABLE tExpeditionScan; - CALL util.throw('palletDoesNotExist'); + CALL util.throw('palletDoesNotExist'); END IF; INSERT INTO vn.expeditionState(expeditionFk, typeFk) @@ -56236,21 +56238,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionState_addByRoute`(vRouteFk INT, vStateCode VARCHAR(100)) BEGIN - + /** * Inserta nuevos registros en la tabla vn.expeditionState, por rutas - * + * * @param vRouteFk Identificador de vn.route * @param vStateCode Corresponde a vn.expeditionStateType.code */ - + INSERT INTO vn.expeditionState(expeditionFk, typeFk) SELECT e.id, est.id FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk JOIN vn.expeditionStateType est ON est.code = vStateCode WHERE t.routeFk = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56292,8 +56294,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() BEGIN - SELECT id truckFk, - eta, + SELECT id truckFk, + eta, description Destino FROM expeditionTruck WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -56337,7 +56339,7 @@ BEGIN JOIN address a ON t.addressFk = a.id JOIN route r ON r.id = t.routeFk LEFT JOIN warehouse w ON t.warehouseFk = w.id - LEFT JOIN (SELECT sub.ticketFk, + LEFT JOIN (SELECT sub.ticketFk, CONCAT('(', GROUP_CONCAT(DISTINCT sub.itemPackingTypeFk ORDER BY sub.items DESC SEPARATOR ','), ') ') itemPackingTypeConcat FROM (SELECT s.ticketFk , i.itemPackingTypeFk, COUNT(*) items FROM ticket t @@ -56368,7 +56370,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_getState`(vExpeditionFk INT) BEGIN - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -56378,24 +56380,24 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -56409,17 +56411,17 @@ BEGIN vTicketsPendientes AS ticketsPendientes, vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56438,12 +56440,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expedition_StateGet`(vExpeditionFk INT) BEGIN - + /* Devuelve una "ficha" con todos los datos relativos a la expedición - * - * param vExpeditionFk + * + * param vExpeditionFk */ - + DECLARE vTicketsPendientes INT; DECLARE vEtiquetasTotales INT; DECLARE vEtiquetasEscaneadas INT; @@ -56454,34 +56456,34 @@ BEGIN FROM vn.ticket t JOIN vn.expedition e ON e.ticketFk = t.id WHERE e.id = vExpeditionFk; - + SELECT COUNT(*) INTO vTicketsPendientes FROM vn.ticket t LEFT JOIN vn.expedition e ON e.ticketFk = t.id WHERE t.routeFk = vRouteFk AND ISNULL(e.id); - + SELECT COUNT(*) INTO vEtiquetasTotales - FROM vn.expedition e + FROM vn.expedition e JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasEscaneadas - FROM vn.expeditionScan es + FROM vn.expeditionScan es JOIN vn.expedition e ON e.id = es.expeditionFk - JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.ticket t ON t.id = e.ticketFk WHERE t.routeFk = vRouteFk; - + SELECT COUNT(*) INTO vEtiquetasLeidasSorter - FROM srt.expedition e + FROM srt.expedition e JOIN vn.expedition ve ON ve.id = e.id LEFT JOIN vn.expeditionScan es ON es.expeditionFk = e.id - JOIN vn.ticket t ON t.id = ve.ticketFk + JOIN vn.ticket t ON t.id = ve.ticketFk WHERE t.routeFk = vRouteFk AND e.created != e.updated - AND ISNULL(es.expeditionFk); - - + AND ISNULL(es.expeditionFk); + + SELECT e.ticketFk ticket, t.nickname cliente, a.city ciudad, @@ -56496,17 +56498,17 @@ BEGIN vEtiquetasTotales AS etiquetasTotales, vEtiquetasEscaneadas AS etiquetasEscaneadas, vEtiquetasLeidasSorter AS etiquetasSorter - FROM vn.expedition e - JOIN vn.ticket t ON t.id = e.ticketFk - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p ON p.id = a.provinceFk - JOIN vn.`zone`z ON z.id = t.zoneFk - LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk - LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id - LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk + FROM vn.expedition e + JOIN vn.ticket t ON t.id = e.ticketFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.`zone`z ON z.id = t.zoneFk + LEFT JOIN vn.route r ON r.id = t.routeFk + LEFT JOIN vn.agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = r.id + LEFT JOIN vn.expeditionTruck et ON et.id = rm.expeditionTruckFk WHERE e.id = vExpeditionFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56552,7 +56554,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControl`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -56561,68 +56563,68 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - SELECT p.id FustCode, - CAST(sent.stucks AS DECIMAL(10,0)) FH, - CAST(tp.stucks AS DECIMAL(10,0)) Tickets, - CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, + SELECT p.id FustCode, + CAST(sent.stucks AS DECIMAL(10,0)) FH, + CAST(tp.stucks AS DECIMAL(10,0)) Tickets, + CAST(-sj.stucks AS DECIMAL(10,0)) Sijsner, CAST(IFNULL(sent.stucks,0) - IFNULL(tp.stucks,0) + IFNULL(sj.stucks,0) AS DECIMAL(10,0)) saldo FROM vn.packaging p LEFT JOIN ( SELECT FustCode, sum(fustQuantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,b.packageFk) FustCode, s.quantity / b.packing AS fustQuantity - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk - JOIN vn.buy b ON b.id = lb.buy_id - JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = t.warehouseFk + JOIN vn.buy b ON b.id = lb.buy_id + JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable - AND c.country = 'FRANCIA') sub + AND p.isPackageReturnable + AND c.country = 'FRANCIA') sub GROUP BY FustCode) sent ON sent.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vDateStart AND vDateEnd AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk - AND tp.quantity > 0) sub + AND tp.quantity > 0) sub GROUP BY FustCode) tp ON tp.FustCode = p.id LEFT JOIN ( SELECT FustCode, sum(quantity) stucks FROM ( SELECT IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id WHERE t.shipped BETWEEN TIMESTAMPADD(DAY, 1, vDateStart ) AND TIMESTAMPADD(DAY, 1, vDateEnd ) AND wa.name = 'VNH' - AND p.isPackageReturnable - AND t.clientFk = vSijsnerClientFk) sub + AND p.isPackageReturnable + AND t.clientFk = vSijsnerClientFk) sub GROUP BY FustCode) sj ON sj.FustCode = p.id - WHERE sent.stucks + WHERE sent.stucks OR tp.stucks OR sj.stucks; @@ -56644,7 +56646,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `fustControlDetail`(vFromDated DATE, vToDated DATE) BEGIN - + DECLARE vSijsnerClientFk INT DEFAULT 19752; DECLARE vDateStart DATETIME; @@ -56652,29 +56654,29 @@ BEGIN SET vDateStart = vFromDated; SET vDateEnd = util.Dayend(vToDated); - + SELECT a.nickname shopName, - a.city , - IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, + a.city , + IFNULL(pe.equivalentFk ,tp.packagingFk) FustCode, tp.quantity, tp.ticketFk, CONCAT('From ', vFromDated,' to ', vToDated) AS dateRange - FROM vn.ticketPackaging tp - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.warehouse w ON w.id = t.warehouseFk - JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk - JOIN vn.packaging p ON p.id = tp.packagingFk + FROM vn.ticketPackaging tp + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + JOIN vn.warehouseAlias wa ON wa.id = w.aliasFk + JOIN vn.packaging p ON p.id = tp.packagingFk LEFT JOIN vn.packageEquivalent pe ON pe.packagingFk = p.id - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.province p2 ON p2.id = a.provinceFk - JOIN vn.country c ON c.id = p2.countryFk + JOIN vn.address a ON a.id = t.addressFk + JOIN vn.province p2 ON p2.id = a.provinceFk + JOIN vn.country c ON c.id = p2.countryFk WHERE t.shipped BETWEEN vFromDated AND util.dayend(vToDated) AND wa.name = 'VNH' - AND p.isPackageReturnable + AND p.isPackageReturnable AND c.country = 'FRANCIA' AND t.clientFk != vSijsnerClientFk AND tp.quantity > 0; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -56700,8 +56702,8 @@ DECLARE vTicketFk INT; DECLARE vSaleFk INT; DECLARE vClonTicket INT DEFAULT 0; -DECLARE cur1 CURSOR FOR -SELECT s.ticketFk, s.id +DECLARE cur1 CURSOR FOR +SELECT s.ticketFk, s.id FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk JOIN vn.item i ON i.id = s.itemFk @@ -56717,17 +56719,17 @@ OPEN cur1; FETCH cur1 INTO vTicketFk, vSaleFk; WHILE done = 0 DO - + SELECT t.id INTO vClonTicket FROM vn.ticket t JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) WHERE t.warehouseFk = 44 LIMIT 1; - + SELECT vTicketFk, vClonTicket; - + IF vClonTicket = 0 THEN - + INSERT INTO ticket ( clientFk, shipped, @@ -56755,12 +56757,12 @@ FETCH cur1 INTO vTicketFk, vSaleFk; zonePrice, zoneBonus, routeFk - + FROM ticket WHERE id = vTicketFk; SET vClonTicket = LAST_INSERT_ID(); - + SELECT 'lstID', vClonTicket; /* INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) @@ -56770,20 +56772,20 @@ FETCH cur1 INTO vTicketFk, vSaleFk; WHERE t.id = vClonTicket; */ INSERT INTO ticketLog - SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', + SET originFk = vTicketFk, userFk = account.myUser_getId(), `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); - + END IF; - + UPDATE vn.sale SET ticketFk = vClonTicket WHERE id = vSaleFk; SET vClonTicket = 0; - + SET done = 0; FETCH cur1 INTO vTicketFk, vSaleFk; - + END WHILE; CLOSE cur1; @@ -56808,8 +56810,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `getDayExpeditions`() BEGIN - SELECT - e.expeditions_id as expeditionFk, + SELECT + e.expeditions_id as expeditionFk, date_format(e.odbc_date,'%Y-%m-%d') as expeditionDate, e.ticket_id as ticketFk, t.routeFk as routeFk @@ -56886,7 +56888,7 @@ BEGIN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL yearsToDelete YEAR) INTO vDated FROM vn.greugeConfig; - + INSERT INTO vn.greuge(clientFk, description, amount, shipped, created, greugeTypeFk) SELECT clientFk, 'Suma agrupada', SUM(amount), MAX(shipped), MAX(created), greugeTypeFk FROM vn.greuge @@ -57004,8 +57006,8 @@ DECLARE done BOOL DEFAULT FALSE; DECLARE vTicketFk INT; DECLARE rs CURSOR FOR - SELECT id FROM vn.ticket - WHERE shipped = util.yesterday() + SELECT id FROM vn.ticket + WHERE shipped = util.yesterday() AND clientFk = 400 AND warehouseFk IN (1,44); @@ -57016,13 +57018,13 @@ OPEN rs; FETCH rs INTO vTicketFk; WHILE NOT done DO - + INSERT INTO vn.inventoryFailure(dated, itemFk, quantity, value, warehouseFk, throwerFk) - SELECT t.shipped, - s.itemFk, - s.quantity, + SELECT t.shipped, + s.itemFk, + s.quantity, b.buyingValue + b.freightValue + b.packageValue + b.comissionValue, - t.warehouseFk, + t.warehouseFk, w.id FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -57033,7 +57035,7 @@ WHILE NOT done DO AND s.quantity > 0; FETCH rs INTO vTicketFk; - + END WHILE; @@ -57101,7 +57103,7 @@ proc: BEGIN SELECT inventorySupplierFk INTO vInventorySupplierFk FROM entryConfig; - + SELECT am.id INTO vAgencyModeFkInventory FROM agencyMode am where code = 'inv'; @@ -57198,7 +57200,7 @@ proc: BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk WHERE tr.warehouseInFk = vWh - AND tr.landed BETWEEN vDateLastInventory + AND tr.landed BETWEEN vDateLastInventory AND vDateYesterday AND NOT isRaid GROUP BY b.itemFk; @@ -57252,7 +57254,7 @@ proc: BEGIN inv.price3 = b.price3, inv.minPrice = b.minPrice, inv.producer = p.name; - + INSERT INTO buy( itemFk, quantity, buyingValue, @@ -57286,15 +57288,15 @@ proc: BEGIN FROM tmp.inventory; SELECT vWh, COUNT(*), util.VN_NOW() FROM tmp.inventory; - + -- Actualizamos el campo lastUsed de item UPDATE item i JOIN tmp.inventory i2 ON i2.itemFk = i.id SET i.lastUsed = NOW() WHERE i2.quantity; - + -- DROP TEMPORARY TABLE tmp.inventory; - + END LOOP; CLOSE cWarehouses; @@ -57308,11 +57310,11 @@ proc: BEGIN SELECT e.id as entryId, t.id as travelId FROM travel t - JOIN `entry` e ON e.travelFk = t.id + JOIN `entry` e ON e.travelFk = t.id WHERE e.supplierFk = vInventorySupplierFk AND t.shipped <= util.VN_CURDATE() - INTERVAL 12 DAY AND (DAY(t.shipped) <> 1 OR shipped < util.VN_CURDATE() - INTERVAL 12 DAY); - + DELETE e FROM `entry` e JOIN tmp.entryToDelete tmp ON tmp.entryId = e.id; @@ -57374,7 +57376,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -57388,20 +57390,20 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk ) ON it.id = i.typeFk LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE (b.packageFk = "--" OR b.price2 = 0 OR b.packing = 0 OR b.buyingValue = 0) AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-1,util.VN_CURDATE())) AND s.name = 'INVENTARIO'; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOk; - CREATE TEMPORARY TABLE tmp.lastEntryOk + CREATE TEMPORARY TABLE tmp.lastEntryOk (PRIMARY KEY (buyFk)) SELECT i.id AS itemFk, @@ -57411,7 +57413,7 @@ BEGIN b.id AS buyFk, b.entryFk, b.isIgnored, - b.price2, + b.price2, b.price3, b.stickers, b.packing, @@ -57425,11 +57427,11 @@ BEGIN s.id AS supplierFk, s.name AS supplier FROM itemType it - RIGHT JOIN (entry e + RIGHT JOIN (entry e LEFT JOIN supplier s ON s.id = e.supplierFk RIGHT JOIN buy b ON b.entryFk = e.id LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN ink ON ink.id = i.inkFk LEFT JOIN travel tr ON tr.id = e.travelFk LEFT JOIN warehouse w ON w.id = tr.warehouseInFk LEFT JOIN origin o ON o.id = i.originFk @@ -57437,34 +57439,34 @@ BEGIN LEFT JOIN edi.ekt ek ON b.ektFk = ek.id WHERE b.packageFk != "--" AND b.price2 != 0 AND b.packing != 0 AND b.buyingValue > 0 AND tr.landed > util.firstDayOfMonth(TIMESTAMPADD(MONTH,-2,util.VN_CURDATE())) ORDER BY tr.landed DESC; - + DROP TEMPORARY TABLE IF EXISTS tmp.lastEntryOkGroup; - CREATE TEMPORARY TABLE tmp.lastEntryOkGroup + CREATE TEMPORARY TABLE tmp.lastEntryOkGroup (INDEX (warehouseFk,itemFk)) SELECT * FROM tmp.lastEntryOk tmp GROUP BY tmp.itemFk,tmp.warehouseFk; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packageFk = eo.packageFk WHERE b.packageFk = "--"; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.price2 = eo.price2 WHERE b.price2 = 0 ; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.packing = eo.packing WHERE b.packing = 0; - + UPDATE buy b JOIN tmp.lastEntry lt ON lt.buyFk = b.id JOIN tmp.lastEntryOkGroup eo ON eo.itemFk = lt.itemFk AND eo.warehouseFk = lt.warehouseFk SET b.buyingValue = eo.buyingValue WHERE b.buyingValue = 0; - + DROP TEMPORARY TABLE tmp.lastEntry; DROP TEMPORARY TABLE tmp.lastEntryOk; DROP TEMPORARY TABLE tmp.lastEntryOkGroup; @@ -57624,7 +57626,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceInDueDay_calculate`(vInvoiceInFk INT) BEGIN /** - * Calcula los vctos. de una factura recibida + * Calcula los vctos. de una factura recibida * En caso de haberlos informado previamente o que el proveedor sea español, no los recalculará * * @param vInvoiceInFk Factura recibida @@ -57645,46 +57647,46 @@ BEGIN WHERE ii.id = vInvoiceInFk; SELECT COUNT(*) INTO vHasDueDay - FROM invoiceInDueDay iid + FROM invoiceInDueDay iid WHERE iid.invoiceInFk = vInvoiceInFk; IF NOT vHasDueDay AND vCompanyCountryCode = 'ES' THEN SET @cont := 0; INSERT INTO invoiceInDueDay ( - invoiceInFk, - dueDated, - amount, + invoiceInFk, + dueDated, + amount, foreignValue ) SELECT vInvoiceInFk, - IF(payDay, + IF(payDay, IF(getNextDueDate(issued, pdd.detail, payDay) < created, created, - getNextDueDate(issued, pdd.detail, payDay)), + getNextDueDate(issued, pdd.detail, payDay)), GREATEST(created, issued + INTERVAL pdd.detail DAY)), - IF((@cont := @cont + 1) < cont, - TRUNCATE(venc / cont, 2), - venc - (TRUNCATE(venc / cont, 2) * (cont - 1))), - IF(@cont < cont, - TRUNCATE(foreignValue / cont, 2), - foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) - FROM ( - SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) - * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc, + IF((@cont := @cont + 1) < cont, + TRUNCATE(venc / cont, 2), + venc - (TRUNCATE(venc / cont, 2) * (cont - 1))), + IF(@cont < cont, + TRUNCATE(foreignValue / cont, 2), + foreignValue - (TRUNCATE(foreignValue / cont, 2) * (cont - 1))) + FROM ( + SELECT SUM((1 + (IFNULL(ti.PorcentajeIva, 0) / 100) * vHasDueDayTax) + * iit.taxableBase) / COUNT(DISTINCT(pdd.detail)) venc, SUM(iit.foreignValue) / COUNT(DISTINCT(pdd.detail)) foreignValue, - s.payDemFk, + s.payDemFk, ii.companyFk, COUNT(DISTINCT(pdd.detail)) cont, s.payDay, ii.issued, DATE(ii.created) + INTERVAL 2 DAY created - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk - JOIN supplier s ON s.id = ii.supplierFk - JOIN payDemDetail pdd ON pdd.id = s.payDemFk - WHERE ii.id = vInvoiceInFk + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN sage.TiposIva ti ON ti.CodigoIva= iit.taxTypeSageFk + JOIN supplier s ON s.id = ii.supplierFk + JOIN payDemDetail pdd ON pdd.id = s.payDemFk + WHERE ii.id = vInvoiceInFk GROUP BY ii.id )sub JOIN payDemDetail pdd ON pdd.id = sub.payDemFk @@ -57712,9 +57714,9 @@ BEGIN DELETE FROM invoiceInDueDay WHERE invoiceInFk = vInvoiceInFk; - + CALL invoiceInDueDay_calculate(vInvoiceInFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57798,7 +57800,7 @@ BEGIN CALL invoiceInTax_getFromEntries(vInvoiceInFk); CALL invoiceInDueDay_calculate(vInvoiceInFk); - + FETCH rs INTO vInvoiceInFk; END WHILE; @@ -57830,7 +57832,7 @@ BEGIN SELECT MAX(rr.dated) INTO vDated FROM referenceRate rr JOIN invoiceIn ii ON ii.id = vId - WHERE rr.dated <= ii.issued + WHERE rr.dated <= ii.issued AND rr.currencyFk = ii.currencyFk ; IF vDated THEN @@ -57839,13 +57841,13 @@ BEGIN WHERE dated = vDated; END IF; - SELECT id INTO vExpenceFk - FROM vn.expence - WHERE `name` = 'Adquisición mercancia Extracomunitaria' - GROUP BY id + SELECT id INTO vExpenceFk + FROM vn.expence + WHERE `name` = 'Adquisición mercancia Extracomunitaria' + GROUP BY id LIMIT 1; - - DELETE FROM invoiceInTax + + DELETE FROM invoiceInTax WHERE invoiceInFk = vId; INSERT INTO invoiceInTax(invoiceInFk, taxableBase, expenceFk, foreignValue, taxTypeSageFk, transactionTypeSageFk) @@ -57859,9 +57861,9 @@ BEGIN JOIN entry e ON e.invoiceInFk = ii.id JOIN supplier s ON s.id = e.supplierFk JOIN buy b ON b.entryFk = e.id - LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk + LEFT JOIN referenceRate rr ON rr.currencyFk = ii.currencyFk AND rr.dated = ii.issued - WHERE ii.id = vId + WHERE ii.id = vId HAVING taxableBase IS NOT NULL; END ;; DELIMITER ; @@ -57888,7 +57890,7 @@ BEGIN SELECT ii.bookEntried, iit.foreignValue, ii.companyFk, - ii.expenceFkDeductible, + ii.expenceFkDeductible, iit.taxableBase, iit.transactionTypeSageFk, ii.serial, @@ -57927,7 +57929,7 @@ BEGIN JOIN country c ON c.id = s.countryFk JOIN supplier sc ON sc.id = ii.companyFk JOIN country cc ON cc.id = sc.countryFk - JOIN invoiceInSerial iis ON iis.code = ii.serial + JOIN invoiceInSerial iis ON iis.code = ii.serial JOIN cplusInvoiceType472 cit ON cit.id = ii.cplusInvoiceType472Fk LEFT JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id LEFT JOIN sage.TiposTransacciones ttr ON ttr.CodigoTransaccion = iit.transactionTypeSageFk @@ -57950,18 +57952,18 @@ BEGIN NFACTICK, CLAVE, empresa_id) - SELECT + SELECT vBookNumber ASIEN, tii.bookEntried FECHA, tii.supplierAccount SUBCTA, - SUM(tii.taxableBase * - IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') - AND tii.taxTypeSageFk IS NOT NULL), - 1 + (tii.PorcentajeIva / 100), - 1)) EUROHABER, - CONCAT('s/fra', - RIGHT(tii.supplierRef, 8), - ':', + SUM(tii.taxableBase * + IF(tii.serial= 'R' AND ((tii.taxCode IS NULL OR tii.taxCode <> 'ISP21') + AND tii.taxTypeSageFk IS NOT NULL), + 1 + (tii.PorcentajeIva / 100), + 1)) EUROHABER, + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', LEFT(tii.supplierName, 10)) CONCEPTO, CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10,4)) CAMBIO, SUM(tii.foreignValue * IF(tii.serial = 'R', 1 + (tii.PorcentajeIva / 100), 1)) HABERME, @@ -57978,7 +57980,7 @@ BEGIN CONTRA, EURODEBE, EUROHABER, - CONCEPTO, + CONCEPTO, CAMBIO, DEBEME, HABERME, @@ -57990,9 +57992,9 @@ BEGIN tii.supplierAccount CONTRA, IF(tii.isWithheld AND tii.taxableBase < 0, NULL, ROUND(SUM(tii.taxableBase),2)) EURODEBE, IF(tii.isWithheld AND tii.taxableBase < 0, ROUND(SUM(-tii.taxableBase), 2), NULL) EUROHABER, - CONCAT('s/fra', - RIGHT(tii.supplierRef, 8), - ':', + CONCAT('s/fra', + RIGHT(tii.supplierRef, 8), + ':', LEFT(tii.supplierName, 10)) CONCEPTO, CAST(tii.taxableBase / tii.foreignValue AS DECIMAL (10, 4)) CAMBIO, IF(tii.isWithheld, NULL,ABS(ROUND(SUM(tii.foreignValue), 2))) DEBEME, @@ -58004,17 +58006,17 @@ BEGIN GROUP BY tii.expenceFk; -- Líneas de IVA - INSERT INTO XDiario( + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EURODEBE, BASEEURO, CONCEPTO, - FACTURA, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -58063,28 +58065,28 @@ BEGIN tii.companyFk FROM tInvoiceIn tii LEFT JOIN ( - SELECT e.id + SELECT e.id FROM tInvoiceIn tii - JOIN expence e ON e.id = tii.expenceFk + JOIN expence e ON e.id = tii.expenceFk WHERE e.isWithheld LIMIT 1 - ) eWithheld ON TRUE - WHERE tii.taxTypeSageFk IS NOT NULL - AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) + ) eWithheld ON TRUE + WHERE tii.taxTypeSageFk IS NOT NULL + AND (tii.taxCode IS NULL OR tii.taxCode NOT IN ('import10', 'import21')) GROUP BY tii.PorcentajeIva, tii.expenceFk; -- Línea iva inversor sujeto pasivo - INSERT INTO XDiario( + INSERT INTO XDiario( ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, - FACTURA, + FACTURA, IVA, - AUXILIAR, + AUXILIAR, SERIE, TIPOOPE, FECHA_EX, @@ -58133,31 +58135,31 @@ BEGIN JOIN sage.config c WHERE tii.taxCode = 'ISP21' OR MID(tii.supplierAccount, 4, 1) = '1' AND tii.taxTypeSageFk IS NOT NULL - AND NOT(tii.isVies - AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk + AND NOT(tii.isVies + AND c.nontaxableTransactionTypeFk = tii.transactionTypeSageFk AND tii.taxCode = 'nonTaxable') GROUP BY tii.PorcentajeIva, tii.expenceFk; - - -- Actualización del registro original + + -- Actualización del registro original UPDATE invoiceIn ii SET ii.isBooked = TRUE WHERE ii.id = vSelf; - + -- Problemas derivados de la precisión en los decimales al calcular los impuestos - UPDATE XDiario - SET EURODEBE = EURODEBE - + UPDATE XDiario + SET EURODEBE = EURODEBE - (SELECT IF(ABS(sub.difference) = 0.01, sub.difference, 0) FROM( - SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference + SELECT SUM(IFNULL(ROUND(EURODEBE, 2),0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) difference FROM XDiario WHERE ASIEN = vBookNumber )sub ) - WHERE ASIEN = vBookNumber + WHERE ASIEN = vBookNumber AND EURODEBE <> 0 ORDER BY id DESC LIMIT 1; - + DROP TEMPORARY TABLE tInvoiceIn; END ;; DELIMITER ; @@ -58272,7 +58274,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS rs; CREATE TEMPORARY TABLE rs - SELECT + SELECT c.accountingAccount AS clientBookingAccount, io.amount as totalAmount, CONCAT('n/fra ', io.ref) as simpleConcept, @@ -58306,19 +58308,19 @@ BEGIN WHERE io.id = vInvoice; CALL vn.ledger_next(vBookNumber); - + -- Linea del cliente INSERT INTO XDiario( ASIEN, FECHA, - SUBCTA, + SUBCTA, EURODEBE, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, rs.clientBookingAccount AS SUBCTA, @@ -58334,14 +58336,14 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, - CONCEPTO, + CONCEPTO, FECHA_EX, FECHA_OP, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, ioe.expenceFk AS SUBCTA, @@ -58355,8 +58357,8 @@ BEGIN JOIN invoiceOutExpence ioe WHERE ioe.invoiceOutFk = vInvoice; - SELECT GROUP_CONCAT(`name` SEPARATOR ',') - INTO vExpenceConcept + SELECT GROUP_CONCAT(`name` SEPARATOR ',') + INTO vExpenceConcept FROM expence e JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id WHERE ioe.invoiceOutFk = vInvoice; @@ -58366,7 +58368,7 @@ BEGIN ASIEN, FECHA, SUBCTA, - CONTRA, + CONTRA, EUROHABER, BASEEURO, CONCEPTO, @@ -58394,7 +58396,7 @@ BEGIN TIPORECTIF, empresa_id ) - SELECT + SELECT vBookNumber AS ASIEN, rs.FECHA, iot.pgcFk AS SUBCTA, @@ -58414,11 +58416,11 @@ BEGIN rs.FECHA_OP, rs.FECHA_EX, rs.TIPOOPE, - rs.NFACTICK, + rs.NFACTICK, rs.TERIDNIF, rs.TERNIF, rs.TERNOM, - pgc.mod340 AS L340, + pgc.mod340 AS L340, pgc.cplusTrascendency477Fk AS TIPOCLAVE, pgc.cplusTaxBreakFk as TIPOEXENCI, rs.TIPONOSUJE, @@ -58426,13 +58428,13 @@ BEGIN rs.TIPORECTIF, rs.companyFk AS empresa_id FROM rs - JOIN invoiceOutTax iot + JOIN invoiceOutTax iot JOIN pgc ON pgc.code = iot.pgcFk LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk -- --------------- Comprueba si la linea es de iva con rec.equiv. asociado - LEFT JOIN pgc pgce ON pgce.code = pe.equFk + LEFT JOIN pgc pgce ON pgce.code = pe.equFk LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk -- --------------- Comprueba si la linea es de rec.equiv. WHERE iot.invoiceOutFk = vInvoice; - + UPDATE invoiceOut SET booked = util.VN_CURDATE() WHERE id = vInvoice; @@ -58464,7 +58466,7 @@ BEGIN DECLARE done BOOL DEFAULT FALSE; - DECLARE rs CURSOR FOR + DECLARE rs CURSOR FOR SELECT io.id FROM invoiceOut io WHERE RIGHT(ref,7) BETWEEN 1724215 AND 1724224 @@ -58479,15 +58481,15 @@ BEGIN WHILE NOT done DO CALL invoiceOutBooking(vInvoice); - + FETCH rs INTO vInvoice ; - + SET vContador = vContador + 1; - + IF vContador MOD 50 = 0 THEN - + SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS; - + END IF; END WHILE; @@ -58517,14 +58519,14 @@ BEGIN DECLARE vAsien INTEGER; DECLARE vSendMail BOOL; DECLARE vBody TEXT; - + SELECT ASIEN INTO vAsien - FROM XDiario + FROM XDiario WHERE SERIE = SUBSTRING(vRef, 1, 1) AND FACTURA = SUBSTRING(vRef, 2, LENGTH(vRef)-1) LIMIT 1; - SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), + SELECT IF(enlazado OR enlazadoSage, TRUE, FALSE), CONCAT( ' @@ -58533,7 +58535,7 @@ BEGIN - ', + ', GROUP_CONCAT( CONCAT(' @@ -58546,14 +58548,14 @@ BEGIN ) SEPARATOR ' ' ), '
FECHACONCEPTO EURODEBE EUROHABER
', IFNULL(FECHA,''), '
' - ) + ) INTO vSendMail, vBody - FROM XDiario + FROM XDiario WHERE ASIEN = vAsien; - DELETE FROM XDiario + DELETE FROM XDiario WHERE ASIEN = vAsien; - + IF vSendMail THEN CALL mail_insert( 'administracion@verdnatura.es', @@ -58571,7 +58573,7 @@ BEGIN SET refFk = NULL WHERE refFk = vRef; - DELETE + DELETE FROM invoiceOut WHERE ref = vRef; @@ -58594,7 +58596,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE) BEGIN -SELECT +SELECT c.socialName as RazonSocial, c.fi as NIF, io.ref as Factura, @@ -58606,7 +58608,7 @@ SELECT pgc.rate as Tipo, iot.vat as Cuota, pgc.name as Concepto - + FROM vn.invoiceOut io JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id JOIN vn.client c ON c.id = io.clientFk @@ -59051,17 +59053,17 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `invoiceOut_newFromClient`( - IN vClientFk INT, - IN vSerial CHAR(2), + IN vClientFk INT, + IN vSerial CHAR(2), IN vMaxShipped DATE, - IN vCompanyFk INT, + IN vCompanyFk INT, IN vTaxArea VARCHAR(25), - IN vRef VARCHAR(25), + IN vRef VARCHAR(25), OUT vInvoiceId INT) BEGIN /** * Factura los tickets de un cliente hasta una fecha dada - * @param vClientFk Id del cliente a facturar + * @param vClientFk Id del cliente a facturar * @param vSerial Serie de factura * @param vMaxShipped Fecha hasta la cual cogera tickets para facturar * @param vCompanyFk Id de la empresa desde la que se factura @@ -59080,11 +59082,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - END IF; + END IF; SELECT COUNT(*) INTO vIsExportation FROM vn.invoiceOutSerial - WHERE taxAreaFk = 'WORLD' + WHERE taxAreaFk = 'WORLD' AND `code` = vSerial; IF vIsExportation THEN @@ -59097,7 +59099,7 @@ BEGIN UPDATE invoiceOut SET `ref` = vRef - WHERE id = vInvoiceId + WHERE id = vInvoiceId AND vRef IS NOT NULL; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN @@ -59126,7 +59128,7 @@ BEGIN * Factura un ticket * @param vTicketFk Id del ticket * @param vSerial Serie de factura - * @param vTaxArea Area de la factura en caso de querer forzarlo, + * @param vTaxArea Area de la factura en caso de querer forzarlo, * en la mayoria de los casos poner NULL * @return vInvoiceId */ @@ -59141,11 +59143,11 @@ BEGIN IF NOT vIsRefEditable THEN CALL util.throw('serial non editable'); END IF; - - UPDATE invoiceOut + + UPDATE invoiceOut SET `ref` = vRef WHERE id = vInvoiceId; - END IF; + END IF; IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN CALL invoiceOutBooking(vInvoiceId); @@ -59227,7 +59229,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemBarcode_update`(vItemFk INT,vCo BEGIN IF vDelete THEN DELETE FROM vn.itemBarcode WHERE itemFk = vItemFk AND code = vCode; -ELSE +ELSE INSERT INTO vn.itemBarcode(itemFk,code) VALUES (vItemFk,vCode); END IF; @@ -59249,8 +59251,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFreight_Show`(vItemFk INT, vWarehouseFk INT) BEGIN - - SELECT cm3 Volumen_Entrada, + + SELECT cm3 Volumen_Entrada, cm3delivery Volumen_Salida, p.volume Volumen_del_embalaje, p.width Ancho_del_embalaje, @@ -59263,11 +59265,11 @@ BEGIN b.id buyFk, b.entryFk, w.name warehouseFk - FROM vn.itemCost ic - JOIN vn.item i ON i.id = ic.itemFk - LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk - LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.packaging p ON p.id = b.packageFk + FROM vn.itemCost ic + JOIN vn.item i ON i.id = ic.itemFk + LEFT JOIN cache.last_buy lb ON lb.item_id = ic.itemFk AND lb.warehouse_id = ic.warehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN vn.packaging p ON p.id = b.packageFk LEFT JOIN vn.warehouse w ON w.id = ic.warehouseFk WHERE ic.itemFk = vItemFk AND ic.warehouseFk = vWarehouseFk; @@ -59291,33 +59293,33 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemFuentesBalance`(vDaysInFuture I BEGIN /* Se utiliza para calcular la necesidad de mover mercancia entre el almacén de fuentes y el nuestro - * + * * @param vDaysInFuture Rango de dias para calcular entradas y salidas - * + * */ - + DECLARE vWarehouseFk INT; SELECT s.warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.code = 'FUENTES_PICASSE'; - + CALL cache.stock_refresh(FALSE); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, i.size, i.subName, - v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, - fue.Fuentes, + v.amount - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as visible, + fue.Fuentes, alb.Albenfruit, - sale.venta, - IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) + sale.venta, + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, + IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) - IFNULL(fue.Fuentes,0) - IFNULL(alb.albenfruit,0) as saldo - FROM vn.item i - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + FROM vn.item i + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Fuentes FROM vn.itemShelving ish @@ -59325,7 +59327,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'FUENTES_PICASSE' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) fue ON fue.itemFk = i.id LEFT JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS Albenfruit @@ -59334,7 +59336,7 @@ BEGIN JOIN vn.parking p ON p.id = sh.parkingFk JOIN vn.sector s ON s.id = p.sectorFk WHERE s.code = 'ALBENFRUIT' - GROUP BY ish.itemFk + GROUP BY ish.itemFk ) alb ON alb.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = vWarehouseFk LEFT JOIN ( @@ -59359,9 +59361,9 @@ BEGIN AND warehouse_id = vWarehouseFk GROUP BY item_id ) mov ON mov.item_id = i.id - WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) + WHERE (v.amount OR fue.Fuentes OR alb.Albenfruit) AND i.itemPackingTypeFk = 'H' - AND ic.shortLife + AND ic.shortLife ; END ;; @@ -59383,7 +59385,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementFromTicket`(vTicket INT) BEGIN /** - * Llama a itemPlacementUpdateVisible + * Llama a itemPlacementUpdateVisible * de los articulos de la tabla temporal tmp.itemPlacement(itemFk) * @treturn tmp.itemPlacement * @param vTicket Id del Ticket @@ -59397,9 +59399,9 @@ BEGIN FROM ticket t JOIN sale s ON s.ticketFk = t.id WHERE t.id = vTicket; - + CALL itemPlacementUpdateVisible(); - + DROP TEMPORARY TABLE tmp.itemPlacement; END ;; DELIMITER ; @@ -59432,7 +59434,7 @@ BEGIN CAST(FLOOR(LEAST(ish.stock,quantity) / ish.packing) AS DECIMAL(10,0)), ' x ', ish.packing, - IF ( + IF ( LEAST(ish.stock,quantity) MOD ish.packing, CONCAT(' + ',CAST(LEAST(ish.stock,quantity) MOD ish.packing AS DECIMAL(10,0))), '' @@ -59463,7 +59465,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemPlacementSupplyCloseOrder`(vId INT, vQuantity INT) BEGIN - UPDATE vn.itemPlacementSupply + UPDATE vn.itemPlacementSupply SET priority = 10 WHERE id = vId; @@ -59489,7 +59491,7 @@ BEGIN DECLARE vId INT; DECLARE vLastParkingFk INT; DECLARE vNextParkingFk INT; - + SELECT sh.parkingFk INTO vLastParkingFk FROM vn.itemShelvingPlacementSupply isps JOIN vn.itemShelving ish ON ish.id = isps.itemShelvingFk @@ -59497,9 +59499,9 @@ BEGIN WHERE isps.userFk = getUser() ORDER BY isps.created DESC LIMIT 1; - + SET vNextParkingFk = vn.itemShelvingPlacementSupply_ClosestGet(vLastParkingFk); - + SELECT ipsl.id INTO vId FROM vn.itemPlacementSupplyList ipsl JOIN vn.itemShelvingPlacementSupplyStock ispss ON ispss.itemFk = ipsl.itemFk @@ -59508,13 +59510,13 @@ BEGIN AND ipsl.sectorFk = vSector ORDER BY ipsl.repoUserFk DESC, ipsl.priority DESC, (ispss.parkingFk = vNextParkingFk) DESC, ispss.parking DESC, ipsl.created LIMIT 1; - + UPDATE vn.itemPlacementSupply SET repoUserFk = getUser() WHERE id = vId; - - SELECT * FROM vn.itemPlacementSupplyList - WHERE id = vId + + SELECT * FROM vn.itemPlacementSupplyList + WHERE id = vId AND sectorFk = vSector; END ;; @@ -59589,20 +59591,20 @@ BEGIN * @param vItemFk item id * @param vTicketFk ticket id * @param vShowType mostrar tipos - */ + */ DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vCalcFk INT; DECLARE vTypeFk INT; - - + + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -59612,16 +59614,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59654,7 +59656,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1 COLLATE utf8_general_ci) DESC, (it1.value = vValue1 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, @@ -59662,7 +59664,7 @@ BEGIN (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, (i.tag8 = vTag8 COLLATE utf8_general_ci) DESC, (i.value8 = vValue8 COLLATE utf8_general_ci) DESC; - + END ;; DELIMITER ; @@ -59688,7 +59690,7 @@ BEGIN * @param vSaleFk id de la tabla sale * @param vMateFk articulo sustituto * @ param vQuantity cantidad que se va a sustituir - */ + */ DECLARE vTicketFk INT; DECLARE vItemFk INT; DECLARE vWarehouseFk SMALLINT; @@ -59697,41 +59699,41 @@ BEGIN DECLARE vBox INT; DECLARE vPacking INT; DECLARE vRoundQuantity INT DEFAULT 1; - + SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk FROM vn.sale s JOIN vn.ticket t ON t.id = s.ticketFk WHERE s.id = vSaleFk; - + UPDATE vn.sale SET quantity = quantity - vQuantity WHERE id = vSaleFk; - + CALL vn.buyUltimate(vWarehouseFk, vDate); - + SELECT `grouping`, groupingMode, packing INTO vGrouping,vBox,vPacking FROM buy b JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk; - + IF vBox = 2 AND vPacking > 0 THEN SET vRoundQuantity = vPacking; END IF; IF vBox = 1 AND vGrouping > 0 THEN SET vRoundQuantity = vGrouping; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept) SELECT vTicketFk, vMateFk, CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName) FROM vn.item i WHERE id = vMateFk; - + SELECT LAST_INSERT_ID() INTO vSaleFk; - + CALL vn.sale_calculateComponent(vSaleFk, NULL); - + INSERT INTO vn.itemProposal(itemFk, mateFk, counter) VALUES(vItemFk, vMateFk, 1) ON DUPLICATE KEY UPDATE counter = counter + 1; @@ -59760,13 +59762,13 @@ BEGIN DECLARE vCalcFk INT; DECLARE vTypeFk INT; DECLARE vResultsMax INT DEFAULT 10; - + DECLARE vTag1 VARCHAR(25); DECLARE vTag5 VARCHAR(25); DECLARE vTag6 VARCHAR(25); DECLARE vTag7 VARCHAR(25); DECLARE vTag8 VARCHAR(25); - + DECLARE vValue1 VARCHAR(50); DECLARE vValue5 VARCHAR(50); DECLARE vValue6 VARCHAR(50); @@ -59776,16 +59778,16 @@ BEGIN SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped FROM vn.ticket WHERE id = vTicketFk; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 - FROM vn.item i + FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vShipped); - + SELECT i.id itemFk, i.longName, i.subName, @@ -59803,7 +59805,7 @@ BEGIN (i.value8 <=> vValue8 COLLATE utf8_general_ci) match8, a.available, IFNULL(ip.counter,0) counter - FROM vn.item i + FROM vn.item i JOIN cache.available a ON a.item_id = i.id LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vItemFk LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 @@ -59817,7 +59819,7 @@ BEGIN (it1.value = vValue1 COLLATE utf8_general_ci) DESC, (i.tag5 = vTag5 COLLATE utf8_general_ci) DESC, (i.value5 = vValue5 COLLATE utf8_general_ci) DESC, - (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, + (i.tag6 = vTag6 COLLATE utf8_general_ci) DESC, (i.value6 = vValue6 COLLATE utf8_general_ci) DESC, (i.tag7 = vTag7 COLLATE utf8_general_ci) DESC, (i.value7 = vValue7 COLLATE utf8_general_ci) DESC, @@ -59853,7 +59855,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.item SELECT vItem id; - + CALL item_refreshTags(); DROP TEMPORARY TABLE tmp.item; @@ -59876,23 +59878,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSale_byWeek`(vWeek INT, IN vYear INT, vItemFk INT, vWarehouseFk INT) BEGIN - + DECLARE vStarted DATE; DECLARE vEnded DATETIME; SELECT MIN(dated), util.dayEnd(MAX(dated)) INTO vStarted, vEnded - FROM `time` t + FROM `time` t WHERE CONCAT(vYear, LPAD(vWeek, 2, 0)) = t.period; SELECT t.shipped, w.name warehouse, - s.ticketFk, + s.ticketFk, t.nickname client, - am.name agencyName, + am.name agencyName, wk.code salesPerson, s.itemFk, - IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, - s.quantity, + IFNULL(CONCAT(ig.longName,' ',ig.`size`,' ',ig.subName), s.concept) AS concept, + s.quantity, s.price, s.priceFixed, s.discount, @@ -59902,15 +59904,15 @@ BEGIN wk.id salesPersonFk FROM sale s JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk + JOIN warehouse w ON w.id = t.warehouseFk JOIN address a ON a.id = t.addressFk LEFT JOIN agencyMode am ON am.id = t.agencyModeFk JOIN `client` c ON c.id = a.clientFk - LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN worker wk ON wk.id = c.salesPersonFk LEFT JOIN ticketLastState tls ON tls.ticketFk = t.id - LEFT JOIN saleBuy sb ON sb.saleFk = s.id - LEFT JOIN buy b ON b.id = sb.buyFk - LEFT JOIN item ig ON ig.id = b.itemOriginalFk + LEFT JOIN saleBuy sb ON sb.saleFk = s.id + LEFT JOIN buy b ON b.id = sb.buyFk + LEFT JOIN item ig ON ig.id = b.itemOriginalFk WHERE s.itemFk = vItemFk AND t.shipped BETWEEN vStarted AND vEnded AND IF(vWarehouseFk = 0, w.hasComission , t.warehouseFk = vWarehouseFk) @@ -59937,9 +59939,9 @@ BEGIN DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE vn.item SET minimum = min WHERE id = vItemFk; - + END ;; @@ -59961,8 +59963,8 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemSearchShelving`(`vShelvingFk` VARCHAR(3)) BEGIN SELECT p.`column` AS col , p.`row` - FROM vn.shelving s - JOIN parking p ON s.parkingFk = p.id + FROM vn.shelving s + JOIN parking p ON s.parkingFk = p.id WHERE s.`code` = vShelvingFk COLLATE utf8_general_ci; END ;; DELIMITER ; @@ -60003,36 +60005,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingLog_get`(vShelvingFk VARCHAR(10) ) BEGIN - + /** * Devuelve el log de los item en cada carro * - * @param vShelvingFk Matrícula del carro - * + * @param vShelvingFk Matrícula del carro + * */ - - SELECT isl.itemShelvingFk, - isl.created, - isl.accion, - isl.itemFk, - isl.shelvingFk, - isl.quantity, + + SELECT isl.itemShelvingFk, + isl.created, + isl.accion, + isl.itemFk, + isl.shelvingFk, + isl.quantity, isl.visible, - isl.available, - isl.grouping, - isl.packing, - isl.stars, - item.longName, - item.size, - item.subName, - worker.code, + isl.available, + isl.grouping, + isl.packing, + isl.stars, + item.longName, + item.size, + item.subName, + worker.code, isl.accion - FROM item - JOIN itemShelvingLog isl ON item.id = isl.itemFk + FROM item + JOIN itemShelvingLog isl ON item.id = isl.itemFk JOIN worker ON isl.workerFk = worker.id WHERE shelvingFk = vShelvingFk OR isl.itemFk = vShelvingFk ORDER BY isl.created DESC; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60051,7 +60053,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMakeFromDate`(IN `vShelvingFk` VARCHAR(8), IN `vBarcode` VARCHAR(22), IN `vQuantity` INT, IN `vPackagingFk` VARCHAR(10), IN `vGrouping` INT, IN `vPacking` INT, IN `vWarehouseFk` INT, `vCreated` VARCHAR(22)) BEGIN - + DECLARE vItemFk INT; SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; @@ -60070,9 +60072,9 @@ BEGIN END IF; - IF (SELECT COUNT(*) FROM vn.itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM vn.itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE vn.itemShelving @@ -60102,8 +60104,8 @@ BEGIN LEFT JOIN cache.last_buy lb ON i.id = lb.item_id AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id WHERE i.id = vItemFk; - END IF; - + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60124,9 +60126,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingMatch`(vEntryFk INT, vA BEGIN DECLARE vTravelFk INT; - - SELECT travelFk INTO vTravelFk - FROM entry + + SELECT travelFk INTO vTravelFk + FROM entry WHERE id = vEntryFk; SELECT i.id, i.longName, i.size, i.subName, b.stickers, ish.etiquetas, b.printed @@ -60139,7 +60141,7 @@ BEGIN GROUP BY itemFk ) b ON b.itemFk = i.id LEFT JOIN ( - SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas + SELECT itemFk, sum(cast(visible / packing AS DECIMAL(10,0))) AS etiquetas FROM itemShelving ish JOIN shelving sh ON sh.code = ish.shelvingFk LEFT JOIN parking pk ON pk.id = sh.parkingFk @@ -60179,7 +60181,7 @@ BEGIN UPDATE vn.itemShelving SET visible = visible - vQuantity WHERE id = vItemShelvingFk; - + END ;; DELIMITER ; @@ -60202,47 +60204,47 @@ BEGIN DECLARE vVisibleCache INT; DECLARE vWarehouseFk INT; - + SELECT warehouseFk INTO vWarehouseFk FROM vn.sector WHERE id = vSectorFk; CALL cache.visible_refresh (vVisibleCache, FALSE, vWarehouseFk); - - SELECT t.id as ticketFk, - CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, - s.itemFk, - s.concept, - v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, + + SELECT t.id as ticketFk, + CAST(s.quantity AS DECIMAL(10,0)) as Cantidad, + s.itemFk, + s.concept, + v.visible - GREATEST(0,iss.visible) + IFNULL(sub3.transit,0) as Nicho, i.subName, - GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, + GREATEST(0,iss.visible - IFNULL(sub3.transit,0)) as Altillo, s.id as saleFk, IFNULL(sub3.transit,0) transit, v.visible, s.isPicked, s.reserved, t.shipped, tst.productionOrder, mm.Id_Movimiento - FROM vn.ticket t + FROM vn.ticket t JOIN vn.ticketState tst ON tst.ticketFk = t.id JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN cache.visible v ON s.itemFk = v.item_id AND v.calc_id = vVisibleCache LEFT JOIN vn2008.Movimientos_mark mm ON mm.Id_Movimiento = s.id AND mm.stateFk = 26 - JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id + JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id LEFT JOIN - (SELECT itemFk, sum(saldo) as transit - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + (SELECT itemFk, sum(saldo) as transit + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 AND sectorFk = vSectorFk GROUP BY itemFk) sub3 ON sub3.itemFk = i.id - WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity + WHERE v.visible + IFNULL(sub3.transit,0) - GREATEST(0,iss.visible) < s.quantity AND IFNULL(sub3.transit,0) < s.quantity - AND s.isPicked = FALSE + AND s.isPicked = FALSE AND s.reserved = FALSE - AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) + AND t.shipped BETWEEN util.VN_CURDATE() AND MIDNIGHT(util.VN_CURDATE()) AND tst.isPreviousPreparable = TRUE AND t.warehouseFk = vWarehouseFk AND iss.sectorFk = vSectorFk AND mm.Id_Movimiento IS NULL ORDER BY itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60261,7 +60263,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingRadar`(vSectorFk INT) proc:BEGIN - + DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE hasFatherSector BOOLEAN; @@ -60269,17 +60271,17 @@ proc:BEGIN DECLARE vWarehouseFk INT DEFAULT 0; DECLARE vSonSectorFk INT; DECLARE vWorkerFk INT; - - SELECT s.workerFk - INTO vWorkerFk + + SELECT s.workerFk + INTO vWorkerFk FROM vn.sector s WHERE s.id = vSectorFk; SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk - FROM vn.worker w + FROM vn.worker w JOIN vn.sector s ON s.code = w.code WHERE s.id = vSectorFk; - + SELECT s.id INTO vSectorFk FROM vn.sector s WHERE s.warehouseFk = vWarehouseFk @@ -60289,21 +60291,21 @@ proc:BEGIN SELECT COUNT(*) INTO hasFatherSector FROM vn.sector WHERE sonFk = vSectorFk; - + SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk FROM vn.sector WHERE id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; - + IF hasFatherSector THEN CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM ( SELECT iss.itemFk, i.longName, @@ -60314,7 +60316,7 @@ proc:BEGIN SUM(IF(iss.sectorFk = vSectorFk, IFNULL(iss.visible,0), 0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible,0)) as visible, vSectorFk as sectorFk - + FROM vn.itemShelvingStock iss JOIN vn.sector s ON s.id = iss.sectorFk JOIN vn.item i on i.id = iss.itemFk @@ -60323,11 +60325,11 @@ proc:BEGIN LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE vSectorFk IN (iss.sectorFk, s.sonFk) AND it.workerFk != 3366 - + GROUP BY iss.itemFk - + UNION ALL - + SELECT v.item_id, i.longName, i.size, @@ -60337,7 +60339,7 @@ proc:BEGIN 0 downstairs, IF(it.isPackaging, NULL, v.visible) visible, vSectorFk as sectorFk - FROM cache.visible v + FROM cache.visible v JOIN vn.item i on i.id = v.item_id JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk @@ -60346,8 +60348,8 @@ proc:BEGIN AND iss.itemFk IS NULL AND it.isInventory ) sub GROUP BY itemFk; - - SELECT ishr.*, + + SELECT ishr.*, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente FROM tmp.itemShelvingRadar ishr @@ -60362,13 +60364,13 @@ proc:BEGIN ) sub ON sub.itemFk = ishr.itemFk ORDER BY i.typeFk, i.longName ; - - + + ELSE - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT iss.itemFk, 0 `hour`, 0 `minute`, @@ -60380,7 +60382,7 @@ proc:BEGIN IFNULL(a.available,0) available, IFNULL(v.visible - iss.visible,0) dayEndVisible, IFNULL(v.visible - iss.visible,0) firstNegative, - IFNULL(v.visible - iss.visible,0) itemPlacementVisible, + IFNULL(v.visible - iss.visible,0) itemPlacementVisible, IFNULL(i.minimum * b.packing,0) itemPlacementSize, ips.onTheWay, iss.visible itemShelvingStock, @@ -60394,13 +60396,13 @@ proc:BEGIN LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay - FROM vn.itemPlacementSupplyList - WHERE saldo > 0 + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 GROUP BY itemFk ) ips ON ips.itemFk = i.id - WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) - OR iss.sectorFk = vSectorFk; - /* + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + OR iss.sectorFk = vSectorFk; + /* UPDATE tmp.itemShelvingRadar isr JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk SET isr.dayEndVisible = isr.dayEndVisible + iss.visible, @@ -60411,10 +60413,10 @@ proc:BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; CREATE TEMPORARY TABLE tmp.itemOutTime SELECT *,SUM(amount) quantity - FROM + FROM (SELECT item_id itemFk, - amount, - IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + 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 @@ -60422,23 +60424,23 @@ proc:BEGIN JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk JOIN vn.state s ON s.id = ts.stateFk LEFT JOIN vn.zone z ON z.id = t.zoneFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM vn.saleTracking st - WHERE st.created > util.VN_CURDATE() + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + WHERE st.created > util.VN_CURDATE() AND st.isChecked ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk WHERE t.warehouseFk = vWarehouseFk - AND s.isPicked = 0 - AND NOT io.Reservado + AND s.isPicked = 0 + AND NOT io.Reservado AND stPrevious.saleFk IS NULL - AND io.dat >= util.VN_CURDATE() + AND io.dat >= util.VN_CURDATE() AND io.dat < util.VN_CURDATE() + INTERVAL 1 DAY ) sub GROUP BY itemFk, hours, minutes; - + INSERT INTO tmp.itemShelvingRadar (itemFk) SELECT itemFk FROM tmp.itemOutTime - ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); @@ -60454,7 +60456,7 @@ proc:BEGIN END IF; DROP TEMPORARY TABLE tmp.itemShelvingRadar; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60478,24 +60480,24 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, i.minimum, CAST(IFNULL(v.visible,0) - IFNULL(iss.visible,0) AS DECIMAL(10,0)) as enNicho, CAST(IFNULL(a.available,0) AS DECIMAL(10,0)) as disponible, @@ -60515,11 +60517,11 @@ BEGIN AND IFNULL(tst.productionOrder,0) < 5 GROUP BY s.itemFK ) ts ON ts.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60543,34 +60545,34 @@ BEGIN DECLARE vCalcVisibleFk INT; DECLARE vCalcAvailableFk INT; DECLARE vTodayDayEnd DATETIME DEFAULT util.dayEnd(util.VN_CURDATE()); - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, 1); CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, util.VN_CURDATE()); - + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item ENGINE = MEMORY SELECT DISTINCT itemFk - FROM vn.buy + FROM vn.buy WHERE entryFk = vEntryFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.item2; CREATE TEMPORARY TABLE tmp.item2 ENGINE = MEMORY SELECT * FROM tmp.item; - - SELECT i.id as itemFk, + + SELECT i.id as itemFk, CAST(IFNULL(iss.visible,0) - IFNULL(v.visible,0) AS DECIMAL(10,0)) as outShelving FROM vn.item i JOIN tmp.item ti ON ti.itemFk = i.id LEFT JOIN cache.visible v ON v.calc_id = vCalcVisibleFk AND v.item_id = i.id LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id; - - + + DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.item2; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60591,10 +60593,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_Add`(vItemShelving BEGIN /** * Añade línea a itemShelvingSale y regulariza el carro - * + * * @param vItemShelvingFk Id itemShelving * @param vSaleFk Id de sale - * @param vQuantity cantidad a regularizar + * @param vQuantity cantidad a regularizar */ INSERT INTO itemShelvingSale(itemShelvingFk, saleFk, @@ -60689,7 +60691,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`(IN vShelvingFk VARCHAR(8), IN vBarcode VARCHAR(22), IN vQuantity INT, IN vPackagingFk VARCHAR(10), IN vGrouping INT, IN vPacking INT, IN vWarehouseFk INT) BEGIN - + /** * Añade registro o lo actualiza si ya existe. @@ -60701,7 +60703,7 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving, NULL para coger el de la ultima compra * @param vPacking el packing del producto, NULL para coger el de la ultima compra * @param vWarehouseFk indica el sector - * + * **/ DECLARE vItemFk INT; @@ -60711,21 +60713,21 @@ BEGIN IF (SELECT COUNT(*) FROM shelving WHERE code = vShelvingFk COLLATE utf8_unicode_ci) = 0 THEN INSERT IGNORE INTO parking(code) VALUES(vShelvingFk); - INSERT INTO shelving(code, parkingFk) + INSERT INTO shelving(code, parkingFk) SELECT vShelvingFk, id - FROM parking + FROM parking WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; END IF; - IF (SELECT COUNT(*) FROM itemShelving - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk - AND itemFk = vItemFk + IF (SELECT COUNT(*) FROM itemShelving + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk + AND itemFk = vItemFk AND packing = vPacking) = 1 THEN UPDATE itemShelving SET visible = visible+vQuantity - WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; + WHERE shelvingFk COLLATE utf8_unicode_ci = vShelvingFk AND itemFk = vItemFk AND packing = vPacking; ELSE CALL cache.last_buy_refresh(FALSE); @@ -60870,7 +60872,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_BuyerGet`( ) BEGIN SELECT * FROM vn.buyer; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60897,10 +60899,10 @@ proc:BEGIN * @return Lista de articulos */ DECLARE vCalcVisibleFk INT; - + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); - SELECT * FROM + SELECT * FROM (SELECT sub.itemFk, sub.longName, CONCAT('Hoy saldrán ', CAST(sub2.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -60917,28 +60919,28 @@ proc:BEGIN 0 upstairs, SUM(IFNULL(iss.visible,0)) downstairs, IF(it.isPackaging, null, IFNULL(v.visible, 0)) visible, - ik.name + ik.name FROM itemShelvingStock iss JOIN sector s ON s.id = iss.sectorFk JOIN item i on i.id = iss.itemFk - LEFT JOIN ink ik ON ik.id = i.inkFk + LEFT JOIN ink ik ON ik.id = i.inkFk JOIN itemType it ON it.id = i.typeFk LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk WHERE s.warehouseFk = vWarehouseFk AND it.workerFk = vBuyerFk - GROUP BY itemFk + GROUP BY itemFk ) sub LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND st.saleFk IS NULL AND ct.code IN ('normal', 'trust') GROUP BY s.itemFk - ) sub2 ON sub2.itemFk = sub.itemFk - UNION ALL + ) sub2 ON sub2.itemFk = sub.itemFk + UNION ALL SELECT v.item_id , i.longName, CONCAT('Hoy saldrán ', CAST(sub5.pendiente AS DECIMAL(10,0)), ' unidades.') `size`, @@ -60956,7 +60958,7 @@ proc:BEGIN LEFT JOIN (SELECT s.itemFk, SUM(s.quantity) pendiente FROM sale s LEFT JOIN saleTracking st ON st.saleFk = s.id - JOIN ticket t ON t.id = s.ticketFk + JOIN ticket t ON t.id = s.ticketFk JOIN client c on c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) @@ -60989,12 +60991,12 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_get`(IN vSelf VARCHAR(8)) BEGIN /** -* Lista artículos de itemshelving +* Lista artículos de itemshelving * * @param vSelf matrícula del carro **/ - SELECT ish.itemFk item, - IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description, + SELECT ish.itemFk item, + IFNULL(i.longName, CONCAT(i.name, ' ', i.size)) description, ish.visible, CEIL(ish.visible/ish.packing) stickers, ish.packing, @@ -61032,7 +61034,7 @@ BEGIN * * @param vShelvingFk matricula del carro */ - SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder + SELECT is2.id,is2.shelvingFk , p.code, is2.itemFk , is2.visible, p.pickingOrder FROM itemShelving is2 JOIN shelving sh ON sh.code = is2.shelvingFk JOIN parking p ON p.id = sh.parkingFk @@ -61098,35 +61100,35 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_getSaleDate`(vShelvingFk VARCHAR(3)) BEGIN - + /* Devuelve la minima fecha en que se necesita cada producto en esa matricula. - * + * * @param vShelvingFk Matrícula del carro o pallet */ - + DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk FROM shelving s - JOIN parking p ON s.parkingFk = p.id + JOIN parking p ON s.parkingFk = p.id JOIN sector st ON st.id = p.sectorFk WHERE s.code = vShelvingFk COLLATE utf8_unicode_ci; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingDistinct; CREATE TEMPORARY TABLE tmp.itemShelvingDistinct (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT itemFk, SUM(visible) visible - FROM vn.itemShelving + FROM vn.itemShelving WHERE shelvingFk = vShelvingFk COLLATE utf8_unicode_ci - GROUP BY itemFk; - + GROUP BY itemFk; + DROP TEMPORARY TABLE IF EXISTS tmp.item; CREATE TEMPORARY TABLE tmp.item (PRIMARY KEY (itemFk)) ENGINE = MEMORY SELECT * FROM tmp.itemShelvingDistinct; - + DROP TEMPORARY TABLE IF EXISTS tmp.stockByDay; CREATE TEMPORARY TABLE tmp.stockByDay (index (itemFk, dated)) @@ -61137,16 +61139,16 @@ BEGIN FROM ( SELECT * FROM ( SELECT t2.* FROM ( - SELECT item_id itemFk, amount, util.VN_CURDATE() dated - FROM cache.stock + SELECT item_id itemFk, amount, util.VN_CURDATE() dated + FROM cache.stock WHERE warehouse_id = vWarehouseFk UNION ALL SELECT ish.itemFk, - sum(visible), util.VN_CURDATE() - FROM vn.itemShelving ish - JOIN shelving sh ON sh.code = ish.shelvingFk - JOIN parking p ON sh.parkingFk = p.id + FROM vn.itemShelving ish + JOIN shelving sh ON sh.code = ish.shelvingFk + JOIN parking p ON sh.parkingFk = p.id JOIN sector s ON s.id = p.sectorFk - WHERE s.isReserve + WHERE s.isReserve GROUP BY ish.itemFk UNION ALL SELECT item_id, sum(iei.amount), dat @@ -61155,9 +61157,9 @@ BEGIN AND warehouse_id = vWarehouseFk AND isVirtualStock = FALSE GROUP BY item_id, dat - UNION ALL + UNION ALL SELECT item_id, sum(ieo.amount), dat - FROM vn2008.item_entry_out ieo + FROM vn2008.item_entry_out ieo WHERE dat >= util.VN_CURDATE() AND warehouse_id = vWarehouseFk GROUP BY item_id, dat @@ -61168,11 +61170,11 @@ BEGIN WHERE io.dat >= util.VN_CURDATE() AND io.warehouse_id = vWarehouseFk GROUP BY io.item_id, io.dat - ) t2 + ) t2 JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = t2.itemFk) t order by t.itemFk, DATE(t.dated), t.amount DESC) t3; - - SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock + + SELECT sbd.itemFk, i.longName, DATE(dated) dated, ish.visible amount, sbd.stock FROM tmp.stockByDay sbd JOIN vn.item i ON i.id = sbd.itemFk JOIN tmp.itemShelvingDistinct ish ON ish.itemFk = sbd.itemFk @@ -61275,15 +61277,15 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_selfConsumption`( - vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, - vItemFk INT, + vShelvingFk VARCHAR(10) COLLATE utf8_general_ci, + vItemFk INT, vQuantity INT ) -BEGIN +BEGIN /** - * Leave the indicated amount on the shelf + * Leave the indicated amount on the shelf * and create a ticket with the difference. - * + * * @param vShelvingFk id of the shelf where the item is located. * @param vItemFk article of which the self-consumption ticket is to be created. * @param vQuantity amount that will stay on the shelf @@ -61327,10 +61329,10 @@ BEGIN END IF; SELECT SUM(visible), id INTO vVisible, vItemShelvingFk - FROM itemShelving + FROM itemShelving WHERE shelvingFk = vShelvingFk AND itemFk = vItemFk; - + IF vVisible IS NULL THEN CALL util.throw('The item is not on the shelf.'); END IF; @@ -61383,9 +61385,9 @@ BEGIN * @param vGrouping el grouping del producto en itemShelving */ UPDATE itemShelving - SET visible = vVisible, - packing = vPacking, - grouping = vGrouping + SET visible = vVisible, + packing = vPacking, + grouping = vGrouping WHERE id = vShelf; END ;; @@ -61407,7 +61409,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagMake`(vItemFk INT) BEGIN -/* * Crea los tags usando la tabla plantilla itemTag +/* * Crea los tags usando la tabla plantilla itemTag * y si no existe a partir de la ficha del artículo. * @param vItemFk El item al que se le añaden los tags */ @@ -61417,33 +61419,33 @@ BEGIN DECLARE vProducer VARCHAR(50); DECLARE vOrigin VARCHAR(20); DECLARE vTypeFk INTEGER; - - DELETE FROM itemTag + + DELETE FROM itemTag WHERE itemFk = vItemFk; - - SELECT typeFk INTO vTypeFk + + SELECT typeFk INTO vTypeFk FROM item WHERE id = vItemFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT vItemFk, itt.tagFk, NULL, itt.priority FROM itemTag it LEFT JOIN itemTypeTag itt ON itt.itemTypeFk = vTypeFk WHERE it.itemFk = vItemFk; - + IF (SELECT COUNT(*) FROM itemTag WHERE itemFk = vItemFk LIMIT 1) = 0 THEN - SELECT ik.name, i.size, i.category, p.name, o.name + SELECT ik.name, i.size, i.category, p.name, o.name INTO vInk, vSize, vCategory, vProducer, vOrigin FROM item i LEFT JOIN ink ik ON ik.id = i.inkFk LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible LEFT JOIN origin o ON o.id = i.originFk WHERE i.id = vItemFk; - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 1, vInk, 1); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES (vItemFk, 8, vSize, 2); @@ -61452,11 +61454,11 @@ BEGIN INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 37, vProducer, 4); - + INSERT IGNORE INTO itemTag(itemFk, tagFk, value, priority) VALUES(vItemFk, 35, vOrigin, 5); END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61477,12 +61479,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorder`(itemTypeFk INT) BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.typeFk = itemTypeFk; UPDATE itemTag it @@ -61491,8 +61493,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -61517,12 +61519,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTagReorderByName`(vName VARCHAR BEGIN SET @isTriggerDisabled = TRUE; - + -- No se puede usar temporary porque da error Error Code: 1137. No puedo reabrir tabla: 'i DROP TABLE IF EXISTS tmp.item; CREATE TABLE tmp.item SELECT DISTINCT i.id - FROM vn.item i + FROM vn.item i WHERE i.`name` LIKE CONCAT(vName,'%'); UPDATE itemTag it @@ -61531,8 +61533,8 @@ BEGIN JOIN itemTypeTag itt ON itt.itemTypeFk = item.typeFk AND itt.tagFk = it.tagFk SET it.priority = itt.priority WHERE itt.itemTypeFk = itemTypeFk; - - CALL item_refreshTags(); + + CALL item_refreshTags(); SET @isTriggerDisabled = FALSE; @@ -61555,36 +61557,36 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `itemTag_replace`(vItemFromFk INT, vItemToFk INT, vPicture VARCHAR(100)) BEGIN - + /* Reemplaza los tags de un artículo por los de otro, así como su imagen - * + * * @param vItemFromFk id de vn.item con el artículo del que se toman los tags * @param vItemToFk id de vn.item con el artículo del que se toman los tags * @param vPicture imagen del artículo. Opcional. Si no se especifica, hereada la del vItemFromFk */ - DELETE FROM vn.itemTag + DELETE FROM vn.itemTag WHERE itemFk = vItemToFk; - + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) SELECT vItemToFk, tagFk, value, priority - FROM vn.itemTag + FROM vn.itemTag WHERE itemFk = vItemFromFk; - + IF ISNULL(vPicture) THEN - - SELECT image INTO vPicture - FROM vn.item + + SELECT image INTO vPicture + FROM vn.item WHERE id = vItemFromFk; - + END IF; - UPDATE vn.item i + UPDATE vn.item i SET i.image = vPicture WHERE i.id = vItemToFk; - + CALL vn.itemRefreshTags(vItemToFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61609,9 +61611,9 @@ BEGIN SELECT DISTINCT id FROM vn.itemCategory WHERE merchandise <> FALSE; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -61622,45 +61624,45 @@ BEGIN INNER JOIN bs.ventas v ON v.Id_Movimiento = s.id WHERE v.fecha BETWEEN TIMESTAMPADD(DAY, - 7, util.VN_CURDATE()) AND util.VN_CURDATE() GROUP BY s.itemFk; - + DROP TABLE IF EXISTS tmp.topSeller; - CREATE TEMPORARY TABLE tmp.topSeller - ( + CREATE TEMPORARY TABLE tmp.topSeller + ( `id` int(11) NOT NULL DEFAULT '0', `typeFk` smallint(5) unsigned NOT NULL, `itemCategoryFk` int(10) unsigned NOT NULL, `total` bigint(21) NOT NULL DEFAULT '0' ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - + OPEN rs; read_loop: LOOP FETCH rs INTO vCategoryFk; - + IF vDone THEN LEAVE read_loop; END IF; - + INSERT INTO tmp.topSeller SELECT tsm.itemFk, tsm.typeFk, it.categoryFk, tsm.total FROM tmp.topSellerMin tsm INNER JOIN vn.itemType it ON it.id = tsm.typeFk WHERE it.categoryFk = vCategoryFk ORDER BY tsm.itemFk ,tsm.total DESC - LIMIT 5; + LIMIT 5; END LOOP; CLOSE rs; - + SELECT i.name ,i.id, i.image, i.typeFk, it.categoryFk AS itemCategoryFk, ic.name AS itemCategoryName, it.name AS itemTypeName, ts.total FROM tmp.topSeller ts INNER JOIN vn.item i ON i.id = ts.id INNER JOIN vn.itemType it ON it.id = ts.typeFk INNER JOIN vn.itemCategory ic ON ic.id = it.categoryFk; - + DROP TABLE IF EXISTS topSellerMin; DROP TABLE IF EXISTS tmp.topSeller; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -61770,7 +61772,7 @@ SET tag6 = t.name, value6 = it.value WHERE it.priority = 2 AND (vItem IS NULL OR vItem = it.itemFk); -UPDATE item i +UPDATE item i JOIN itemTag it ON it.itemFk = i.id JOIN tag t ON t.id = it.tagFk SET tag7 = t.name, value7 = it.value @@ -61803,7 +61805,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_cleanFloramondo`() BEGIN /** -* Elimina todos los items repetidos de floramondo +* Elimina todos los items repetidos de floramondo * y los sustituye por el que tiene menor id */ DECLARE vItemFrom INT; @@ -61869,7 +61871,7 @@ BEGIN AND i2.EmbalageCode <=> i.EmbalageCode AND i2.quality <=> i.quality JOIN ( - SELECT DISTINCT b.itemFk + SELECT DISTINCT b.itemFk FROM buy b JOIN item i ON i.id = b.itemFk WHERE i.isFloramondo @@ -61877,7 +61879,7 @@ BEGIN )sub2 ON sub2.itemFk = GREATEST(i.id, i2.id) WHERE i.isFloramondo AND i.id <> i2.id; - + DECLARE EXIT HANDLER FOR SQLEXCEPTION SET vDone = TRUE; BEGIN SET vDone = TRUE; @@ -62131,13 +62133,13 @@ BEGIN /** * @vItemFk item a buscar * @vWarehouseFk almacen donde buscar - * @vDate Si la fecha es null, muestra el histórico desde el inventario. + * @vDate Si la fecha es null, muestra el histórico desde el inventario. * Si la fecha no es null, muestra histórico desde la fecha pasada. */ DECLARE vDateInventory DATETIME; IF vDate IS NULL THEN - SELECT inventoried INTO vDateInventory + SELECT inventoried INTO vDateInventory FROM config; ELSE SELECT mockUtcTime INTO vDateInventory @@ -62163,7 +62165,7 @@ BEGIN inventorySupplierFk INT(10) ); - INSERT INTO tItemDiary + INSERT INTO tItemDiary SELECT tr.landed shipped, b.quantity `in`, NULL `out`, @@ -62184,14 +62186,14 @@ BEGIN JOIN entry e ON e.id = b.entryFk JOIN travel tr ON tr.id = e.travelFk JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + JOIN state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() OR (util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', + 'DELIVERED', 'FREE') JOIN entryConfig ec WHERE tr.landed >= vDateInventory AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) AND b.itemFk = vItemFk AND e.isExcludedFromAvailable = FALSE AND e.isRaid = FALSE @@ -62217,14 +62219,14 @@ BEGIN JOIN travel tr ON tr.id = e.travelFk JOIN warehouse w ON w.id = tr.warehouseOutFk JOIN supplier s ON s.id = e.supplierFk - JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() + JOIN state st ON st.`code` = IF(tr.shipped < util.VN_CURDATE() OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), - 'DELIVERED', + 'DELIVERED', 'FREE') JOIN entryConfig ec WHERE tr.shipped >= vDateInventory AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) AND b.itemFk = vItemFk AND e.isExcludedFromAvailable = FALSE AND w.isFeedStock = FALSE @@ -62253,12 +62255,12 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN clientType ct ON ct.id = c.clientTypeFk JOIN state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', + 'DELIVERED', IF (t.shipped > util.dayEnd(util.VN_CURDATE()), 'FREE', IFNULL(ts.code, 'FREE'))) LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' - LEFT JOIN saleTracking stk ON stk.saleFk = s.id + LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id LEFT JOIN claimBeginning cb ON s.id = cb.saleFk WHERE t.shipped >= vDateInventory @@ -62274,7 +62276,7 @@ BEGIN `out` DESC; IF vDate IS NULL THEN - + SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; @@ -62289,9 +62291,9 @@ BEGIN `in` invalue, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0) balance, - @currentLineFk := IF (@shipped < util.VN_CURDATE() + @currentLineFk := IF (@shipped < util.VN_CURDATE() OR (@shipped = util.VN_CURDATE() AND (isPicked OR a.`code` >= 'ON_PREPARATION')), - lineFk, + lineFk, @currentLineFk) lastPreparedLineFk, isTicket, lineFk, @@ -62323,25 +62325,25 @@ BEGIN 0 clientType, 0 claimFk UNION ALL - SELECT shipped, - alertlevel, - stateName, - origin, - reference, - clientFk, - name, `in`, - `out`, - @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), - 0, - isTicket, - lineFk, - isPicked, - clientType, + SELECT shipped, + alertlevel, + stateName, + origin, + reference, + clientFk, + name, `in`, + `out`, + @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), + 0, + isTicket, + lineFk, + isPicked, + clientType, claimFk FROM tItemDiary WHERE shipped >= vDate; END IF; - + DROP TEMPORARY TABLE tItemDiary; END ;; DELIMITER ; @@ -62448,7 +62450,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getLack`(IN vForce BOOLEAN, IN BEGIN /** * Calcula una tabla con el máximo negativo visible para cada producto y almacen - * + * * @param vForce Fuerza el recalculo del stock * @param vDays Numero de dias a considerar **/ @@ -62457,31 +62459,31 @@ BEGIN CALL item_getMinacum(NULL, util.VN_CURDATE(), vDays, NULL); CALL item_getMinETD(); - SELECT i.id itemFk, + SELECT i.id itemFk, i.longName, w.id warehouseFk, - p.`name` producer, + p.`name` producer, i.`size`, i.category, - w.name warehouse, + w.name warehouse, SUM(IFNULL(sub.amount,0)) lack, i.inkFk, - IFNULL(im.timed, util.midnight()) timed - FROM (SELECT item_id, - warehouse_id, + IFNULL(im.timed, util.midnight()) timed + FROM (SELECT item_id, + warehouse_id, amount FROM cache.stock WHERE amount > 0 UNION ALL - SELECT itemFk, - warehouseFk, + SELECT itemFk, + warehouseFk, amount FROM tmp.itemMinacum ) sub JOIN warehouse w ON w.id = sub.warehouse_id JOIN item i ON i.id = sub.item_id - LEFT JOIN producer p ON p.id = i.producerFk - JOIN itemType it ON it.id = i.typeFk + LEFT JOIN producer p ON p.id = i.producerFk + JOIN itemType it ON it.id = i.typeFk JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN tmp.itemMinETD im ON im.itemFk = i.id WHERE w.isForTicket @@ -62602,12 +62604,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getMinETD`() BEGIN - + /* Devuelve una tabla temporal con la primera ETD, para todos los artículos con salida hoy. - * + * * @return tmp.itemMinETD(itemFk, timed) */ - + DECLARE vMidnight DATETIME DEFAULT util.midnight(); DROP TEMPORARY TABLE IF EXISTS tmp.itemMinETD; @@ -62618,7 +62620,7 @@ BEGIN SELECT s.itemFk, MIN(TIME(IFNULL(z.`hour`,vMidnight))) timed FROM ticket t JOIN sale s ON s.ticketFk = t.id - LEFT JOIN `zone` z ON z.id = t.zoneFk + LEFT JOIN `zone` z ON z.id = t.zoneFk WHERE t.shipped BETWEEN util.VN_CURDATE() AND vMidnight GROUP BY s.itemFk; END ;; @@ -62648,33 +62650,33 @@ BEGIN * @param vWarehouseFk warehouse id * @param vDate fecha para revisar disponible * @param vIsShowedByType para mostrar solo artículos de ese tipo - */ + */ DECLARE vCalcFk INT; DECLARE vTypeFk INT; - + DECLARE vTag1 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag5 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag6 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag7 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vTag8 VARCHAR(25) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + DECLARE vValue1 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue5 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue6 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue7 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; DECLARE vValue8 VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'; - + SELECT typeFk, tag5, value5, tag6, value6, tag7, value7, tag8, value8, t1.name, it1.value INTO vTypeFk, vTag5, vValue5, vTag6, vValue6, vTag7, vValue7, vTag8, vValue8, vTag1, vValue1 FROM vn.item i LEFT JOIN vn.itemTag it1 ON it1.itemFk = i.id AND it1.priority = 1 LEFT JOIN vn.tag t1 ON t1.id = it1.tagFk WHERE i.id = vItemFk; - + CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDate); - + SELECT i.id itemFk, i.longName, i.subName, @@ -62707,7 +62709,7 @@ BEGIN ORDER BY counter DESC, (t1.name = vTag1) DESC, (it1.value = vValue1) DESC, - (i.tag6 = vTag6) DESC, + (i.tag6 = vTag6) DESC, (i.value6 = vValue6) DESC, (i.tag5 = vTag5) DESC, (i.value5 = vValue5) DESC, @@ -62716,7 +62718,7 @@ BEGIN (i.tag8 = vTag8) DESC, (i.value8 = vValue8) DESC LIMIT 30; - + END ;; DELIMITER ; @@ -63001,11 +63003,11 @@ BEGIN * @param vBarcode del item * @param vReference referencia a actualizar */ - + DECLARE vItemFk INT; SELECT barcodeToItem(vBarcode) INTO vItemFk; - + UPDATE item SET comment = vReference WHERE id = vItemFk; END ;; @@ -63028,7 +63030,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_setGeneric`(vSelf INT) BEGIN /** * Asigna el código genérico a un item, salvo que sea un código de item genérico. - * + * * @param vSelf identificador de vn.item */ DECLARE vGenericFk INT; @@ -63038,7 +63040,7 @@ BEGIN SELECT itemFk, SUM(matches) = maxMatches `match` FROM ( SELECT ga.id gaid, ga.itemFk, - CASE + CASE WHEN t.code = 'nflowers' THEN it.value <=> ga.numFlores WHEN t.code = 'origin' THEN @@ -63069,13 +63071,13 @@ BEGIN AND (i.`size` = ga.`size` OR ga.`size` IS NULL) AND i.id != ga.itemFk WHERE i.id = vSelf - AND NOT i.isFloramondo) sub + AND NOT i.isFloramondo) sub GROUP BY gaid HAVING `match`) sub2 LIMIT 1; - UPDATE vn.item - SET genericFk = vGenericFk + UPDATE vn.item + SET genericFk = vGenericFk WHERE id = vSelf; END ;; DELIMITER ; @@ -63095,18 +63097,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `item_updatePackingShelve`(vSelf INT, vPacking INT) BEGIN - + /** * Actualiza el valor de item.packingShelve - * + * * @param vSelf Identificador de vn.item * @param vPacking Cantidad de unidades de venta que caben en una bandeja */ - - UPDATE vn.item i + + UPDATE vn.item i SET i.packingShelve = vPacking WHERE i.id = vSelf; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63156,9 +63158,9 @@ BEGIN DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; DECLARE vInventoried2 DATE; DECLARE vDateDayEnd DATETIME; - + SET vDateDayEnd = util.dayEnd(vDated); - + SELECT landed INTO vInventoried FROM travel tr JOIN entry E ON E.travelFk = tr.id @@ -63168,7 +63170,7 @@ BEGIN LIMIT 1; SET vHasNotInventory = IF (vInventoried is null, TRUE, FALSE); - + IF vHasNotInventory THEN SELECT landed INTO vInventoried2 @@ -63189,13 +63191,13 @@ BEGIN CREATE TEMPORARY TABLE inv (warehouseFk SMALLINT, Id_Article BIGINT, - cantidad INT, + cantidad INT, coste DOUBLE DEFAULT 0, total DOUBLE DEFAULT 0, Almacen VARCHAR(20), PRIMARY KEY (Almacen, Id_Article) USING HASH) ENGINE = MEMORY; - + IF vHasNotInventory = TRUE THEN INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -63272,7 +63274,7 @@ BEGIN AND it.isInventory ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + s.quantity * IF(vHasNotInventory,0,1); - END IF; + END IF; -- Mercancia en transito INSERT INTO inv(warehouseFk, Id_Article, cantidad, Almacen) @@ -63290,7 +63292,7 @@ BEGIN AND t.isInventory AND e.isConfirmed ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity); - + CALL vn.buyUltimate(NULL,vDateDayEnd); UPDATE inv i @@ -63305,20 +63307,20 @@ BEGIN IF vIsDetailed THEN SELECT inv.warehouseFk, - i.id itemFk, - i.longName , - i.size, - inv.Cantidad, + i.id itemFk, + i.longName , + i.size, + inv.Cantidad, tp.name Tipo, - ic.name Reino, - inv.coste, + ic.name Reino, + inv.coste, cast(inv.total as decimal(10,2)) total, almacen FROM inv JOIN warehouse w on w.id = warehouseFk JOIN item i ON i.id = inv.Id_Article JOIN itemType tp ON tp.id = i.typeFk - JOIN itemCategory ic ON ic.id = tp.categoryFk + JOIN itemCategory ic ON ic.id = tp.categoryFk WHERE w.valuatedInventory and inv.total > 0 order by inv.total desc; @@ -63365,37 +63367,37 @@ BEGIN * @param vConcept descripcion * @param vAmount cantidad que se compensa * @param vCompany empresa - * @param vOriginalAccount cuenta contable desde la cual se compensa - * - */ + * @param vOriginalAccount cuenta contable desde la cual se compensa + * + */ DECLARE vNewBookEntry INT; DECLARE vIsClientCompensation INT; DECLARE vClientFk INT; DECLARE vSupplierFk INT; DECLARE vIsOriginalAClient BOOL; DECLARE vPayMethodCompensation INT; - + CALL ledger_next(vNewBookEntry); SELECT COUNT(id) INTO vIsOriginalAClient FROM client WHERE accountingAccount LIKE vOriginalAccount COLLATE utf8_general_ci; - SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation - FROM client + SELECT id, COUNT(id) INTO vClientFk, vIsClientCompensation + FROM client WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci; - + SET @vAmount1:= 0.0; SET @vAmount2:= 0.0; - INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) - VALUES ( vNewBookEntry, - vDated, - vOriginalAccount, - vCompensationAccount, - vConcept, + INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) + VALUES ( vNewBookEntry, + vDated, + vOriginalAccount, + vCompensationAccount, + vConcept, @vAmount1:= IF( - (vIsOriginalAClient AND vAmount > 0) OR - (NOT vIsOriginalAClient AND vAmount < 0), - 0, + (vIsOriginalAClient AND vAmount > 0) OR + (NOT vIsOriginalAClient AND vAmount < 0), + 0, ABS(vAmount) ), @vAmount2:= IF(@vAmount1, @@ -63404,20 +63406,20 @@ BEGIN ), vCompanyFk ), - ( vNewBookEntry, - vDated, - vCompensationAccount, - vOriginalAccount, - vConcept, + ( vNewBookEntry, + vDated, + vCompensationAccount, + vOriginalAccount, + vConcept, @vAmount2, @vAmount1, vCompanyFk); - + IF vIsClientCompensation THEN IF vIsOriginalAClient THEN SET vAmount = -vAmount; END IF; - INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) + INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientFk, TRUE); ELSE IF NOT vIsOriginalAClient THEN @@ -63425,7 +63427,7 @@ BEGIN END IF; SELECT id INTO vSupplierFk FROM supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation'; - + INSERT INTO payment (received, dueDated, supplierFk, amount, bankFk, payMethodFk, concept, companyFk, isConciliated) VALUES(vDated, vDated, vSupplierFk, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE); END IF; @@ -63447,10 +63449,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ledger_next`(OUT vNewBookEntry INT) BEGIN - + UPDATE vn.ledgerConfig SET lastBookEntry = LAST_INSERT_ID(lastBookEntry + 1); SET vNewBookEntry = LAST_INSERT_ID(); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63476,15 +63478,15 @@ BEGIN * @param vEntity Nombre que hace referencia a la tabla. */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vEntity, 'Log'); - + SET @qryLog := CONCAT( 'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot', ' INNER JOIN account.user u ON u.id = ot.userFk', ' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; END ;; @@ -63509,9 +63511,9 @@ BEGIN SET @buildingOrder := 0; SET @route := 0; set @cajas := 0; - + UPDATE tmp.sorter - SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 + SET buildingOrder = @buildingOrder := IF(@route = @route := routeFk, @buildingOrder, 0) + 1 where date(created) = vDate order by routeFk, created, weight DESC; @@ -63529,23 +63531,23 @@ set @cajas := 0; UPDATE tmp.sorter SET lungGrow = IF(palletOrder = 0, -13, lungGrow); - + DELETE FROM tmp.lungSize WHERE dia = vDate; - + INSERT INTO tmp.lungSize(dia, hora,size) select vDate,hora, @cajas := @cajas + cajas as size from ( select IF(lungGrow BETWEEN -12 AND -1, ETD,time_format(created,"%H:%i")) as hora, sum(if(lungGrow <= 0, lungGrow, 1)) as cajas, @cajas := 0 - from tmp.sorter + from tmp.sorter where date(created) = vDate group by hora ) sub; - + SELECT * FROM tmp.lungSize WHERE dia = vDate; - - + + END ;; @@ -63566,23 +63568,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_add`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** * Inserta registro si el vWorkerFk no ha registrado nada en las últimas 12 horas * @param vPlate número de matrícula - * @param vWorkerFk id del worker - * -*/ - UPDATE vn.machineWorker mw - JOIN vn.machine m ON m.id = mw.machineFk + * @param vWorkerFk id del worker + * +*/ + UPDATE vn.machineWorker mw + JOIN vn.machine m ON m.id = mw.machineFk SET mw.outTimed = util.VN_NOW() WHERE (mw.workerFk = vWorkerFk OR m.plate = vPlate) AND ISNULL(mw.outTimed); - + INSERT INTO machineWorker (machineFk, workerFk) SELECT m.id, vWorkerFk FROM machine m - WHERE m.plate= vPlate; + WHERE m.plate= vPlate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63602,21 +63604,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_getHistorical`(vPlate VARCHAR(20), vWorkerFk INT) BEGIN /** - * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, + * Obtiene historial de la matrícula vPlate que el trabajador vWorkerFk escanea, * si es jefe de producción muestra el historial completo. - * + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vWorkerName VARCHAR(255) DEFAULT account.user_getNameFromId(vWorkerFk); - SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed + SELECT mw.inTimed,account.user_getNameFromId(mw.workerFk) as workerName, mw.outTimed FROM machineWorker mw JOIN machine m ON m.plate = vPlate WHERE mw.machineFk = m.id AND mw.workerFk = IF(account.user_hasRole(vWorkerName, 'coolerAssist'), mw.workerFk, vWorkerFk) - ORDER BY mw.inTimed DESC; + ORDER BY mw.inTimed DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63635,13 +63637,13 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `machineWorker_update`(vPlate VARCHAR(10), vWorkerFk INT) BEGIN - + /** - * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, - * + * Actualiza el registro correspondiente si el vWorkerFk se ha registrado en las últimas horas (campo maxHours de machineWorkerConfig) con vPlate, + * * @param vPlate número de matrícula - * @param vWorkerFk id del trabajador - * + * @param vWorkerFk id del trabajador + * */ DECLARE vMachineFk INT(10); @@ -63650,24 +63652,24 @@ BEGIN SELECT m.id INTO vMachineFk FROM machine m WHERE m.plate = vPlate; - + SELECT maxHours INTO vMaxHours FROM machineWorkerConfig; - IF (SELECT COUNT(*) + IF (SELECT COUNT(*) FROM machineWorker m WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN - + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed)) THEN + UPDATE machineWorker m SET m.outTimed = CURRENT_TIMESTAMP() - WHERE m.workerFk = vWorkerFk - AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) + WHERE m.workerFk = vWorkerFk + AND m.inTimed >= TIMESTAMPADD(HOUR , -vMaxHours, util.VN_NOW()) AND ISNULL(m.outTimed) AND m.machineFk = vMachineFk; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63722,12 +63724,12 @@ BEGIN /** * Inserta en la tabla vn.mail * - * @param vReceiver Receptor del correo + * @param vReceiver Receptor del correo * @param vReplyTo A quién contestar el correo * @param vSubject Título del correo * @param vBody Cuerpo del correo */ - + DECLARE vIsRepeated BOOLEAN; SELECT COUNT(*) INTO vIsRepeated @@ -63768,12 +63770,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `makeNewItem`() BEGIN DECLARE newItemFk INT; - + SELECT getNewItemId() INTO newItemFk; - + INSERT INTO item(id,name,typeFk,originFk) SELECT newItemFk, 'Nuevo artículo', 78,39; - + SELECT newItemFk; @@ -63801,34 +63803,34 @@ BEGIN DECLARE vMinute INT DEFAULT 0; DECLARE vBoxes INT; - + DROP TEMPORARY TABLE IF EXISTS vn.pcsDay; CREATE TEMPORARY TABLE vn.pcsDay SELECT 0 as hh, 0 as mm, 0 as boxes; - + -- Creamos una tabla soporte para acumular las cajas a lo largo del dia WHILE vHour < 24 DO - + WHILE vMinute < 59 DO - + SET vMinute = vMinute + 1; - + INSERT INTO vn.pcsDay(hh,mm) VALUES(vHour, vMinute); - + END WHILE; - + SET vMinute = -1; SET vHour = vHour + 1; - + END WHILE; - + -- Acumulamos UPDATE vn.pcsDay pd LEFT JOIN (SELECT * FROM vn.pcs_graf WHERE dia = vDated) pg USING(hh,mm) SET pd.boxes = pd.boxes + pg.box; - + SELECT * FROM vn.pcsDay; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -63851,7 +63853,7 @@ BEGIN * Recalcula el mana consumido por un trabajador * * @param vWorkerFk Id Trabajador - */ + */ DECLARE vWorkerIsExcluded BOOLEAN; DECLARE vFromDated DATE; DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,util.VN_CURDATE()); @@ -63860,32 +63862,32 @@ BEGIN DECLARE vClaimMana INT; DECLARE vManaBank INT; DECLARE vManaGreugeType INT; - + SELECT COUNT(*) INTO vWorkerIsExcluded FROM workerManaExcluded WHERE workerFk = vWorkerFk; - + IF NOT vWorkerIsExcluded THEN - SELECT id INTO vMana + SELECT id INTO vMana FROM `component` WHERE code = 'mana'; - - SELECT id INTO vAutoMana + + SELECT id INTO vAutoMana FROM `component` WHERE code = 'autoMana'; - - SELECT id INTO vClaimMana + + SELECT id INTO vClaimMana FROM `component` WHERE code = 'manaClaim'; - - SELECT id INTO vManaBank + + SELECT id INTO vManaBank FROM `bank` WHERE code = 'mana'; - - SELECT id INTO vManaGreugeType + + SELECT id INTO vManaGreugeType FROM `greugeType` WHERE code = 'mana'; - SELECT max(dated) INTO vFromDated + SELECT max(dated) INTO vFromDated FROM clientManaCache; - + REPLACE workerMana (workerFk, amount) - SELECT vWorkerFk, sum(mana) FROM + SELECT vWorkerFk, sum(mana) FROM ( SELECT s.quantity * sc.value as mana FROM ticket t @@ -63906,8 +63908,8 @@ BEGIN FROM greuge g JOIN client c ON c.id = g.clientFk WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() - UNION ALL + AND g.shipped > vFromDated and g.shipped < util.VN_CURDATE() + UNION ALL SELECT cc.mana FROM clientManaCache cc JOIN client c ON c.id = cc.clientFk @@ -63934,20 +63936,20 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlConnectionsSorter_kill`() BEGIN /** - * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre - */ - + * Elimina conexiones del usuario sorter con tiempo >= 30seg. Asociado al evento con el mismo nombre + */ + DECLARE vDone INT DEFAULT 0; DECLARE vProcesId INT; DECLARE vCursor CURSOR FOR - SELECT p.id + SELECT p.id FROM information_schema.processlist p - WHERE USER = 'sorter' + WHERE USER = 'sorter' AND TIME >= 30; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + OPEN vCursor; l: LOOP @@ -63984,7 +63986,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `mysqlPreparedCount_check`() BEGIN DECLARE vPreparedCount INTEGER; - SELECT VARIABLE_VALUE INTO vPreparedCount + SELECT VARIABLE_VALUE INTO vPreparedCount FROM INFORMATION_SCHEMA.GLOBAL_STATUS WHERE VARIABLE_NAME LIKE '%prepared_stmt_count%'; @@ -63992,7 +63994,7 @@ BEGIN CALL `vn`.`mail_insert`('cau@verdnatura.es', NULL, 'Problemas BBDD prepared_stmt_count', - CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', + CONCAT('Existen problemas con el servicio de Logiflora, prepared_stmt_count con valor: ', vPreparedCount, ', está próximo a exceder su límite. \r\n Hay que reiniciar el servicio LF.VMP.Service del servidor a3.') ); @@ -64019,37 +64021,37 @@ BEGIN DECLARE newShelving VARCHAR(3); DECLARE vCode VARCHAR(3); - + SELECT MAX(code) INTO vCode FROM vn.shelving WHERE isPrinted = FALSE; - + SET @a1 := ASCII(MID(vCode,1,1)); SET @a2 := ASCII(MID(vCode,2,1)); SET @a3 := ASCII(MID(vCode,3,1)) + 1; - + IF @a3 > 90 THEN - + SET @a3 = 65; SET @a2 = @a2 + 1; - + IF @a2 > 90 THEN - + SET @a2 = 65; SET @a1 = @a1 + 1; - + IF @a1 > 90 THEN - + SET @a1 = 65; - + END IF; - + END IF; - + END IF; SET newShelving = CHAR(@a1,@a2,@a3 USING utf8); - + INSERT INTO vn.shelving(code) VALUES(newShelving); END ;; @@ -64078,18 +64080,18 @@ BEGIN * @param descripcion Texto de la observacion */ DECLARE vTableName VARCHAR(45); - + SET vTableName = CONCAT(vTableCode,'Observation'); - + IF ISNULL(vTableName) THEN CALL util.throw('CODE_NOT_FOUND'); END IF; - + SET @qryLog := CONCAT( 'INSERT INTO ', vTableName, ' (originFk, userFk, description)', ' VALUES (', vOriginFk, ', ', account.myUser_getId(), ', "', vDescription, '")' ); - + PREPARE stmt FROM @qryLog; EXECUTE stmt; DEALLOCATE PREPARE stmt; @@ -64119,15 +64121,15 @@ BEGIN DECLARE vDeliveryMethod INT; DECLARE vClient INT; - + SELECT deliveryMethodFk INTO vDeliveryMethod - FROM vn.agencyMode + FROM vn.agencyMode WHERE id = vAgencyMode; - + SELECT clientFk INTO vClient FROM vn.address WHERE id = vAddress; - + INSERT INTO hedera.order(date_send,customer_id,delivery_method_id,agency_id,address_id,source_app) VALUES( vLanded,vClient ,vDeliveryMethod,vAgencyMode ,vAddress ,vSourceApp); @@ -64153,7 +64155,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `orderDelete`(IN vId INT) BEGIN DELETE FROM hedera.`order` where id = vId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64180,7 +64182,7 @@ BEGIN DECLARE vOrderId INT; CALL vn.orderCreate(vLanded,vAgencyMode,vAddress,vSourceApp,vOrderId); SELECT vOrderId; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64200,7 +64202,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `orderListVolume`(IN vOrderId INT) BEGIN - SELECT + SELECT o.id, o.itemFk, i.description, @@ -64226,7 +64228,7 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( +CREATE DEFINER=`root`@`localhost` PROCEDURE `packageInvoicing`( IN vClient INT, IN vDate DATE, IN vCompany INT, @@ -64245,20 +64247,20 @@ BEGIN SET vGraceDays = IF(vIsAllInvoiceable ,0, 30); SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate); - - /* Clientes especiales: + + /* Clientes especiales: 3240 MADEFLOR 992 JAVIER FELIU 4 TONI VENDRELL */ - + IF vClient IN (992, 3240, 4) THEN - + SET vGraceDays = 365; - + END IF; /* Fin clientes especiales */ - + SET vDateEnd = DATE_ADD(vDate, INTERVAL 1 DAY); DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice; @@ -64282,22 +64284,22 @@ BEGIN FROM tmp.packageToInvoice GROUP BY itemFk HAVING totalQuantity > 0; - + SELECT COUNT(*) INTO vIsInvoiceable FROM tmp.packageToInvoicePositives; IF vIsInvoiceable THEN - CALL ticket_add(vClient, + CALL ticket_add(vClient, vDateEnd, - vWarehouse, - vCompany, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouse, + vCompany, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); @@ -64306,44 +64308,44 @@ BEGIN packagingFk, quantity, pvp) - SELECT vNewTicket, - pti.packagingFk, - - SUM(pti.quantity) AS totalQuantity, + SELECT vNewTicket, + pti.packagingFk, + - SUM(pti.quantity) AS totalQuantity, pti.price FROM tmp.packageToInvoice pti - LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY packagingFk HAVING totalQuantity; INSERT INTO sale( ticketFk, - itemFk, - concept, - quantity, + itemFk, + concept, + quantity, price ) - SELECT vNewTicket, - pti.itemFk, - i.name as concept, - sum(pti.quantity) as totalQuantity, + SELECT vNewTicket, + pti.itemFk, + i.name as concept, + sum(pti.quantity) as totalQuantity, pti.price FROM tmp.packageToInvoice pti JOIN item i ON i.id = pti.itemFk LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk - WHERE ptip.itemFK IS NOT NULL + WHERE ptip.itemFK IS NOT NULL OR vIsAllInvoiceable GROUP BY pti.itemFk HAVING totalQuantity; - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64369,7 +64371,7 @@ BEGIN WHERE mm.valor = 1 -- Listo para imprimir AND mm.stateFk = 9 -- Encajando AND m.Id_Ticket = ticketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64391,15 +64393,15 @@ BEGIN DECLARE valueFk INT; DECLARE encajando INT DEFAULT 9; - - SELECT valor INTO valueFk - FROM vn2008.Movimientos_mark - WHERE Id_Movimiento = saleFk + + SELECT valor INTO valueFk + FROM vn2008.Movimientos_mark + WHERE Id_Movimiento = saleFk AND stateFk = encajando; - + SET valueFk = (IFNULL(valueFk,0) + 1) MOD 3; - - REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) + + REPLACE vn2008.Movimientos_mark(Id_Movimiento, valor, Id_Trabajador, stateFk) VALUES(saleFk,valueFk,account.myUser_getId(),encajando); @@ -64491,34 +64493,34 @@ BEGIN DECLARE vLetters VARCHAR(26) DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; DECLARE vMaxId INT; DECLARE vCode VARCHAR(8); - + SET vColumn = vFromColumn; SET vRow = vFromRow; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + SELECT MAX(id) INTO vMaxId FROM vn.parking; WHILE vColumn <= vToColumn DO - + WHILE vRow <= vToRow DO - + INSERT IGNORE INTO vn.parking(`column`, `row`, sectorFk, `code`, pickingOrder) VALUES (vColumn, vRow, vSectorFk, vCode, vColumn * 100 + vRow ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET vRow = vRow + 1; SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SET vRow = vFromRow; SET vColumn = vColumn + 1; - + SET vCode = CONCAT(LPAD(vColumn,3,'0'),'-',IF(vIsLetterMode, MID(vLetters, vRow, 1), LPAD(vRow, 2,'0'))); - + END WHILE; - + SELECT * FROM vn.parking WHERE `column` BETWEEN vFromColumn AND vToColumn; END ;; @@ -64543,59 +64545,59 @@ BEGIN DECLARE vRow INT; DECLARE vCode VARCHAR(8); DECLARE i INT; - + IF vToRow < vFromRow THEN - + SET vRow = vFromRow; - + WHILE vRow >= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10)) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow - 1; - + END WHILE; ELSE - + SET vRow = vFromRow; - + WHILE vRow <= vToRow DO - + SET i = 1; - + WHILE i <= vTrolleysByLine DO - + SET vCode = CONCAT(vLetter,'-', LPAD(vRow,2,'0'),'-', i); - + INSERT IGNORE INTO vn.parking( sectorFk, `code`, pickingOrder) VALUES (vSectorFk, vCode, vPickingOrder + (i * 10) ) ON DUPLICATE KEY UPDATE `code` = vCode; - + SET i = i + 1; - + END WHILE; - + SET vRow = vRow + 1; - + END WHILE; - - + + END IF; - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64619,28 +64621,28 @@ BEGIN DECLARE vColumn INT; DECLARE vLetters VARCHAR(200); DECLARE vLettersLength INT; - + SET vColumn = vStart; SET vRow = 1; SET vLetters = 'ABCDEF'; SET vLettersLength = LENGTH(vLetters); - + WHILE vColumn <= vEnd DO - + REPLACE vn.parking(`column`, `row`, `code`, sectorFk) VALUES(vColumn, vRow, CONCAT(vColumn,MID(vLetters,vRow,1)), vSectorFk); - + SET vRow = vRow + 1; - + IF vRow > vLettersLength THEN - + SET vRow = 1; SET vColumn = vColumn + 1; - + END IF; - + END WHILE; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64659,11 +64661,11 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `parking_setOrder`(vWarehouseFk INT) BEGIN - + /* * Ordena el orden de preparacion de los parking de acuerdo con la tabla vn.corridor */ - + UPDATE vn.parking p JOIN ( SELECT code, @@ -64672,15 +64674,15 @@ BEGIN SELECT c.prepOrder, p.code, @orden := 0, - IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , - CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication + IF(c.isAscendent, 1,-1) * CAST(SUBSTRING(p.code,3,2) AS DECIMAL(2,0)) subCorridor , + CAST(IF(LENGTH(p.code) > 5, SUBSTRING(p.code,6,2), 0) AS DECIMAL(2,0)) ubication FROM vn.parking p - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.sector s ON s.id = p.sectorFk JOIN vn.corridor c ON c.code = LEFT(p.code,1) COLLATE utf8_general_ci - WHERE s.warehouseFk = vWarehouseFk) sub - ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code + WHERE s.warehouseFk = vWarehouseFk) sub + ORDER BY sub.prepOrder, subCorridor, ubication) sub2 ON sub2.code = p.code SET p.pickingOrder = sub2.po; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64699,17 +64701,17 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `prepareClientList`() BEGIN - + /* * Require la tabla tmp.ticket(id,clientFk) */ - + DROP TEMPORARY TABLE IF EXISTS tmp.client; CREATE TEMPORARY TABLE tmp.client (PRIMARY KEY (id)) ENGINE = MEMORY SELECT DISTINCT clientFk id - FROM tmp.ticket; + FROM tmp.ticket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64837,14 +64839,14 @@ BEGIN /** * Comprueba si la impresora pertenece al sector * - * @param vLabelerFk id de la impresora + * @param vLabelerFk id de la impresora * @param vSector sector a comprobar */ DECLARE isPrinterInNewSector BOOL; IF vLabelerFk IS NOT NULL THEN SELECT COUNT(sectorFK) INTO isPrinterInNewSector - FROM vn.printer p + FROM vn.printer p WHERE id = vLabelerFk AND sectorFk = vSector; IF !isPrinterInNewSector THEN @@ -64868,7 +64870,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -64969,7 +64971,7 @@ proc: BEGIN LEFT JOIN parking pk ON pk.id = tp.parkingFk WHERE t.warehouseFk = vWarehouseFk AND dm.code IN ('AGENCY', 'DELIVERY', 'PICKUP'); - + UPDATE tmp.productionBuffer pb JOIN ( SELECT pb.ticketFk, GROUP_CONCAT(p.code) previaParking @@ -64977,12 +64979,12 @@ proc: BEGIN JOIN sale s ON s.ticketFk = pb.ticketFk JOIN saleGroupDetail sgd ON sgd.saleFk = s.id JOIN saleGroup sg ON sg.id = sgd.saleGroupFk - JOIN parking p ON p.id = sg.parkingFk + JOIN parking p ON p.id = sg.parkingFk GROUP BY pb.ticketFk ) t ON t.ticketFk = pb.ticketFk SET pb.previaParking = t.previaParking; - -- Problemas por ticket + -- Problemas por ticket ALTER TABLE tmp.productionBuffer CHANGE COLUMN `problem` `problem` VARCHAR(255), ADD COLUMN `collectionH` INT, @@ -65263,7 +65265,7 @@ BEGIN `yearMonth` INT ) ENGINE = MEMORY; - + WHILE vDated <= vEnded DO INSERT INTO tmp.rangeDate SET `dated` = vDated, @@ -65273,7 +65275,7 @@ BEGIN `day` = DAY(vDated), `week` = WEEK(vDated, 1), `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); END WHILE; END ;; @@ -65362,7 +65364,7 @@ BEGIN CALL cache.available_refresh(vCalc, FALSE, vWarehouseFk, vDate); DROP TEMPORARY TABLE IF EXISTS tmp.recipeCook; - + CREATE TEMPORARY TABLE tmp.recipeCook SELECT *, @counter := IF(@element = element COLLATE utf8_general_ci , @counter + 1, 1) as counter, @@ -65380,22 +65382,22 @@ BEGIN IFNULL((i.inkFk = r.inkFk ) ,0) + IFNULL((i.size = r.size) ,0) + IFNULL((i.name LIKE CONCAT('%',r.name,'%')) ,0) - + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + + IFNULL((i.longName LIKE CONCAT('%',r.longName,'%')),0) + IFNULL((i.typeFk = r.typeFk),0) as matches, i.typeFk, rl.previousSelected - FROM vn.recipe r + FROM vn.recipe r JOIN vn.item i ON (IFNULL(i.name LIKE CONCAT('%',r.name,'%'), 0) OR IFNULL(i.longName LIKE CONCAT('%',r.longName,'%'),0)) OR i.typeFk <=> r.typeFk JOIN cache.available a ON a.item_id = i.id AND a.calc_id = vCalc LEFT JOIN (SELECT recipe_ItemFk, element as log_element, selected_ItemFk, count(*) as previousSelected FROM vn.recipe_log - GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk + GROUP BY recipe_ItemFk, element, selected_ItemFk) rl ON rl.recipe_ItemFk = r.itemFk AND rl.log_element = r.element AND rl.selected_ItemFk = i.id WHERE r.itemFk = vItemFk - AND a.available > vBunchesQuantity * r.quantity + AND a.available > vBunchesQuantity * r.quantity UNION ALL SELECT 100 itemFk, CONCAT('? ',r.element,' ',IFNULL(r.size,''),' ',IFNULL(r.inkFk,'')) as longName, @@ -65412,15 +65414,15 @@ BEGIN WHERE r.itemFk = vItemFk GROUP BY r.element ) sub - + ORDER BY element, matches DESC, previousSelected DESC; - - SELECT * + + SELECT * FROM tmp.recipeCook WHERE counter < 6 - OR itemFk = 100 + OR itemFk = 100 ; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65445,71 +65447,71 @@ BEGIN DECLARE vShipped DATE; DECLARE vEntryFk INT; DECLARE vTravelFk INT; - + CALL cache.last_buy_refresh(FALSE); - - SELECT warehouseFk, shipped + + SELECT warehouseFk, shipped INTO vWarehouseFk, vShipped - FROM vn.ticket + FROM vn.ticket WHERE id = vTicketFk; UPDATE vn.ticket t JOIN vn.item i ON i.id = vItemFk SET t.nickname = CONCAT(vQuantity,' ',i.longName) WHERE t.id = vTicketFk; - + SELECT b.buyingValue INTO vLastCost FROM vn.buy b JOIN cache.last_buy lb ON lb.buy_id = b.id WHERE lb.item_id = vItemFk ORDER BY (lb.warehouse_id = vWarehouseFk) DESC LIMIT 1; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price) SELECT vTicketFk, 98, - vQuantity, i.longName, vLastCost FROM vn.item i WHERE i.id = vItemFk; - /* + /* SELECT tr.id INTO vTravelFk FROM vn.travel tr JOIN vn.warehouse w ON w.id = tr.warehouseOutFk WHERE tr.warehouseInFk = vWarehouseFk AND tr.landed = vShipped AND w.name = 'Confeccion'; - + IF IFNULL(vTravelFk,0) = 0 THEN - + INSERT INTO vn.travel(shipped, landed, warehouseInFk, warehouseOutFk, agencyFk) SELECT vShipped, vShipped, vWarehouseFk, w.id, am.id - FROM vn.warehouse w - JOIN vn.agencyMode am + FROM vn.warehouse w + JOIN vn.agencyMode am WHERE w.name = 'Confeccion' AND am.name = 'DIRECTO PROVEEDOR'; - + SET vTravelFk = LAST_INSERT_ID(); - - END IF; - + + END IF; + SELECT e.id INTO vEntryFk FROM vn.entry e JOIN vn.supplier s ON s.id = supplierFk WHERE e.travelFk = vTravelFk AND s.name = 'Confeccion Natural' AND e.isRaid = FALSE; - + IF IFNULL(vEntryFk,0) = 0 THEN - + INSERT INTO vn.entry(supplierFk, evaNotes, travelFk, companyFk) SELECT s.id, t.nickname, vTravelFk, c.id FROM vn.supplier s JOIN vn.ticket t ON t.id = vTicketFk - JOIN vn.company c ON c.code = 'VNL' + JOIN vn.company c ON c.code = 'VNL' WHERE s.name = 'Confeccion Natural'; - + SET vEntryFk = LAST_INSERT_ID(); - + END IF; - + INSERT INTO vn.buy(entryFk, itemFk, quantity, buyingValue, packageFk, packing, grouping) SELECT vEntryFk, b.itemFk, vQuantity, b.buyingValue, b.packageFk, b.packing, b.grouping FROM cache.last_buy lb @@ -65611,7 +65613,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `report_print`( ) BEGIN /** - * Inserts in the print queue the report to be printed and the necessary parameters for this + * Inserts in the print queue the report to be printed and the necessary parameters for this * one taking into account the paper size of both the printer and the report. * * @param vReportName the report to be printed. @@ -65654,11 +65656,11 @@ BEGIN END IF; IF vReportFk IS NULL THEN - CALL util.throw('reportNotExists'); + CALL util.throw('reportNotExists'); END IF; IF vReportSize <> vPrinteSize THEN - CALL util.throw('incorrectSize'); + CALL util.throw('incorrectSize'); END IF; START TRANSACTION; @@ -65667,7 +65669,7 @@ BEGIN priorityFk = vPriorityFk, reportFk = vReportFk, workerFk = vUserFk; - + SET vPrintQueueFk = LAST_INSERT_ID(); WHILE vI < vLength DO @@ -65700,16 +65702,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `riskAllClients`(maxRiskDate DATE) BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY SELECT id Id_Cliente, null grade FROM vn.client; - + CALL vn2008.risk_vs_client_list(maxRiskDate); - - SELECT + + SELECT c.RazonSocial, c.Id_Cliente, c.Credito, @@ -65721,7 +65723,7 @@ BEGIN JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente GROUP BY c.Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -65780,25 +65782,25 @@ BEGIN DECLARE vM3 INT; DECLARE vKg INT; DECLARE vMatricula varchar(50); - + SELECT sum(packages) as bultos INTO vPackages - FROM vn.ticket t + FROM vn.ticket t WHERE routeFk = vRouteFk; - + SELECT SUM(sv.physicalVolume), SUM(sv.physicalWeight) INTO vM3, vKg FROM vn.saleVolume sv WHERE sv.routeFk = vRouteFk; - + SELECT v.numberPlate as matricula INTO vMatricula - FROM vn.route r + FROM vn.route r JOIN vn.vehicle v ON r.vehicleFk = v.id WHERE r.id = vRouteFk; - + SELECT vRouteFk as Ruta, - vPackages as Bultos, + vPackages as Bultos, vM3 as m3, vKg as Kg, vMatricula as Matricula; @@ -65863,7 +65865,7 @@ BEGIN ) sub ON sub.routeFk = rm.routeFk SET rm.ticketFree = sub.ticketFree; - UPDATE routesMonitor rm + UPDATE routesMonitor rm JOIN( SELECT t.routeFk, COUNT(*) AS ticketPacked FROM vn.ticket t @@ -65949,11 +65951,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `routeSetOk`( vRouteFk INT) BEGIN - + UPDATE vn.route r SET r.isOk = 1 WHERE r.id = vRouteFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66018,17 +66020,17 @@ proc: BEGIN IF vIsFreelance THEN INSERT INTO routeCommission ( - routeFk, - workCenterFk, - freelanceYearlyM3, - cat4m3, + routeFk, + workCenterFk, + freelanceYearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, rc.freelanceM3 * IF( - IFNULL(r.m3, 0) >= rc.freelanceMinM3, - IFNULL(r.m3, 0), + IFNULL(r.m3, 0) >= rc.freelanceMinM3, + IFNULL(r.m3, 0), 0), rc.distributionCat4M3 * IFNULL(r.m3, 0), rc.distributionCat5M3 * IFNULL(r.m3, 0) @@ -66040,20 +66042,20 @@ proc: BEGIN AND r.commissionWorkCenterFk; ELSE INSERT INTO routeCommission ( - routeFk, - workCenterFk, - km, - m3, - yearlyKm, - yearlyM3, - cat4m3, + routeFk, + workCenterFk, + km, + m3, + yearlyKm, + yearlyM3, + cat4m3, cat5m3 ) SELECT vSelf, r.commissionWorkCenterFk, - (r.kmEnd - r.kmStart) * + (r.kmEnd - r.kmStart) * IF(v.isKmTruckRate, rc.kmHeavy, rc.kmLight), - IFNULL(r.m3, 0) * + IFNULL(r.m3, 0) * IF(v.isKmTruckRate, rc.deliveryM3Cat5, rc.deliveryM3Cat4), (r.kmEnd - r.kmStart) * rc.kmYearly, IFNULL(r.m3, 0) * rc.m3Yearly, @@ -66090,7 +66092,7 @@ proc: BEGIN /** * Recalculates modified route. */ - + DECLARE vDone BOOL; DECLARE vRouteFk INT; @@ -66099,7 +66101,7 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN DO RELEASE_LOCK('vn.route_doRecalc'); @@ -66257,27 +66259,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleBuy_Add`(vSaleFk INT, vBuyFk INT) BEGIN - + /* Añade un registro a la tabla saleBuy en el caso de que sea posible mantener la trazabilidad - * + * * @param vSaleFk clave primaria de vn.sale * @param vBuyFk clave primaria de vn.buy */ - /*IF (SELECT COUNT(*) + /*IF (SELECT COUNT(*) FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk WHERE s.id = vSaleFk AND ic.code = 'fruit') THEN */ - - IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN - + + IF (SELECT COUNT(*) FROM vn.buy WHERE id = vBuyFk AND itemOriginalFk) THEN + INSERT INTO vn.saleBuy (saleFk, buyFk) VALUES(vSaleFk, vBuyFk); - + END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66301,7 +66303,7 @@ BEGIN * * @param vSectorFk Identificador de vn.sector */ - INSERT INTO vn.saleGroup(userFk, sectorFk) + INSERT INTO vn.saleGroup(userFk, sectorFk) VALUES (account.myUser_getId(), vSectorFk); SELECT LAST_INSERT_ID(); @@ -66433,41 +66435,41 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sales_merge`(vTicketFk INT) -BEGIN - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve - SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity - FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND it.isMergeable - GROUP BY s.itemFk, s.price, s.discount; - - START TRANSACTION; - - UPDATE sale s - JOIN tSalesToPreserve stp ON stp.id = s.id - SET quantity = newQuantity - WHERE s.ticketFk = vTicketFk; - - DELETE s.* - FROM sale s - LEFT JOIN tSalesToPreserve stp ON stp.id = s.id - JOIN item i ON i.id = s.itemFk - JOIN itemType it ON it.id = i.typeFk - WHERE s.ticketFk = vTicketFk - AND stp.id IS NULL - AND it.isMergeable; - - COMMIT; - - DROP TEMPORARY TABLE tSalesToPreserve; +BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + CREATE OR REPLACE TEMPORARY TABLE tSalesToPreserve + SELECT s.id, s.itemFk, SUM(s.quantity) newQuantity + FROM sale s + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND it.isMergeable + GROUP BY s.itemFk, s.price, s.discount; + + START TRANSACTION; + + UPDATE sale s + JOIN tSalesToPreserve stp ON stp.id = s.id + SET quantity = newQuantity + WHERE s.ticketFk = vTicketFk; + + DELETE s.* + FROM sale s + LEFT JOIN tSalesToPreserve stp ON stp.id = s.id + JOIN item i ON i.id = s.itemFk + JOIN itemType it ON it.id = i.typeFk + WHERE s.ticketFk = vTicketFk + AND stp.id IS NULL + AND it.isMergeable; + + COMMIT; + + DROP TEMPORARY TABLE tSalesToPreserve; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66502,17 +66504,17 @@ BEGIN OPEN cCur; myLoop: LOOP - + SET vDone = FALSE; - + FETCH cCur INTO vTicketFk; IF vDone THEN LEAVE myLoop; END IF; - + CALL vn.sales_merge(vTicketFk); - + END LOOP; CLOSE cCur; @@ -66643,9 +66645,9 @@ BEGIN DELETE st.* FROM vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk - WHERE st.saleFk = vSaleFk + WHERE st.saleFk = vSaleFk AND s.code = vState COLLATE utf8_unicode_ci; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66662,12 +66664,12 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( - vSaleFK INT, - vIsChecked BOOLEAN, - vOriginalQuantity INT, - vWorkerFk INT, - vAction VARCHAR(50), +CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_new`( + vSaleFK INT, + vIsChecked BOOLEAN, + vOriginalQuantity INT, + vWorkerFk INT, + vAction VARCHAR(50), vState VARCHAR(50), vIsScanned BOOLEAN) BEGIN @@ -66683,12 +66685,12 @@ BEGIN * @param vIsScanned Identificador si se ha escaneado automáticamente o manual */ - REPLACE vn.saleTracking(saleFk, - isChecked, - originalQuantity, - workerFk, + REPLACE vn.saleTracking(saleFk, + isChecked, + originalQuantity, + workerFk, stateFk, - isScanned) + isScanned) SELECT vSaleFK, vIsChecked, vOriginalQuantity, @@ -66715,27 +66717,27 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `saleTracking_updateIsChecked`(vSaleFK INT, vIsChecked BOOL, vIsScanned BOOL) BEGIN - + /** * Actualiza el estado del campo vn.saleTracking.isChecked y elimina las lineas de vn.itemShelving * si procede, en el caso de las preparaciones previas, por usuario - * + * * @param vSaleFk Identificador de vn.sale * @param vIsChecked Estado del registro */ - + UPDATE vn.saleTracking st JOIN vn.state s ON s.id = st.stateFk AND s.code = 'PREVIOUS_PREPARATION' SET st.isChecked = vIsChecked, st.isScanned = vIsScanned WHERE st.saleFk = vSaleFK AND st.workerFk = account.myUser_getId(); - + IF vIsChecked = FALSE THEN - - DELETE FROM vn.itemShelvingSale + + DELETE FROM vn.itemShelvingSale WHERE saleFk = vSaleFK; - + END IF; END ;; @@ -66761,14 +66763,14 @@ proc: BEGIN * * @param vSelf Id de la venta * @param vOption indica en que componente pone el descuadre, NULL en casos habituales - */ + */ CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales SELECT s.id FROM sale s WHERE s.id = vSelf; - + CALL sale_recalcComponent(vOption); - + DROP TEMPORARY TABLE tmp.recalculateSales; END ;; DELIMITER ; @@ -66815,7 +66817,7 @@ BEGIN GROUP BY s.id; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET v_done = TRUE; + SET v_done = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.coste; @@ -66823,7 +66825,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.coste (PRIMARY KEY (id)) ENGINE = MEMORY SELECT s.id - FROM sale s + FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemType tp ON tp.id = i.typeFk JOIN itemCategory ic ON ic.id = tp.categoryFk @@ -66842,17 +66844,17 @@ BEGIN IF v_done THEN LEAVE l; END IF; - + SELECT ticketFk, concept INTO vTicketFk, vConcept FROM sale WHERE id = vSaleFk; - + CALL sale_calculateComponent(vSaleFk, 1); END LOOP; CLOSE vCur; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -66938,7 +66940,7 @@ DECLARE vIsCollection BOOL; TRIM(CONCAT(LPAD(s.concept,30,' '), ' ', RPAD(IFNULL(i.size,''),5,' '))) line1, '' cel1, - TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, + TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) line2, IF(s.quantity MOD IFNULL(b.packing,s.quantity + 1), CONCAT(CAST(s.quantity/IFNULL(b.`grouping`,1) AS DECIMAL(10,0)),' x ',IFNULL(b.`grouping`,1)), CONCAT(CAST(s.quantity / IFNULL(b.packing,1) AS DECIMAL(10,0)),' pack de ',IFNULL(b.packing,1))) cel2, @@ -66955,12 +66957,12 @@ DECLARE vIsCollection BOOL; JOIN sale s ON s.ticketFk = t.id JOIN ticket tt ON tt.id = t.id LEFT JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND lb.warehouse_id = tt.warehouseFk - LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN buy b ON b.id = lb.buy_id JOIN item i ON i.id = s.itemFk LEFT JOIN ticketCollection tc ON tc.ticketFk = t.id LEFT JOIN collection c ON c.id = tc.collectionFk - LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity - FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity + LEFT JOIN (SELECT sub.saleFk, sub.isChecked, sub.stateFk, sub.originalQuantity + FROM (SELECT DISTINCT st.id, st.saleFk, st.isChecked, st.stateFk, st.originalQuantity FROM tmp.ticket2 t JOIN sale s ON s.ticketFk = t.id JOIN saleTracking st ON st.saleFk = s.id @@ -66972,7 +66974,7 @@ DECLARE vIsCollection BOOL; LEFT JOIN itemColor ic ON ic.itemFk = s.itemFk LEFT JOIN itemProductor ip ON ip.itemFk = s.itemFk LEFT JOIN origin o ON o.id = i.originFk - LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + LEFT JOIN saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN parking p ON p.id = sg.parkingFk LEFT JOIN saleMistake sm ON sm.saleFk = s.id @@ -67024,8 +67026,8 @@ BEGIN DELETE tt.* FROM tmp.sale_getProblems tt JOIN vn.ticketObservation tto ON tto.ticketFk = tt.ticketFk - JOIN vn.observationType ot ON ot.id = tto.observationTypeFk - WHERE ot.code = 'administrative' + JOIN vn.observationType ot ON ot.id = tto.observationTypeFk + WHERE ot.code = 'administrative' AND tto.description = 'Miriam'; CREATE OR REPLACE TEMPORARY TABLE tmp.sale_problems ( @@ -67057,7 +67059,7 @@ BEGIN -- Too Little INSERT INTO tmp.sale_problems(ticketFk, isTooLittle) - SELECT tp.ticketFk, TRUE + SELECT tp.ticketFk, TRUE FROM tmp.sale_getProblems tp JOIN vn.ticket t ON t.id = tp.ticketFk JOIN (SELECT t.addressFk, SUM(sv.litros) litros, t.totalWithoutVat @@ -67144,25 +67146,25 @@ BEGIN -- Disponible: no va a haber suficiente producto para preparar todos los pedidos CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouseFk, vDate); - - -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida + + -- Faltas: visible, disponible y ubicado son menores que la cantidad vendida CALL cache.visible_refresh(vVisibleCache, FALSE, vWarehouseFk); INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT tl.ticketFk, - LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, + SELECT tl.ticketFk, + LEFT(CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')),250) problem, s.id AS saleFk FROM tmp.ticket_list tl JOIN vn.ticket t ON t.id = tl.ticketFk JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -67175,7 +67177,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemShortage = sub.problem, saleFk = sub.saleFk; - + -- Inventario: Visible suficiente, pero ubicado menor a la cantidad vendida INSERT INTO tmp.sale_problems(ticketFk, itemLost, saleFk) SELECT ticketFk, problem, saleFk @@ -67188,7 +67190,7 @@ BEGIN JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -67201,7 +67203,7 @@ BEGIN AND t.warehouseFk = vWarehouseFk GROUP BY tl.ticketFk) sub ON DUPLICATE KEY UPDATE itemDelay = sub.problem, saleFk = sub.saleFk; - + -- Retraso: Disponible suficiente, pero no visible ni ubicado INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) SELECT ticketFk, problem, saleFk @@ -67215,7 +67217,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -67235,13 +67237,13 @@ BEGIN INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) SELECT ticketFk, problem, saleFk FROM ( - SELECT - tl.ticketFk, + SELECT + tl.ticketFk, s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, MOD(s.quantity, b.`grouping`) hasRounding FROM tmp.ticket_list tl - JOIN ticket t ON t.id = tl.ticketFk + JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk JOIN sale s ON s.ticketFk = tl.ticketFk JOIN item i ON i.id = s.itemFk @@ -67249,12 +67251,12 @@ BEGIN JOIN buy b ON b.id = bu.buyFk GROUP BY tl.ticketFk HAVING hasRounding - ) sub + ) sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; - + INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) SELECT DISTINCT tl.ticketFk, FALSE FROM tmp.ticket_list tl @@ -67284,16 +67286,16 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_getProblemsByTicket`(IN vTicketFk INT, IN vIsTodayRelative TINYINT(1)) BEGIN /** - * Calcula los problemas de cada venta + * Calcula los problemas de cada venta * para un conjunto de tickets. * * @return Problems result */ DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; - CREATE TEMPORARY TABLE tmp.sale_getProblems + CREATE TEMPORARY TABLE tmp.sale_getProblems (INDEX (ticketFk)) ENGINE = MEMORY - SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped + SELECT t.id ticketFk, t.clientFk, t.warehouseFk, t.shipped FROM ticket t WHERE t.id = vTicketFk; @@ -67322,7 +67324,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_PriceFix`(vTicketFk INT) BEGIN - + DELETE sc.* FROM vn.saleComponent sc JOIN vn.sale s ON s.id = sc.saleFk @@ -67358,52 +67360,52 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sale_recalcComponent`(vOption INT) proc: BEGIN /** - * Este procedimiento recalcula los componentes de un conjunto de sales, + * Este procedimiento recalcula los componentes de un conjunto de sales, * eliminando los componentes existentes e insertandolos de nuevo * * @param vOption si no se quiere forzar llamar con NULL * @table tmp.recalculateSales (id) - */ - DECLARE vShipped DATE; + */ + DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vTicketFk INT; - DECLARE vLanded DATE; + DECLARE vLanded DATE; DECLARE vIsEditable BOOLEAN; DECLARE vZoneFk INTEGER; DECLARE vDone BOOL DEFAULT FALSE; - + DECLARE vCur CURSOR FOR SELECT DISTINCT s.ticketFk FROM tmp.recalculateSales rs JOIN vn.sale s ON s.id = rs.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + OPEN vCur; l: LOOP SET vDone = FALSE; - FETCH vCur INTO vTicketFk; - + FETCH vCur INTO vTicketFk; + IF vDone THEN LEAVE l; END IF; - SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL, - t.zoneFk, - t.warehouseFk, - t.shipped, - t.addressFk, - t.agencyModeFk, + SELECT (hasToRecalcPrice OR ts.alertLevel IS NULL) AND t.refFk IS NULL, + t.zoneFk, + t.warehouseFk, + t.shipped, + t.addressFk, + t.agencyModeFk, t.landed - INTO vIsEditable, - vZoneFk, - vWarehouseFk, - vShipped, - vAddressFk, - vAgencyModeFk, + INTO vIsEditable, + vZoneFk, + vWarehouseFk, + vShipped, + vAddressFk, + vAgencyModeFk, vLanded FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket @@ -67411,31 +67413,31 @@ proc: BEGIN WHERE t.id = vTicketFk; CALL zone_getLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk, TRUE); - + IF NOT EXISTS (SELECT TRUE FROM tmp.zoneGetLanded LIMIT 1) THEN CALL util.throw(CONCAT('There is no zone for these parameters ', vTicketFk)); END IF; - + IF vLanded IS NULL OR vZoneFk IS NULL THEN - + UPDATE ticket t - SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) + SET t.landed = (SELECT landed FROM tmp.zoneGetLanded LIMIT 1) WHERE t.id = vTicketFk AND t.landed IS NULL; - + IF vZoneFk IS NULL THEN SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; UPDATE ticket t SET t.zoneFk = vZoneFk WHERE t.id = vTicketFk AND t.zoneFk IS NULL; END IF; - + END IF; - + DROP TEMPORARY TABLE tmp.zoneGetLanded; - - -- rellena la tabla buyUltimate con la ultima compra - CALL buyUltimate (vWarehouseFk, vShipped); - + + -- rellena la tabla buyUltimate con la ultima compra + CALL buyUltimate (vWarehouseFk, vShipped); + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (saleFk)) ENGINE = MEMORY SELECT s.id saleFk, vWarehouseFk warehouseFk @@ -67443,7 +67445,7 @@ proc: BEGIN JOIN tmp.recalculateSales rs ON s.id = rs.id WHERE s.ticketFk = vTicketFk; - CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketLot SELECT vWarehouseFk warehouseFk, NULL available, s.itemFk, bu.buyFk, vZoneFk zoneFk FROM sale s JOIN tmp.recalculateSales rs ON s.id = rs.id @@ -67457,15 +67459,15 @@ proc: BEGIN IF vOption IS NULL THEN SET vOption = IF(vIsEditable, 1, 6); END IF; - - CALL ticketComponentUpdateSale(vOption); + + CALL ticketComponentUpdateSale(vOption); CALL catalog_componentPurge(); - + DROP TEMPORARY TABLE tmp.buyUltimate; DROP TEMPORARY TABLE tmp.sale; - + END LOOP; - CLOSE vCur; + CLOSE vCur; END ;; DELIMITER ; @@ -67486,22 +67488,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollectionSaleGroup_add`(vSaleGroupFk INT, vSectorCollectionFk INT) BEGIN /** - * Inserta un nuevo registro en vn.sectorCollectionSaleGroup + * Inserta un nuevo registro en vn.sectorCollectionSaleGroup * Actualiza el usuario en vn.saleGroup y reemplaza los registros de vn.saleTracking - * + * * @param vSaleGroupFk Identificador de vn.saleGroup * @param vSectorCollectionFk Identificador de vn.sectorCollection */ REPLACE sectorCollectionSaleGroup - SET sectorCollectionFk = vSectorCollectionFk, + SET sectorCollectionFk = vSectorCollectionFk, saleGroupFk = vSaleGroupFk; - + UPDATE saleGroup sg JOIN sectorCollectionSaleGroup scsg ON scsg.saleGroupFk = sg.id JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk - SET sg.userFk = sc.userFk + SET sg.userFk = sc.userFk WHERE sg.id = vSaleGroupFk; - + INSERT IGNORE saleTracking( saleFk, isChecked, @@ -67513,8 +67515,8 @@ BEGIN sc.userFk, s.id FROM saleGroupDetail sgd - JOIN sectorCollectionSaleGroup scsg - ON scsg.saleGroupFk = sgd.saleGroupFk + JOIN sectorCollectionSaleGroup scsg + ON scsg.saleGroupFk = sgd.saleGroupFk JOIN sectorCollection sc ON sc.id = scsg.sectorCollectionFk JOIN state s ON s.code = 'PREVIOUS_PREPARATION' WHERE sgd.saleGroupFk = vSaleGroupFk; @@ -67615,30 +67617,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_new`(vSectorFk INT) -BEGIN -/** - * Inserta una nueva colección, si el usuario no tiene ninguna vacia. - * Esto se hace para evitar que por error se generen colecciones sin sentido. - * - * @param vSectorFk Identificador de #vn.sector - */ - DECLARE hasEmptyCollections BOOL; - DECLARE vUserFk INT; - - SET vUserFk = account.myUser_getId(); - - SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections - FROM vn.sectorCollection sc - LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id - WHERE ISNULL(scsg.id) - AND sc.userFk = vUserFk - AND sc.sectorFk = vSectorFk - AND sc.created >= util.VN_CURDATE(); - - IF NOT hasEmptyCollections THEN - INSERT INTO vn.sectorCollection(userFk, sectorFk) - VALUES(vUserFk, vSectorFk); - END IF; +BEGIN +/** + * Inserta una nueva colección, si el usuario no tiene ninguna vacia. + * Esto se hace para evitar que por error se generen colecciones sin sentido. + * + * @param vSectorFk Identificador de #vn.sector + */ + DECLARE hasEmptyCollections BOOL; + DECLARE vUserFk INT; + + SET vUserFk = account.myUser_getId(); + + SELECT (COUNT(sc.id) > 0) INTO hasEmptyCollections + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + WHERE ISNULL(scsg.id) + AND sc.userFk = vUserFk + AND sc.sectorFk = vSectorFk + AND sc.created >= util.VN_CURDATE(); + + IF NOT hasEmptyCollections THEN + INSERT INTO vn.sectorCollection(userFk, sectorFk) + VALUES(vUserFk, vSectorFk); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67774,7 +67776,7 @@ BEGIN SELECT s.warehouseFk FROM vn.sector s WHERE s.id = vSectorFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67869,10 +67871,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingChange`(IN `vShelvingO` VAR BEGIN UPDATE vn.itemShelving - SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci - WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; - - + SET shelvingFk = vShelvingD COLLATE utf8_unicode_ci + WHERE shelvingFk = vShelvingO COLLATE utf8_unicode_ci; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -67891,16 +67893,16 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingLog_get`(shelvingFk VARCHAR(10)) BEGIN - + /* Lista el log de un carro - * + * * @param shelvingFk matrícula del carro - * + * */ - + SELECT originFk, name, creationDate, description FROM shelvingLog sl - JOIN account.user u ON u.id = sl.userFk + JOIN account.user u ON u.id = sl.userFk WHERE sl.originFk = shelvingFk COLLATE utf8_general_ci ORDER BY creationDate DESC; @@ -67923,22 +67925,22 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `shelvingParking_get`(vShelvingFk VARCHAR(10), vWarehouseFk INT, vDayRange INT) BEGIN - -SELECT s.itemFk, + +SELECT s.itemFk, s.concept, - CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, - CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado + CAST(SUM(s.quantity) AS DECIMAL(10,0)) as sinServir, + CAST(IFNULL(ist.visible,0) AS DECIMAL(10,0)) as aparcado FROM vn.sale s LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id JOIN vn.ticket t ON t.id = s.ticketFk LEFT JOIN vn.itemShelvingStock ist ON ist.itemFk = s.itemFk AND ist.warehouseFk = vWarehouseFk JOIN vn.itemShelving ish ON ish.itemFk = s.itemFk AND ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci - WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) + WHERE t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(TIMESTAMPADD(DAY, GREATEST(0,vDayRange), util.VN_CURDATE())) AND iss.saleFk IS NULL AND t.warehouseFk = vWarehouseFk GROUP BY s.itemFk HAVING sinServir > aparcado; - + END ;; DELIMITER ; @@ -67983,12 +67985,12 @@ BEGIN DELETE FROM vn.shelving WHERE length(code) > 3 AND parked < TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - + DELETE FROM vn.itemShelving WHERE visible <= 0 AND created < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - DELETE ish.* + DELETE ish.* FROM vn.itemShelving ish JOIN vn.shelving sh ON sh.code = ish.shelvingFk WHERE sh.parkingFk IS NULL @@ -67996,12 +67998,12 @@ BEGIN UPDATE vn.shelving sh LEFT JOIN vn.itemShelving its ON its.shelvingFk = sh.`code` - SET isPrinted = 0, + SET isPrinted = 0, parkingFk = NULL WHERE its.id IS NULL - AND sh.isRecyclable - AND ( sh.parked IS NULL - OR + AND sh.isRecyclable + AND ( sh.parked IS NULL + OR sh.parked < TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()) ); @@ -68178,20 +68180,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `solunionRiskRequest`() BEGIN - + DROP TEMPORARY TABLE IF EXISTS tmp.client_list; CREATE TEMPORARY TABLE tmp.client_list (PRIMARY KEY (Id_Cliente)) ENGINE = MEMORY - SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc + SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification WHERE dateEnd IS NULL ORDER BY ci.creationDate DESC LIMIT 10000000000000000000) t1 GROUP BY Id_Cliente; - + CALL vn2008.risk_vs_client_list(util.VN_CURDATE()); - - SELECT + + SELECT c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo, cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo, f.Consumo consumo_anual, c.Vencimiento, ci.grade @@ -68201,7 +68203,7 @@ BEGIN JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente GROUP BY Id_cliente; - + DROP TEMPORARY TABLE IF EXISTS tmp.risk; DROP TEMPORARY TABLE IF EXISTS tmp.client_list; END ;; @@ -68416,10 +68418,10 @@ BEGIN DECLARE vBossId INT; DECLARE vDone BOOL; DECLARE workerCur CURSOR FOR - SELECT workerFk - FROM tmp.subordinate + SELECT workerFk + FROM tmp.subordinate WHERE NOT isChecked; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR 1062 BEGIN @@ -68427,29 +68429,29 @@ BEGIN END; DROP TEMPORARY TABLE IF EXISTS tmp.subordinate; - + CREATE TEMPORARY TABLE tmp.subordinate (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBossFk AS workerFk, 0 AS isChecked; - + WHILE (SELECT COUNT(*) FROM tmp.subordinate WHERE NOT isChecked) > 0 DO OPEN workerCur; workerLoop: LOOP SET vDone = FALSE; FETCH workerCur INTO vBossId; - + IF vDone THEN LEAVE workerLoop; END IF; - - INSERT INTO tmp.subordinate - SELECT id, 0 - FROM worker + + INSERT INTO tmp.subordinate + SELECT id, 0 + FROM worker WHERE bossFk = vBossId; - - UPDATE tmp.subordinate + + UPDATE tmp.subordinate SET isChecked = 1 WHERE workerFk = vBossId; END LOOP; @@ -68489,13 +68491,13 @@ BEGIN -- Calcula el balance inicial y final de cada proveedor INSERT INTO openingBalance SELECT MAX(dueDated), - supplierFk, - companyFk, + supplierFk, + companyFk, sum(amount) eurAmount, sum(divisa) foreignAmount FROM ( SELECT p.dueDated, - p.supplierFk, + p.supplierFk, p.companyFk, p.amount, p.divisa @@ -68511,7 +68513,7 @@ BEGIN SELECT iidd.dueDated, ii.supplierFk, ii.companyFk, - - iidd.amount, + - iidd.amount, - iidd.foreignValue FROM invoiceIn ii JOIN invoiceInDueDay iidd ON ii.id = iidd.invoiceInFk @@ -68519,14 +68521,14 @@ BEGIN JOIN company co ON co.id = ii.companyFk WHERE iidd.dueDated > '2014-12-31' AND iidd.dueDated <= vEnded - AND ii.isBooked AND co.`code` = 'VNL' + AND ii.isBooked AND co.`code` = 'VNL' AND c.`code` <> 'EUR' UNION ALL SELECT se.dueDated, se.supplierFk, se.companyFk, - - se.amount, + - se.amount, 0 FROM supplierExpense se JOIN currency c ON c.id = se.currencyFk @@ -68536,7 +68538,7 @@ BEGIN AND co.`code` = 'VNL' AND c.`code` <> 'EUR' ) sub GROUP BY companyFk, supplierFk; - + SELECT ob.dueDated , ob.supplierFk , ob.companyFk @@ -68750,7 +68752,7 @@ BEGIN - SUM(iid.amount) mysql, 0 sage FROM invoiceInDueDay iid - JOIN invoiceIn ii ON ii.id = iid.invoiceInFk + JOIN invoiceIn ii ON ii.id = iid.invoiceInFk WHERE IFNULL(ii.bookEntried, ii.issued) BETWEEN vDateFrom AND vDateTo AND ii.isBooked GROUP BY ii.id @@ -68889,15 +68891,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketBoxesView`(IN vTicketFk INT) BEGIN - - SELECT s.id, - s.itemFk, - s.concept, - floor(s.quantity / b.packing) as Cajas, - b.packing, - s.isPicked, + + SELECT s.id, + s.itemFk, + s.concept, + floor(s.quantity / b.packing) as Cajas, + b.packing, + s.isPicked, i.size - FROM ticket t + FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN item i ON i.id = s.itemFk JOIN cache.last_buy lb on lb.warehouse_id = t.warehouseFk AND lb.item_id = s.itemFk @@ -68908,7 +68910,7 @@ BEGIN AND p.isBox GROUP BY s.itemFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -68930,7 +68932,7 @@ BEGIN DECLARE vDateStart DATETIME DEFAULT DATE(vDate); DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketBuiltTime; CREATE TEMPORARY TABLE tmp.ticketBuiltTime @@ -68943,7 +68945,7 @@ BEGIN SELECT ticketFk, builtTime FROM ( - SELECT + SELECT ticketFk, created as builtTime FROM @@ -68951,13 +68953,13 @@ BEGIN WHERE created BETWEEN vDateStart AND vDateEnd ORDER BY ticketFk, created DESC LIMIT 10000000000000000000 - ) sub + ) sub GROUP BY ticketFk ) sub2 ON sub2.ticketFk = t.id WHERE t.shipped BETWEEN vDate AND util.dayEnd(vDate) AND t.clientFk NOT IN (50,400,200) AND t.companyFk = 442 - + ; END ;; @@ -68986,30 +68988,30 @@ BEGIN */ REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket + SELECT orderFk, vTicketNew + FROM orderTicket WHERE ticketFk = vTicketOld; - + -- Bionizamos lineas con Preu = 0 CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT id + SELECT id FROM sale WHERE ticketFk = vTicketNew AND price = 0; - + CALL sale_recalcComponent(1); -- Bionizamos lineas con Preu > 0 CREATE OR REPLACE TEMPORARY TABLE tmp.recalculateSales (PRIMARY KEY (id)) ENGINE = MEMORY - SELECT id + SELECT id FROM sale WHERE ticketFk = vTicketNew AND price > 0; - + CALL sale_recalcComponent(6); DROP TEMPORARY TABLE IF EXISTS tmp.recalculateSales; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69032,12 +69034,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculateFromType`( vLanded D vTypeFk INT) BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - (INDEX (itemFk)) - ENGINE = MEMORY + CREATE TEMPORARY TABLE tmp.item + (INDEX (itemFk)) + ENGINE = MEMORY SELECT id itemFk FROM vn.item WHERE typeFk = vTypeFk; - + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; DROP TEMPORARY TABLE tmp.ticketLot; @@ -69059,7 +69061,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCalculatePurge`() BEGIN - DROP TEMPORARY TABLE + DROP TEMPORARY TABLE tmp.ticketCalculateItem, tmp.ticketComponentPrice, tmp.ticketComponent, @@ -69083,56 +69085,56 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketClon`(vTicketFk INT, vNewShipped DATE) BEGIN - + DECLARE done INT DEFAULT FALSE; - DECLARE vNewTicketFk INT; + DECLARE vNewTicketFk INT; DECLARE vOldSaleFk INT; DECLARE vNewSaleFk INT; - + DECLARE cur1 CURSOR FOR SELECT id FROM vn.sale WHERE ticketFk = vTicketFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - + SET vNewShipped = IFNULL(vNewShipped, util.VN_CURDATE()); - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.ticket + + UPDATE vn.ticket SET landed = TIMESTAMPADD(DAY, DATEDIFF(vNewShipped, shipped), landed), shipped = vNewShipped WHERE id = vNewTicketFk; - + OPEN cur1; - + read_loop: LOOP - + FETCH cur1 INTO vOldSaleFk; - + IF done THEN LEAVE read_loop; END IF; - + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed) SELECT vNewTicketFk, itemFk, quantity, concept, price, discount, priceFixed, isPriceFixed FROM vn.sale WHERE id = vOldSaleFk; - + SELECT max(id) INTO vNewSaleFk FROM vn.sale WHERE ticketFk = vNewTicketFk; - + INSERT INTO vn.saleComponent(saleFk, componentFk, value, isGreuge) SELECT vNewSaleFk, componentFk, value, isGreuge FROM vn.saleComponent WHERE saleFk = vOldSaleFk; - + END LOOP; CLOSE cur1; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69154,18 +69156,18 @@ BEGIN DECLARE vShipped DATE; DECLARE vMaxDated DATE; - - SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) + + SELECT shipped, TIMESTAMPADD(YEAR,1,shipped) INTO vShipped, vMaxDated FROM vn.ticket WHERE id = vTicketFk; - + WHILE vShipped <= vMaxDated DO - + SET vShipped = TIMESTAMPADD(WEEK, 1, vShipped); - + CALL vn.ticketClon(vTicketFk, vShipped); - + END WHILE; END ;; @@ -69187,10 +69189,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_get`(vTicketFk INT) BEGIN - SELECT tc.collectionFk + SELECT tc.collectionFk FROM vn.ticketCollection tc WHERE ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69209,18 +69211,18 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketCollection_setUsedShelves`(vTicketFk INT, vUsedShelves INT) BEGIN - + /* * Inserta número de baldas que ocupa un ticket - * + * * @param vTicketFk Identificador de ticket * @param vUsedShelves Número de baldas */ - + UPDATE ticketCollection tc SET tc.usedShelves = vUsedShelves WHERE tc.ticketFk = vTicketFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69258,18 +69260,18 @@ BEGIN END; START TRANSACTION; - + IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.agencyModeFk = vAgencyModeFk, t.addressFk = vAddressFk, @@ -69280,12 +69282,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -69327,104 +69329,104 @@ BEGIN DECLARE vComponentFk INT; DECLARE vRenewComponents BOOLEAN; DECLARE vKeepPrices BOOLEAN; - + CASE vOption - WHEN 1 THEN + WHEN 1 THEN SET vRenewComponents = TRUE; SET vKeepPrices = FALSE; WHEN 2 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; + SELECT id INTO vComponentFk FROM component WHERE `code` = 'debtCollection'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - WHEN 3 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; - SET vRenewComponents = TRUE; - SET vKeepPrices = TRUE; - WHEN 4 THEN - SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + WHEN 3 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'mana'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; - /* WHEN 5 THEN + WHEN 4 THEN + SELECT id INTO vComponentFk FROM component WHERE `code` = 'buyerDiscount'; + SET vRenewComponents = TRUE; + SET vKeepPrices = TRUE; + /* WHEN 5 THEN SET vComponentFk = 35; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE;*/ - WHEN 6 THEN + WHEN 6 THEN SELECT id INTO vComponentFk FROM component WHERE `code` = 'imbalance'; SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; WHEN 7 THEN REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.8, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) + SELECT s.id, 29, ROUND(((s.price * (100 - s.discount) / 100) - SUM(IFNULL(sc.value, 0))) * 0.2, 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk NOT IN (28, 29) GROUP BY s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; WHEN 8 THEN - DELETE sc.* + DELETE sc.* FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk; - + REPLACE INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) + SELECT s.id, 28, ROUND(((s.price * (100 - s.discount) / 100)), 3) FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id; - + SET vRenewComponents = FALSE; SET vKeepPrices = FALSE; - WHEN 9 THEN + WHEN 9 THEN SET vRenewComponents = TRUE; SET vKeepPrices = TRUE; END CASE; IF vRenewComponents THEN - DELETE sc.* - FROM tmp.sale tmps + DELETE sc.* + FROM tmp.sale tmps JOIN saleComponent sc ON sc.saleFk = tmps.saleFk JOIN `component` c ON c.id = sc.componentFk WHERE c.isRenewable; - + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, tc.componentFk, tc.cost - FROM sale s + FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id - AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk + LEFT JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = tc.componentFk + LEFT JOIN `component` c ON c.id = tc.componentFk WHERE IF(sc.componentFk IS NULL AND NOT c.isRenewable, FALSE, TRUE); - - -- Añadir componente venta por paquete + + -- Añadir componente venta por paquete DROP TEMPORARY TABLE IF EXISTS tmp.sale2; CREATE TEMPORARY TABLE tmp.sale2 (PRIMARY KEY (saleFk)) - ENGINE = MEMORY + ENGINE = MEMORY SELECT * FROM tmp.sale; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent2; CREATE TEMPORARY TABLE tmp.ticketComponent2 - SELECT * FROM tmp.ticketComponent; - - REPLACE INTO saleComponent(saleFk, componentFk, value) + SELECT * FROM tmp.ticketComponent; + + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT t.id, t.componentFk, t.cost FROM ( SELECT s.id, tc.componentFk, tc.cost, MOD(s.quantity, b.packing) as resto FROM vn.sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id - JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id + JOIN cache.last_buy lb ON lb.item_id = s.itemFk AND tmps.warehouseFk = lb.warehouse_id JOIN vn.buy b ON b.id = buy_id JOIN tmp.ticketComponent tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = tmps.warehouseFk - JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' + JOIN `component` c ON c.id = tc.componentFk AND c.code = 'salePerPackage' LEFT JOIN ( SELECT s.id FROM vn.sale s @@ -69435,8 +69437,8 @@ BEGIN ) tp ON tp.id = s.id WHERE tp.id IS NULL HAVING resto <> 0) t; - - DROP TEMPORARY TABLE IF EXISTS + + DROP TEMPORARY TABLE IF EXISTS tmp.sale2, tmp.ticketComponent2; END IF; @@ -69454,26 +69456,26 @@ BEGIN UPDATE sale s JOIN item i on i.id = s.itemFk JOIN itemType it on it.id = i.typeFk - JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk + JOIN (SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk GROUP BY sc.saleFk) sc ON sc.saleFk = s.id SET s.price = sumValue / ((100 - s.discount) / 100) - WHERE it.code != 'PRT' ; - + WHERE it.code != 'PRT' ; + REPLACE INTO saleComponent(saleFk, componentFk, value) SELECT s.id, 21, ROUND((s.price * (100 - s.discount) / 100) - SUM(value), 3) saleValue FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id WHERE sc.componentFk != 21 - GROUP BY s.id + GROUP BY s.id HAVING ROUND(saleValue, 4) <> 0; END IF; - + UPDATE sale s JOIN ( - SELECT SUM(sc.value) sumValue, sc.saleFk + SELECT SUM(sc.value) sumValue, sc.saleFk FROM saleComponent sc JOIN tmp.sale tmps ON tmps.saleFk = sc.saleFk JOIN `component` c ON c.id = sc.componentFk @@ -69487,10 +69489,10 @@ BEGIN JOIN sale s on s.id = sc.saleFk JOIN item i ON i.id = s.itemFk JOIN itemType it ON it.id = i.typeFk - WHERE it.code = 'PRT'; - + WHERE it.code = 'PRT'; + INSERT INTO saleComponent(saleFk, componentFk, value) - SELECT s.id, 15, s.price + SELECT s.id, 15, s.price FROM sale s JOIN tmp.sale tmps ON tmps.saleFk = s.id JOIN item i ON i.id = s.itemFK @@ -69557,24 +69559,24 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket ENGINE = MEMORY SELECT vTicketFk ticketFk; - + CALL vn.ticket_getTax(NULL); - SELECT + SELECT tt.ticketFk, CAST(tt.taxableBase AS DECIMAL(10, 2)) AS taxableBase, CAST(tt.rate * tt.taxableBase / 100 AS DECIMAL(10, 2)) AS tax, - pgc.*, + pgc.*, CAST(IF(pe.equFk IS NULL, taxableBase, 0) AS DECIMAL(10, 2)) AS Base, pgc.rate / 100 as vatPercent FROM tmp.ticketTax tt JOIN vn.pgc ON pgc.code = tt.pgcFk LEFT JOIN vn.pgcEqu pe ON pe.equFk = pgc.code; - + DROP TEMPORARY TABLE tmp.ticket; DROP TEMPORARY TABLE tmp.ticketTax; DROP TEMPORARY TABLE tmp.ticketAmount; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69612,29 +69614,29 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; CREATE TEMPORARY TABLE tmp.ticketTax (INDEX (ticketFk)) ENGINE = MEMORY SELECT tmpTicket.ticketFk, bp.pgcFk, - SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) + SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) AS taxableBase, SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) ) * pgc.rate / 100 AS tax, tc.code - + FROM tmp.ticket tmpTicket JOIN sale s ON s.ticketFk = tmpTicket.ticketFk JOIN item i ON i.id = s.itemFk JOIN ticket t ON t.id = tmpTicket.ticketFk JOIN supplier su ON su.id = t.companyFk - JOIN tmp.addressTaxArea ata + JOIN tmp.addressTaxArea ata ON ata.addressFk = t.addressFk AND ata.companyFk = t.companyFk - JOIN itemTaxCountry itc + JOIN itemTaxCountry itc ON itc.itemFk = i.id AND itc.countryFk = su.countryFk - JOIN bookingPlanner bp + JOIN bookingPlanner bp ON bp.countryFk = su.countryFk AND bp.taxAreaFk = ata.areaFk AND bp.taxClassFk = itc.taxClassFk @@ -69642,7 +69644,7 @@ BEGIN JOIN taxClass tc ON tc.id = bp.taxClassFk GROUP BY tmpTicket.ticketFk, pgc.code HAVING taxableBase != 0; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) @@ -69653,7 +69655,7 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.addressCompany; DROP TEMPORARY TABLE IF EXISTS tmp.addressTaxArea; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69674,7 +69676,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketGetTotal`(vTaxArea VARCHAR(25 BEGIN /** * Calcula el total con IVA para un conjunto de tickets. - * + * * @param vTaxArea * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular * @return tmp.ticketTotal Total para cada ticket @@ -69691,7 +69693,7 @@ BEGIN FROM tmp.ticket t LEFT JOIN tmp.ticketAmount ta ON t.ticketFk = ta.ticketFk GROUP BY ticketFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketAmount; DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax; END ;; @@ -69763,18 +69765,18 @@ BEGIN DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) INTO vLevel, vCollectionFk FROM vn.ticketCollection WHERE ticketFk = vTicketFk LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking WHERE ticketFk = vTicketFk; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -69801,7 +69803,7 @@ BEGIN AND sc.isPackagingArea AND tp.created < vParked AND t.packages <=> 0); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69822,7 +69824,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketNotInvoicedByClient`(vClientF BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - + CREATE TEMPORARY TABLE tmp.ticket SELECT id ticketFk FROM ticket @@ -69832,7 +69834,7 @@ BEGIN CALL vn.ticketGetTotal(NULL); - SELECT c.id, + SELECT c.id, c.name as Cliente, t.shipped as Fecha, t.id as Id_Ticket, @@ -69843,7 +69845,7 @@ BEGIN DROP TEMPORARY TABLE tmp.ticket, - tmp.ticketTotal; + tmp.ticketTotal; END ;; DELIMITER ; @@ -69863,21 +69865,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketObservation_addNewBorn`(vTicketFk INT) BEGIN - + /** * Inserta observaciones para los tickets con clientes nuevos o recuperados - * + * * @param vTicketFk Identificador de vn.ticket */ - + DECLARE vDescription VARCHAR(20) DEFAULT '¡Cliente NUEVO! '; INSERT INTO vn.ticketObservation(ticketFk, observationTypeFk, description) SELECT vTicketFk, ot.id, vDescription FROM vn.observationType ot WHERE ot.hasNewBornMessage - ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); - + ON DUPLICATE KEY UPDATE description = CONCAT(vDescription, ticketObservation.description); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69917,7 +69919,7 @@ BEGIN DECLARE vComponentCost INT; DECLARE vDone INT DEFAULT FALSE; DECLARE vClientId INT; - + DECLARE vCursor CURSOR FOR SELECT DISTINCT clientFk FROM ( @@ -69934,31 +69936,31 @@ BEGIN RESIGNAL; END; - SELECT id INTO vWarehouseInventory - FROM warehouse + SELECT id INTO vWarehouseInventory + FROM warehouse WHERE `code`= 'inv'; - - SELECT id INTO vComponentCost - FROM component + + SELECT id INTO vComponentCost + FROM component WHERE `code`= 'purchaseValue'; - - SELECT packagingInvoicingDated INTO vDateStart - FROM ticketConfig; - + + SELECT packagingInvoicingDated INTO vDateStart + FROM ticketConfig; + IF vWarehouseInventory IS NULL THEN CALL util.throw('Warehouse inventory not set'); END IF; IF vComponentCost IS NULL THEN CALL util.throw('Component cost not set'); - END IF; + END IF; SET vDateEnd = vDated + INTERVAL 1 DAY; - + IF NOT vWithoutPeriodGrace THEN SET vGraceDate = vGraceDate -INTERVAL 1 MONTH; END IF; - + DROP TEMPORARY TABLE IF EXISTS tmp.packagingToInvoice; CREATE TEMPORARY TABLE tmp.packagingToInvoice (INDEX (clientFk)) @@ -69971,7 +69973,7 @@ BEGIN t.clientFk FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk - JOIN ticket t ON t.id = tp.ticketFk + JOIN ticket t ON t.id = tp.ticketFk JOIN client c ON c.id = t.clientFk WHERE c.isActive AND (vClientFk IS NULL OR t.clientFk = vClientFk) @@ -69979,7 +69981,7 @@ BEGIN AND (tp.quantity < 0 OR (tp.quantity > 0 AND t.shipped < vGraceDate)) AND tp.quantity AND p.itemFk; - + OPEN vCursor; l: LOOP @@ -69992,25 +69994,25 @@ BEGIN START TRANSACTION; CALL ticket_add( - vClientId, + vClientId, vDateEnd, - vWarehouseInventory, - vCompanyFk, - NULL, - NULL, - NULL, - vDateEnd, - account.myUser_getId(), + vWarehouseInventory, + vCompanyFk, + NULL, + NULL, + NULL, + vDateEnd, + account.myUser_getId(), TRUE, vNewTicket); - + INSERT INTO ticketPackaging(ticketFk, packagingFk, quantity, pvp) SELECT vNewTicket, packagingFk, - SUM(quantity) totalQuantity, price - FROM tmp.packagingToInvoice + FROM tmp.packagingToInvoice WHERE clientFk = vClientId GROUP BY packagingFk HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity < 0); - + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price) SELECT vNewTicket, pti.itemFk, i.name, SUM(pti.quantity) totalQuantity, pti.price FROM tmp.packagingToInvoice pti @@ -70018,12 +70020,12 @@ BEGIN WHERE pti.clientFk = vClientId GROUP BY pti.itemFk HAVING IF(vWithoutPeriodGrace, totalQuantity <> 0, totalQuantity > 0); - + INSERT INTO saleComponent(saleFk, componentFk, value) SELECT id, vComponentCost, price FROM sale WHERE ticketFk = vNewTicket; - + COMMIT; END LOOP; CLOSE vCursor; @@ -70047,37 +70049,37 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketParking_findSkipped`(vTicketFk INT, vItemPackingTypeFk VARCHAR(1)) BEGIN - + /** * Averigua los tickets que se han saltado por un error en el proceso encajado * @param vTicketFk Ticket * @param vItemPackingTypeFk Modo de encajado * @return un select con los tickets afectados - */ + */ DECLARE vParkingFk INT; DECLARE vParked DATETIME; DECLARE vLevel INT; DECLARE vWagon INT; DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) + + SELECT IFNULL(`level`,0), IFNULL(`wagon`,0),IFNULL(collectionFk,0) INTO vLevel, vWagon, vCollectionFk FROM vn.ticketCollection tc JOIN vn.collection c ON c.id = tc.collectionFk AND c.itemPackingTypeFk = vItemPackingTypeFk WHERE ticketFk = vTicketFk ORDER BY c.id DESC LIMIT 1; - - SELECT created, parkingFk + + SELECT created, parkingFk INTO vParked, vParkingFk FROM vn.ticketParking tp - JOIN vn.parking p ON p.id = tp.parkingFk - JOIN vn.sector s ON s.id = p.sectorFk + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector s ON s.id = p.sectorFk WHERE ticketFk = vTicketFk AND s.itemPackingTypeFk = vItemPackingTypeFk AND s.isPackagingArea ; - + SELECT tp.ticketFk, CONCAT(tc.collectionFk, ' ', tc.wagon, ' - ', tc.level) coleccion, tp.created, p.code, am.name as Agencia FROM vn.ticketParking tp JOIN vn.parking p ON p.id = tp.parkingFk @@ -70094,9 +70096,9 @@ BEGIN AND ( ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) OR - ( tc.collectionFk = vCollectionFk + ( tc.collectionFk = vCollectionFk AND (LEFT(tc.wagon,1) < LEFT(vWagon,1) - OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) + OR (LEFT(tc.wagon,1) = LEFT(vWagon,1) AND LEFT(tc.level,1) < LEFT(vLevel,1))) ) ) ) -- Etiquetas que no se han escaneado y ya estamos con una posterior @@ -70104,7 +70106,7 @@ BEGIN (s.alertLevel > 1 AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END ;; DELIMITER ; @@ -70156,11 +70158,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketRequest_Add`(vDescription VARCHAR(255), vQuantity INT, vPrice DOUBLE, vTicketFk INT, vBuyerCode VARCHAR(3)) BEGIN - INSERT INTO vn.ticketRequest(description, - quantity, - price, - ticketFk, - buyerCode, + INSERT INTO vn.ticketRequest(description, + quantity, + price, + ticketFk, + buyerCode, requesterFk) VALUES(vDescription, vQuantity, @@ -70168,7 +70170,7 @@ BEGIN vTicketFk, vBuyerCode, vn.getUser()); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70187,26 +70189,26 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* Modifica el estado de un ticket de hoy - * + * * @param vTicketFk el id del ticket * @param vStateCode estado a modificar del ticket - * + * */ - + DECLARE vAlertLevel INT; - - SELECT s.alertLevel INTO vAlertLevel - FROM state s - JOIN ticketStateToday tst ON tst.state = s.id + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id WHERE tst.ticket = vTicketFk LIMIT 1; - + IF vAlertLevel < 2 THEN - + CALL vn.ticket_setState(vTicketFk, vStateCode); - + END IF; END ;; @@ -70227,23 +70229,23 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN - + /* * @deprecated:utilizar ticket_setState */ - + DECLARE vAlertLevel INT; - SELECT s.alertLevel INTO vAlertLevel + SELECT s.alertLevel INTO vAlertLevel FROM vn.state s JOIN vn.ticketState ts ON ts.stateFk = s.id WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + INSERT INTO ticketTracking(stateFk, ticketFk, workerFk) SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state + FROM vn.state WHERE `code` = vStateCode collate utf8_unicode_ci; END IF; @@ -70523,20 +70525,20 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_administrativeCopy`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN - + INSERT INTO vn.ticket(clientFk, addressFk, shipped, warehouseFk, companyFk, landed) - SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed + SELECT t.clientFk , t.addressFk , t.shipped ,w.id, t.companyFk , t.landed FROM vn.ticket t JOIN vn.warehouse w ON w.name = 'INVENTARIO' WHERE t.id = vOriginalTicket; - + SELECT LAST_INSERT_ID() INTO vNewTicket; INSERT INTO vn.sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount + SELECT vNewTicket, s.itemFk , s.concept , s.quantity , s.price , s.discount FROM vn.sale s WHERE s.ticketFk = vOriginalTicket; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70780,7 +70782,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_canMerge`(vDated DATE, vScop BEGIN /** * Devuelve un listado de tickets susceptibles de fusionarse con otros tickets en el futuro - * + * * @param vDated Fecha en cuestión * @param vScopeDays Dias en el futuro a sondear * @param vLitersMax Volumen máximo de los tickets a catapultar @@ -70861,10 +70863,10 @@ BEGIN * Comprueba que los tickets entre un rango de fechas tienen componentes * y recalcula sus componentes * - * @param vShippedFrom rango inicial de fecha + * @param vShippedFrom rango inicial de fecha * @param vShippedTo rango final de fecha */ - + CREATE OR REPLACE TEMPORARY TABLE tmp.coste (primary key (id)) ENGINE = MEMORY SELECT s.id @@ -70893,9 +70895,9 @@ BEGIN AND ic.merchandise; CALL vn.sale_recalcComponent(1); - + DROP TEMPORARY TABLE tmp.recalculateSales; - DROP TEMPORARY TABLE tmp.coste; + DROP TEMPORARY TABLE tmp.coste; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -71011,7 +71013,7 @@ BEGIN t.companyFk, t.addressFk, tt.agencyModeFk - FROM ticketWeekly tt + FROM ticketWeekly tt JOIN ticket t ON tt.ticketFk = t.id; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; @@ -71025,15 +71027,15 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; FETCH rsTicket INTO vTicketFk, vWeekDay, vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk; IF vIsDone THEN LEAVE myLoop; END IF; - - SELECT dated INTO vShipment + + SELECT dated INTO vShipment FROM `time` WHERE `year` = vYear AND `week` = vWeek AND WEEKDAY(dated) = vWeekDay; @@ -71044,17 +71046,17 @@ BEGIN JOIN saleCloned sc ON sc.saleOriginalFk = saleOrig.id JOIN sale saleClon ON saleClon.id = sc.saleClonedFk JOIN ticket tClon ON tClon.id = saleClon.ticketFk - WHERE tOrig.id = vTicketFk - AND tClon.isDeleted = FALSE + WHERE tOrig.id = vTicketFk + AND tClon.isDeleted = FALSE AND DATE(tClon.shipped) = vShipment) THEN ITERATE myLoop; END IF; IF vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk + SELECT agencyModeFk INTO vAgencyModeFk FROM address - WHERE clientFk = vClientFk + WHERE clientFk = vClientFk AND isDefaultAddress; END IF; @@ -71075,8 +71077,8 @@ BEGIN FALSE, vNewTicket); - UPDATE ticket - SET clonedFrom = vTicketFk + UPDATE ticket + SET clonedFrom = vTicketFk WHERE id = vNewTicket; INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, @@ -71095,7 +71097,7 @@ BEGIN INSERT IGNORE INTO saleCloned(saleOriginalFk, saleClonedFk) SELECT saleOriginal.id, saleClon.id FROM sale saleOriginal - JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk + JOIN sale saleClon ON saleOriginal.itemFk = saleClon.itemFk AND saleOriginal.quantity = saleClon.quantity WHERE saleOriginal.ticketFk = vTicketFk AND saleClon.ticketFk = vNewTicket; @@ -71125,7 +71127,7 @@ BEGIN buyed, requesterFk, attenderFk, - vNewTicket + vNewTicket FROM ticketRequest WHERE ticketFk =vTicketFk; @@ -71140,26 +71142,26 @@ BEGIN INSERT INTO ticketObservation( ticketFk, observationTypeFk, - description) + description) VALUES( vNewTicket, vSalesPersonFK, CONCAT('turno desde ticket: ',vTicketFk)) - ON DUPLICATE KEY UPDATE description = + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); INSERT INTO ticketObservation(ticketFk, observationTypeFk, - description) + description) VALUES( vNewTicket, vItemPicker, 'ATENCION: Contiene lineas de TURNO') - ON DUPLICATE KEY UPDATE description = + ON DUPLICATE KEY UPDATE description = CONCAT(ticketObservation.description,VALUES(description),' '); IF (vLanding IS NULL) THEN - + SELECT e.email INTO vSalesPersonEmail FROM client c JOIN account.emailUser e ON e.userFk = c.salesPersonFk @@ -71167,8 +71169,8 @@ BEGIN SET vSubject = CONCAT('Turnos - No se ha podido clonar correctamente el ticket ', vTicketFk,' para el dia: ', vShipment); - SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, - ' para el dia: ', vShipment, + SET vMessage = CONCAT('No se ha podido clonar el ticket ', vTicketFk, + ' para el dia: ', vShipment, ' porque no hay una zona de envío disponible. Se ha creado el ticket: ', vNewTicket, ' pero ha que revisar las fechas y la agencia'); @@ -71207,7 +71209,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_close`() BEGIN /** - * Realiza el cierre de todos los + * Realiza el cierre de todos los * tickets de la tabla tmp.ticket_close. * * @table tmp.ticket_close(ticketFk) Identificadores de los tickets a cerrar @@ -71225,7 +71227,7 @@ BEGIN DECLARE cur CURSOR FOR SELECT ticketFk FROM tmp.ticket_close; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; @@ -71235,7 +71237,7 @@ BEGIN proc: LOOP SET vDone = FALSE; - + FETCH cur INTO vCurTicketFk; IF vDone THEN @@ -71252,12 +71254,12 @@ BEGIN c.hasToInvoice INTO vClientFk, vIsTaxDataChecked, - vCompanyFk, + vCompanyFk, vShipped, vHasDailyInvoice, vWithPackage, vHasToInvoice - FROM ticket t + FROM ticket t JOIN `client` c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk @@ -71267,22 +71269,22 @@ BEGIN INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) (SELECT vCurTicketFk, p.id, COUNT(*) - FROM expedition e + FROM expedition e JOIN packaging p ON p.itemFk = e.freightItemFk WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable AND vWithPackage GROUP BY p.itemFk); -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) + INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) (SELECT e.freightItemFk, vCurTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.freightItemFk, vClientFk), 1 - FROM expedition e + FROM expedition e JOIN item i ON i.id = e.freightItemFk LEFT JOIN packaging p ON p.itemFk = i.id WHERE e.ticketFk = vCurTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 AND getSpecialPrice(e.freightItemFk, vClientFk) > 0 GROUP BY e.freightItemFk); - + IF(vHasDailyInvoice) AND vHasToInvoice THEN -- Facturacion rapida @@ -71290,10 +71292,10 @@ BEGIN -- Facturar si está contabilizado IF vIsTaxDataChecked THEN CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, + vClientFk, + (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), + vShipped, + vCompanyFk, NULL, NULL, vNewInvoiceId); @@ -71361,25 +71363,25 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentMakeUpdate`( - vTicketFk INT, + vTicketFk INT, vClientFk INT, - vNickname VARCHAR(50), + vNickname VARCHAR(50), vAgencyModeFk INT, - vAddressFk INT, - vZoneFk INT, + vAddressFk INT, + vZoneFk INT, vWarehouseFk INT, - vCompanyFk INT, + vCompanyFk INT, vShipped DATETIME, - vLanded DATE, + vLanded DATE, vIsDeleted BOOLEAN, - vHasToBeUnrouted BOOLEAN, + vHasToBeUnrouted BOOLEAN, vOption INT) BEGIN - + /** * Modifica en el ticket los campos que se le pasan por parámetro * y cambia sus componentes - * + * * @param vTicketFk Id del ticket a modificar * @param vClientFk nuevo cliente * @param vNickname nuevo alias @@ -71394,29 +71396,29 @@ BEGIN * @param vHasToBeUnrouted si se le elimina la ruta al ticket * @param vOption opcion para el case del proc ticketComponentUpdateSale */ - + DECLARE vPrice DECIMAL(10,2); DECLARE vBonus DECIMAL(10,2); CALL ticket_componentPreview (vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); IF (SELECT addressFk FROM ticket WHERE id = vTicketFk) <> vAddressFk THEN - - UPDATE ticket t + + UPDATE ticket t JOIN address a ON a.id = vAddressFk SET t.nickname = a.nickname WHERE t.id = vTicketFk; - + END IF; CALL zone_getShipped(vLanded, vAddressFk, vAgencyModeFk, TRUE); - SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus + SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus FROM tmp.zoneGetShipped WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1; - + UPDATE ticket t - SET + SET t.clientFk = vClientFk, t.nickname = vNickname, t.agencyModeFk = vAgencyModeFk, @@ -71431,12 +71433,12 @@ BEGIN t.isDeleted = vIsDeleted WHERE t.id = vTicketFk; - + IF vHasToBeUnrouted THEN UPDATE ticket t SET t.routeFk = NULL WHERE t.id = vTicketFk; END IF; - + IF vOption <> 8 THEN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -71474,7 +71476,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_componentPreview`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk SMALLINT) @@ -71490,7 +71492,7 @@ BEGIN * * @return tmp.ticketComponentPreview (warehouseFk, itemFk, componentFk, cost) */ - DECLARE vHasDataChanged BOOL DEFAULT FALSE; + DECLARE vHasDataChanged BOOL DEFAULT FALSE; DECLARE vHasAddressChanged BOOL; DECLARE vHasZoneChanged BOOL DEFAULT FALSE; DECLARE vHasWarehouseChanged BOOL DEFAULT FALSE; @@ -71501,8 +71503,8 @@ BEGIN DECLARE vHasChangeAll BOOL DEFAULT FALSE; - SELECT DATE(landed) <> vLanded, - addressFk <> vAddressFk, + SELECT DATE(landed) <> vLanded, + addressFk <> vAddressFk, zoneFk <> vZoneFk, warehouseFk <> vWarehouseFk INTO @@ -71525,15 +71527,15 @@ BEGIN SET vAgencyModeTypeRateFk = 6; END IF; - SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped + SELECT TIMESTAMPADD(DAY, -travelingDays, vLanded) INTO vShipped FROM zone WHERE id = vZoneFk; - + CALL buyUltimate(vWarehouseFk, vShipped); - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( - SELECT + CREATE TEMPORARY TABLE tmp.ticketLot ENGINE = MEMORY ( + SELECT vWarehouseFk AS warehouseFk, NULL AS available, s.itemFk, @@ -71553,9 +71555,9 @@ BEGIN JOIN sale s ON s.id = sc.saleFk JOIN ticket t ON t.id = s.ticketFk JOIN `component` c ON c.id = sc.componentFk - WHERE s.ticketFk = vTicketFk - AND (c.isRenewable = FALSE - OR + WHERE s.ticketFk = vTicketFk + AND (c.isRenewable = FALSE + OR (NOT vHasChangeAll AND (NOT (c.typeFk <=> vAddressTypeRateFk OR c.typeFk <=> vAgencyModeTypeRateFk)))); @@ -71635,52 +71637,52 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) BEGIN - + /* * Splita las lineas de ticket que no estan ubicadas - * + * */ - + DECLARE vNewTicketFk INT; DECLARE vTotalLines INT; DECLARE vLinesToSplit INT; DROP TEMPORARY TABLE IF EXISTS tmp.SalesToSplit; - + SELECT COUNT(*) INTO vTotalLines - FROM vn.sale + FROM vn.sale WHERE ticketFk = vTicketFk; - + CREATE TEMPORARY TABLE tmp.SalesToSplit SELECT s.id saleFk FROM vn.ticket t - JOIN vn.sale s ON t.id = s.ticketFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk + JOIN vn.sale s ON t.id = s.ticketFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = s.itemFk AND issw.warehouseFk = t.warehouseFk WHERE s.quantity > IFNULL(issw.visible, 0) AND s.quantity > 0 AND s.isPicked = FALSE AND s.reserved = FALSE AND t.id = vTicketFk; - + SELECT COUNT(*) INTO vLinesToSplit FROM tmp.SalesToSplit; - + IF vLinesToSplit = vTotalLines AND vLinesToSplit > 0 THEN - + SET vNewTicketFk = vTicketFk; - + ELSE - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE vn.sale s - JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.SalesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + CALL vn.ticketStateUpdate(vNewTicketFk, 'FIXING'); - + DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; @@ -71700,91 +71702,91 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_doCmr`(vSelf INT) -BEGIN -/** -* Crea u actualiza la información del CMR asociado con -* un ticket específico en caso de que sea necesario. -* -* @param vSelf El id del ticket -*/ - DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; - SELECT cmrFk INTO vCmrFk - FROM ticket - WHERE id = vSelf; - - CREATE OR REPLACE TEMPORARY TABLE tTicket - SELECT wo.firstName, - v.numberPlate, - com.id companyFk, - a.id addressFk, - c2.defaultAddressFk, - su.id supplierFk, - t.landed - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN `state` s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN `address` a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - JOIN warehouse w ON w.id = t.warehouseFk - JOIN company com ON com.id = t.companyFk - JOIN client c2 ON c2.id = com.clientFk - JOIN supplierAccount sa ON sa.id = com.supplierAccountFk - JOIN supplier su ON su.id = sa.supplierFk - LEFT JOIN route r ON r.id = t.routeFk - LEFT JOIN worker wo ON wo.id = r.workerFk - LEFT JOIN vehicle v ON v.id = r.vehicleFk - WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE()) - AND al.code IN ('PACKED', 'DELIVERED') - AND co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND dm.code = 'DELIVERY' - AND t.id = vSelf - GROUP BY t.id; - - START TRANSACTION; - - IF vCmrFk THEN - UPDATE cmr c - JOIN tTicket t - SET c.senderInstruccions = t.firstName, - c.truckPlate = t.numberPlate, - c.companyFk = t.companyFk, - c.addressToFk = t.addressFk, - c.addressFromFk = t.defaultAddressFk, - c.supplierFk = t.supplierFk, - c.ead = t.landed - WHERE id = vCmrFk; - ELSE - SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; - - INSERT INTO cmr ( - senderInstruccions, - truckPlate, - companyFk, - addressToFk, - addressFromFk, - supplierFk, - ead - ) - SELECT * FROM tTicket; - - SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; - - IF vPreviousCmrFk <> vCurrentCmrFk THEN - UPDATE ticket - SET cmrFk = vCurrentCmrFk - WHERE id = vSelf; - END IF; - END IF; - - COMMIT; - DROP TEMPORARY TABLE tTicket; +BEGIN +/** +* Crea u actualiza la información del CMR asociado con +* un ticket específico en caso de que sea necesario. +* +* @param vSelf El id del ticket +*/ + DECLARE vCmrFk, vPreviousCmrFk, vCurrentCmrFk INT; + SELECT cmrFk INTO vCmrFk + FROM ticket + WHERE id = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tTicket + SELECT wo.firstName, + v.numberPlate, + com.id companyFk, + a.id addressFk, + c2.defaultAddressFk, + su.id supplierFk, + t.landed + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN `state` s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN `address` a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN warehouse w ON w.id = t.warehouseFk + JOIN company com ON com.id = t.companyFk + JOIN client c2 ON c2.id = com.clientFk + JOIN supplierAccount sa ON sa.id = com.supplierAccountFk + JOIN supplier su ON su.id = sa.supplierFk + LEFT JOIN route r ON r.id = t.routeFk + LEFT JOIN worker wo ON wo.id = r.workerFk + LEFT JOIN vehicle v ON v.id = r.vehicleFk + WHERE t.shipped BETWEEN util.yesterday() AND util.dayEnd(util.VN_CURDATE()) + AND al.code IN ('PACKED', 'DELIVERED') + AND co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND dm.code = 'DELIVERY' + AND t.id = vSelf + GROUP BY t.id; + + START TRANSACTION; + + IF vCmrFk THEN + UPDATE cmr c + JOIN tTicket t + SET c.senderInstruccions = t.firstName, + c.truckPlate = t.numberPlate, + c.companyFk = t.companyFk, + c.addressToFk = t.addressFk, + c.addressFromFk = t.defaultAddressFk, + c.supplierFk = t.supplierFk, + c.ead = t.landed + WHERE id = vCmrFk; + ELSE + SELECT MAX(id) INTO vPreviousCmrFk FROM cmr; + + INSERT INTO cmr ( + senderInstruccions, + truckPlate, + companyFk, + addressToFk, + addressFromFk, + supplierFk, + ead + ) + SELECT * FROM tTicket; + + SELECT MAX(id) INTO vCurrentCmrFk FROM cmr; + + IF vPreviousCmrFk <> vCurrentCmrFk THEN + UPDATE ticket + SET cmrFk = vCurrentCmrFk + WHERE id = vSelf; + END IF; + END IF; + + COMMIT; + DROP TEMPORARY TABLE tTicket; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72017,37 +72019,37 @@ BEGIN * @param vTicketFk -> Ticket * @param vDatedNew -> Nueva fecha * @return Sales con Movible -*/ +*/ DECLARE vDatedOld DATETIME; SET vDatedNew = DATE_ADD(vDatedNew, INTERVAL 1 DAY); SELECT t.shipped INTO vDatedOld - FROM ticket t + FROM ticket t WHERE t.id = vTicketFk; - CALL item_getStock(vWarehouseFk, vDatedNew, NULL); + CALL item_getStock(vWarehouseFk, vDatedNew, NULL); CALL item_getMinacum(vWarehouseFk, vDatedNew, DATEDIFF(DATE_SUB(vDatedOld, INTERVAL 1 DAY), vDatedNew), NULL); - - SELECT s.id, - s.itemFk, - s.quantity, - s.concept, - s.price, + + SELECT s.id, + s.itemFk, + s.quantity, + s.concept, + s.price, s.reserved, - s.discount, - i.image, - i.subName, + s.discount, + i.image, + i.subName, il.stock + IFNULL(im.amount, 0) AS movable FROM ticket t JOIN sale s ON s.ticketFk = t.id - JOIN item i ON i.id = s.itemFk + JOIN item i ON i.id = s.itemFk LEFT JOIN tmp.itemMinacum im ON im.itemFk = s.itemFk AND im.warehouseFk = vWarehouseFk LEFT JOIN tmp.itemList il ON il.itemFk = s.itemFk WHERE t.id = vTicketFk; DROP TEMPORARY TABLE IF EXISTS tmp.itemList; - DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; - + DROP TEMPORARY TABLE IF EXISTS tmp.itemMinacum; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72076,10 +72078,10 @@ BEGIN CALL sale_getProblems(vIsTodayRelative); DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems + CREATE TEMPORARY TABLE tmp.ticket_problems (PRIMARY KEY (ticketFk)) ENGINE = MEMORY - SELECT + SELECT ticketFk, MAX(p.isFreezed) isFreezed, MAX(p.risk) risk, @@ -72097,7 +72099,7 @@ BEGIN GROUP BY ticketFk; UPDATE tmp.ticket_problems tp - SET tp.totalProblems = + SET tp.totalProblems = ( (tp.isFreezed) + IF(tp.risk, TRUE, FALSE) + @@ -72151,17 +72153,17 @@ BEGIN (saleFk INT PRIMARY KEY, ticketFk INT, problem VARCHAR(1)) ENGINE = MEMORY; - + INSERT INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'F' FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = i.id AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) < s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -72171,16 +72173,16 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'I' - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id JOIN vn.item i ON i.id = s.itemFk JOIN vn.itemType it on it.id = i.typeFk JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity AND s.quantity > 0 @@ -72190,7 +72192,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + INSERT IGNORE INTO tmp.salesToSplit(saleFk, ticketFk, problem) SELECT s.id, s.ticketFk, 'R' FROM vn.ticket t @@ -72200,7 +72202,7 @@ BEGIN JOIN vn.itemCategory ic ON ic.id = it.categoryFk LEFT JOIN cache.visible v ON v.item_id = s.itemFk AND v.calc_id = vVisibleCache LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk + LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk WHERE IFNULL(v.visible,0) < s.quantity AND IFNULL(av.available ,0) >= s.quantity AND IFNULL(issw.visible, 0) < s.quantity @@ -72211,7 +72213,7 @@ BEGIN AND t.shipped BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) AND NOT i.generic AND t.warehouseFk = vWarehouseFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketsToSplit; CREATE TEMPORARY TABLE tmp.ticketsToSplit @@ -72232,11 +72234,11 @@ BEGIN JOIN vn.ticket t ON t.id = ss.ticketFk JOIN vn.sale s ON s.id = ss.saleFk JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk GROUP BY ss.ticketFk; - - SELECT - ts.*, + + SELECT + ts.*, t.id ticketFuture, st.name state, zc.`hour` tfEtd, @@ -72245,23 +72247,23 @@ BEGIN FROM tmp.ticketsToSplit ts LEFT JOIN vn.ticketState ts2 ON ts2.ticketFk = ts.ticketFk LEFT JOIN vn.state st ON st.id = ts2.stateFk - LEFT JOIN vn.ticket t - ON t.id != ts.ticketFk + LEFT JOIN vn.ticket t + ON t.id != ts.ticketFk AND t.addressFk = ts.addressFk AND t.shipped BETWEEN vDated AND util.dayend(vDated) LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND zc.dated = vDated LEFT JOIN vn.sale s ON s.ticketFk = t.id LEFT JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id + LEFT JOIN vn.ticketState tst ON tst.ticketFk = t.id LEFT JOIN vn.state st2 ON st2.id = tst.stateFk - WHERE (t.id IS NULL + WHERE (t.id IS NULL OR (vDated > util.VN_CURDATE()) OR (vDated = util.VN_CURDATE() AND vHour >= zc.`hour`)) AND ts.etd <= vHour GROUP BY ts.ticketFk, t.id ORDER BY ts.etd, ts.ticketFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.ticketsToSplit; END ;; DELIMITER ; @@ -72298,7 +72300,7 @@ BEGIN JOIN ticket t ON t.id = tmpTicket.ticketFk; CALL addressTaxArea (); - + IF vTaxArea IS NOT NULL THEN UPDATE tmp.addressTaxArea SET areaFk = vTaxArea; @@ -72370,8 +72372,8 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticketAmount (INDEX (ticketFk)) ENGINE = MEMORY - SELECT ticketFk, - taxableBase, + SELECT ticketFk, + taxableBase, SUM(CAST(taxableBase * rate / 100 AS DECIMAL(10, 2))) tax, code FROM tmp.ticketTax @@ -72451,11 +72453,11 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_getWithParameters`( - vClientFk INT, + vClientFk INT, vWarehouseFk INT, - vShipped DATE, - vAddressFk INT, - vCompanyFk INT, + vShipped DATE, + vAddressFk INT, + vCompanyFk INT, vAgencyModeFk INT, OUT vTicketFk INT ) @@ -72469,8 +72471,8 @@ BEGIN * @param vAddressFk Consignatario * @param vCompanyFk Empresa * @param vAgencyModeFk agencia - */ - + */ + SELECT t.id INTO vTicketFk FROM vn.ticket t WHERE t.clientFk <=> vClientFk @@ -72480,7 +72482,7 @@ BEGIN AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL) AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL) LIMIT 1; - + IF vTicketFk IS NULL THEN CALL vn.ticket_add( vClientFk, @@ -72520,24 +72522,24 @@ BEGIN DECLARE vAddressFk INT; DECLARE vAgencyModeFk INT; DECLARE vWarehouseFk INT; - DECLARE vCursor CURSOR FOR + DECLARE vCursor CURSOR FOR SELECT id, landed, addressFk, agencyModeFk, warehouseFk FROM vn.ticket WHERE shipped > '2020-01-01' AND zoneFk is null; DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET vDone = 1; - + OPEN vCursor; REPEAT FETCH vCursor INTO vFechedTicket, vLanded, vAddressFk, vAgencyModeFk, vWarehouseFk; CALL vn.zone_getShipped (vlanded, vAddressFk, vAgencyModeFk, TRUE); - + UPDATE vn.ticket t JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = vWarehouseFk SET t.zoneFk = zgs.zoneFk WHERE t.id = vFechedTicket; - + UNTIL vDone END REPEAT; DROP TEMPORARY TABLE tmp.zoneGetShipped; - + CLOSE vCursor; END ;; DELIMITER ; @@ -72557,14 +72559,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_priceDifference`( vTicketFk INT, - vLanded DATE, + vLanded DATE, vAddressFk INT, vZoneFk INT, vWarehouseFk INT) BEGIN /** * Devuelve las diferencias de precio de los movimientos de un ticket. - * + * * @param vTicketFk Id del ticket * @param vLanded Fecha de recepcion * @param vAddressFk Id del consignatario @@ -72573,26 +72575,26 @@ BEGIN */ CALL vn.ticket_componentPreview(vTicketFk, vLanded, vAddressFk, vZoneFk, vWarehouseFk); - SELECT s.itemFk, - i.name, - i.size, - i.category, - IFNULL(s.quantity, 0) AS quantity, - IFNULL(s.price, 0) AS price, + SELECT s.itemFk, + i.name, + i.size, + i.category, + IFNULL(s.quantity, 0) AS quantity, + IFNULL(s.price, 0) AS price, ROUND(SUM(tc.cost), 2) AS newPrice, s.quantity * (s.price - ROUND(SUM(tc.cost), 2)) difference, s.id AS saleFk FROM sale s - JOIN item i ON i.id = s.itemFk - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk + JOIN item i ON i.id = s.itemFk + JOIN ticket t ON t.id = s.ticketFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk AND tc.warehouseFk = vWarehouseFk - LEFT JOIN saleComponent sc ON sc.saleFk = s.id + LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk - LEFT JOIN `component` c ON c.id = tc.componentFk - WHERE t.id = vTicketFk - AND IF(sc.componentFk IS NULL - AND c.classRate IS NOT NULL, FALSE, TRUE) + LEFT JOIN `component` c ON c.id = tc.componentFk + WHERE t.id = vTicketFk + AND IF(sc.componentFk IS NULL + AND c.classRate IS NOT NULL, FALSE, TRUE) GROUP BY s.id ORDER BY s.id; DROP TEMPORARY TABLE tmp.ticketComponentPreview; @@ -72615,7 +72617,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_printLabelPrevious`(vTicketFk INT) BEGIN /** - * Calls the report_print procedure and passes it + * Calls the report_print procedure and passes it * the necessary parameters for printing. * * @param vTicketFk id ticket to print. @@ -72623,18 +72625,18 @@ BEGIN DECLARE vPrinterFk INT; DECLARE vSaleGroup INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + SELECT sg.id, o.labelerFk INTO vSaleGroup, vPrinterFk FROM saleGroup sg JOIN sector sc ON sc.id = sg.sectorFk - JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk + JOIN saleGroupDetail sgd ON sg.id = sgd.saleGroupFk JOIN sale s ON sgd.saleFk = s.id JOIN ticket t ON s.ticketFk = t.id JOIN operator o ON o.workerFk = vUserFk - WHERE sc.id = o.sectorFk + WHERE sc.id = o.sectorFk AND t.id = vTicketFk LIMIT 1; - + CALL report_print( 'LabelPrevia', vPrinterFk, @@ -72668,12 +72670,12 @@ proc:BEGIN */ DECLARE hasInvoice BOOL; - SELECT COUNT(*) INTO hasInvoice - FROM ticket + SELECT COUNT(*) INTO hasInvoice + FROM ticket WHERE id = vSelf AND refFk IS NOT NULL; - - IF hasInvoice THEN + + IF hasInvoice THEN LEAVE proc; END IF; @@ -72907,62 +72909,62 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_setState`(vSelf INT, vStateCode VARCHAR(255) COLLATE utf8_general_ci) -BEGIN -/** - * Modifica el estado de un ticket si se cumplen las condiciones necesarias. - * - * @param vSelf el id del ticket - * @param vStateCode estado a modificar del ticket - */ - DECLARE vticketAlertLevel INT; - DECLARE vTicketStateCode VARCHAR(255); - DECLARE vCanChangeState BOOL; - DECLARE vPackedAlertLevel INT; - DECLARE vOnPreparationAlertLevel INT; - DECLARE vNextAlertLevel INT; - DECLARE vZoneFk INT; - - SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk - INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk - FROM state s - JOIN ticketTracking tt ON tt.stateFk = s.id - JOIN state s2 ON s2.code = vStateCode - JOIN ticket t ON t.id = tt.ticketFk - WHERE tt.ticketFk = vSelf - ORDER BY tt.created DESC - LIMIT 1; - - SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; - SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; - - IF vStateCode = 'OK' AND vZoneFk IS NULL THEN - CALL util.throw('ASSIGN_ZONE_FIRST'); - END IF; - - IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN - UPDATE sale - SET originalQuantity = quantity - WHERE ticketFk = vSelf; - END IF; - - SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) - AND NOT ( - vTicketStateCode IN ('CHECKED', 'CHECKING') - AND vStateCode IN ('PREPARED', 'ON_PREPARATION') - ); - - IF vCanChangeState THEN - INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) - SELECT id, vSelf, account.myUser_getId() - FROM state - WHERE `code` = vStateCode COLLATE utf8_unicode_ci; - - IF vStateCode = 'PACKED' THEN - CALL ticket_doCmr(vSelf); - END IF; - ELSE - CALL util.throw('INCORRECT_TICKET_STATE'); - END IF; +BEGIN +/** + * Modifica el estado de un ticket si se cumplen las condiciones necesarias. + * + * @param vSelf el id del ticket + * @param vStateCode estado a modificar del ticket + */ + DECLARE vticketAlertLevel INT; + DECLARE vTicketStateCode VARCHAR(255); + DECLARE vCanChangeState BOOL; + DECLARE vPackedAlertLevel INT; + DECLARE vOnPreparationAlertLevel INT; + DECLARE vNextAlertLevel INT; + DECLARE vZoneFk INT; + + SELECT s.alertLevel, s.`code`, s2.alertLevel, t.zoneFk + INTO vticketAlertLevel, vTicketStateCode, vNextAlertLevel , vZoneFk + FROM state s + JOIN ticketTracking tt ON tt.stateFk = s.id + JOIN state s2 ON s2.code = vStateCode + JOIN ticket t ON t.id = tt.ticketFk + WHERE tt.ticketFk = vSelf + ORDER BY tt.created DESC + LIMIT 1; + + SELECT id INTO vPackedAlertLevel FROM alertLevel WHERE code = 'PACKED'; + SELECT id INTO vOnPreparationAlertLevel FROM alertLevel WHERE code = 'ON_PREPARATION'; + + IF vStateCode = 'OK' AND vZoneFk IS NULL THEN + CALL util.throw('ASSIGN_ZONE_FIRST'); + END IF; + + IF vNextAlertLevel > vticketAlertLevel && vticketAlertLevel < vOnPreparationAlertLevel THEN + UPDATE sale + SET originalQuantity = quantity + WHERE ticketFk = vSelf; + END IF; + + SET vCanChangeState = (vStateCode <> 'ON_CHECKING' OR vticketAlertLevel < vPackedAlertLevel) + AND NOT ( + vTicketStateCode IN ('CHECKED', 'CHECKING') + AND vStateCode IN ('PREPARED', 'ON_PREPARATION') + ); + + IF vCanChangeState THEN + INSERT INTO ticketTracking (stateFk, ticketFk, workerFk) + SELECT id, vSelf, account.myUser_getId() + FROM state + WHERE `code` = vStateCode COLLATE utf8_unicode_ci; + + IF vStateCode = 'PACKED' THEN + CALL ticket_doCmr(vSelf); + END IF; + ELSE + CALL util.throw('INCORRECT_TICKET_STATE'); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -72996,40 +72998,40 @@ proc:BEGIN SELECT COUNT(*) INTO vProblemLines FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - + SELECT count(*) INTO vTotalLines - FROM vn.sale s + FROM vn.sale s WHERE s.ticketFk = vTicketFk; - + SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - + UPDATE vn.ticket SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) WHERE id = vTicketFk; - + SELECT CONCAT("Se ha cambiado el ticket ", vTicketFk, " al dia ", vDated); LEAVE proc; - + END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s + + UPDATE vn.sale s JOIN tmp.salesToSplit ss ON s.id = ss.saleFk SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE ss.ticketFk = vTicketFk; - - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al ticket existente ", vTicketFutureFk,"(", vDated,")"); LEAVE proc; - + END IF; -- Ticket nuevo @@ -73041,18 +73043,18 @@ proc:BEGIN t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, - t.zoneFk = pc.defaultZone + t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE vn.sale s + JOIN tmp.salesToSplit sts ON sts.saleFk = s.id SET s.ticketFk = vTicketFutureFk, s.concept = CONCAT('(s) ', s.concept) WHERE sts.ticketFk = vTicketFk; CALL vn.ticketStateUpdate(vTicketFutureFk, 'FIXING'); - SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, + SELECT CONCAT("Se han movido lineas del ticket ", vTicketFk, " al nuevo ticket ", vTicketFutureFk,"(", vDated,")"); END ;; DELIMITER ; @@ -73191,43 +73193,43 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitPackingComplete`(vTicketFk INT, vSectorFk INT) BEGIN - + DECLARE vNeedToSplit BOOLEAN; DECLARE vNewTicketFk INT; - + DROP TEMPORARY TABLE IF EXISTS tmpSale; - + CREATE TEMPORARY TABLE tmpSale SELECT DISTINCT s.id - FROM vn.ticket t + FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk + JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = s.itemFk AND iss.sectorFk = vSectorFk - JOIN vn.packagingConfig pc + JOIN vn.packagingConfig pc WHERE t.id = vTicketFk AND ( s.quantity MOD IFNULL(iss.packing,1) != 0 - OR + OR IFNULL(iss.packing,1) = 1 - OR + OR i.`size` <= pc.previousPreparationMinimumSize ); - - SELECT COUNT(*) + + SELECT COUNT(*) INTO vNeedToSplit - FROM tmpSale; - + FROM tmpSale; + IF vNeedToSplit THEN - + CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - + UPDATE vn.sale s - JOIN vn.tmpSale ts ON ts.id = s.id + JOIN vn.tmpSale ts ON ts.id = s.id SET s.ticketFk = vNewTicketFk; - + END IF; - + DROP TEMPORARY TABLE tmpSale; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73258,7 +73260,7 @@ BEGIN WHERE ot.description = 'Peso Aduana' AND t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SELECT sum(IF(sv.physicalWeight = 0, sv.weight, sv.physicalWeight)) INTO vTheorycalWeight FROM vn.ticket t JOIN vn.sale s ON s.ticketFk = t.id @@ -73267,9 +73269,9 @@ BEGIN JOIN vn.itemCost ic ON ic.itemFk = i.id AND ic.warehouseFk = t.warehouseFk WHERE t.clientFk = vClientFk AND t.shipped BETWEEN vDated AND util.dayend(vDated); - + SET vRatio = vRealWeight / vTheorycalWeight; - + DROP TEMPORARY TABLE IF EXISTS tmp.ticketWeight; CREATE TEMPORARY TABLE tmp.ticketWeight @@ -73290,7 +73292,7 @@ BEGIN AND t.shipped BETWEEN vDated AND util.dayend(vDated) GROUP BY ib.ediBotanic, o.code; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73410,18 +73412,18 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateAll`(vDatedFr BEGIN /** - * @param vDatedFrom Fecha desde + * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta */ - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM vn.worker w; - + CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73441,21 +73443,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73480,19 +73482,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeBusiness_calculateByUser`(vUser BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73519,14 +73521,14 @@ BEGIN * @param vDatedFrom Fecha desde * @param vDatedTo Fecha hasta */ - - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM worker w WHERE w.id = vWorkerFk; - + CALL timeBusiness_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73546,30 +73548,30 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculate`( - vDatedFrom DATETIME, + vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /* * @param vDatedFrom - * @param vDatedTo - * Cálculo de horas trabajadas por empleado y día, + * @param vDatedTo + * Cálculo de horas trabajadas por empleado y día, * sin tener en cuenta los días con fichadas incorrectas (tabla tmp.timeControlError) - * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), + * En el caso de haber hecho descanso y trabajado un mínimo de tiempo (vTimeToBreakTime), * se añade al tiempo de trabajo efectivo el descanso (vBreakTime) - * @return tmp.timeControlCalculate + * @return tmp.timeControlCalculate * (workerFk, dated, timeWorkSeconds, timeWorkSexagesimal, timeWorkDecimal, timed) */ DECLARE vHourToSeconds INTEGER; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; + DECLARE vDatedToTomorrow DATETIME; DECLARE vTimeToBreakTime INT; DECLARE vBreakTime INT; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; - + SELECT timeToBreakTime, breakTime INTO vTimeToBreakTime, vBreakTime - FROM workerTimeControlConfig + FROM workerTimeControlConfig LIMIT 1; CALL timeControl_getError(vDatedFrom, vDatedTo); @@ -73578,9 +73580,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction, TRUE isReal FROM workerTimeControl wtc @@ -73590,10 +73592,10 @@ BEGIN AND tce.id IS NULL ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -73606,14 +73608,14 @@ BEGIN -- Cambio de dia en medio de un descanso INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - userFk, - util.dayEnd(dated) timed, + SELECT @vCont:= @vCont + 1 id, + userFk, + util.dayEnd(dated) timed, 'middle' direction FROM(SELECT wtc.userFk, DATE(@lastTimed) dated, (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' + IF(@vIsOdd AND wtc.direction = 'middle' AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed FROM tmp.workerTimeControl wtc @@ -73626,14 +73628,14 @@ BEGIN SET @vIsOdd := FALSE; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - userFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + userFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM(SELECT wtc.userFk, DATE(@lastTimed) dated, (@vIsOdd := NOT @vIsOdd) isOdd, - IF(@vIsOdd AND wtc.direction = 'middle' + IF(@vIsOdd AND wtc.direction = 'middle' AND DATE(timed) <> DATE(@lastTimed), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed FROM tmp.workerTimeControl wtc @@ -73644,9 +73646,9 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1 id, - sub.userFk, - util.dayEnd(sub.dated) timed, + SELECT @vCont:= @vCont + 1 id, + sub.userFk, + util.dayEnd(sub.dated) timed, 'out' direction FROM (SELECT MAX(wtc.timed) timed, wtc.userFk, date(wtc.timed) dated FROM workerTimeControl wtc @@ -73656,7 +73658,7 @@ BEGIN AND tce.id IS NULL GROUP BY wtc.userFk, DATE(wtc.timed) ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed + JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed AND wtc.userFk = sub.userFk WHERE wtc.direction <> 'out'; @@ -73670,7 +73672,7 @@ BEGIN AND tce.id IS NULL GROUP BY wtc.userFk, DATE(wtc.timed) ) sub - JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed + JOIN tmp.workerTimeControl wtc ON wtc.timed = sub.timed AND wtc.userFk = sub.userFk WHERE wtc.direction <> 'out'; @@ -73687,7 +73689,7 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerBreakDays (INDEX (userFk), INDEX (dated)) ENGINE = MEMORY - SELECT sub.userFk, + SELECT sub.userFk, sub.dated FROM (SELECT (@vIsOdd := NOT @vIsOdd), IF(wtc.direction = 'in', @vIsOdd := TRUE, NULL), @@ -73696,7 +73698,7 @@ BEGIN IF(direction='in', @vDated := DATE(wtc.timed), @vDated) dated, wtc.userFk FROM tmp.workerTimeControl wtc - ORDER BY wtc.userFk, wtc.timed, wtc.id + ORDER BY wtc.userFk, wtc.timed, wtc.id LIMIT 10000000000000000000 )sub GROUP BY sub.userFk, sub.dated @@ -73707,9 +73709,9 @@ BEGIN SET @vLastTimed := 0; DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux2; - CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 + CREATE TEMPORARY TABLE tmp.workerTimeControlAux2 SELECT * - FROM tmp.workerTimeControl + FROM tmp.workerTimeControl WHERE timed BETWEEN vDatedFromYesterday AND vDatedTo ORDER BY userFk, timed, id; @@ -73722,7 +73724,7 @@ BEGIN IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork) timeWorkSeconds, SEC_TO_TIME(IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) timeWorkSexagesimal, (IF(wb.userFk, vBreakTime, 0) + SUM(sub.timeWork)) / vHourToSeconds timeWorkDecimal, - CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") + CAST(GROUP_CONCAT(DATE_FORMAT(sub.realTimed, "%H:%i") ORDER BY sub.timed ASC SEPARATOR ' - ') AS CHAR(256)) timed FROM (SELECT (@vIsOdd := NOT @vIsOdd), IF(direction='in', @vIsOdd := TRUE, 0), @@ -73767,14 +73769,14 @@ BEGIN * @param vDatedTo Fecha hasta */ - CREATE OR REPLACE TEMPORARY TABLE tmp.`user` + CREATE OR REPLACE TEMPORARY TABLE tmp.`user` SELECT w.id userFk FROM vn.worker w; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73794,21 +73796,21 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByDepartment`(vDepartmentFk INT, vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN /** - * @param vDepartmentFk + * @param vDepartmentFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT DISTINCT b.workerFk userFk - FROM business AS b - WHERE (b.started BETWEEN vDatedFrom AND vDatedTo + FROM business AS b + WHERE (b.started BETWEEN vDatedFrom AND vDatedTo OR IFNULL(b.ended, vDatedTo) BETWEEN vDatedFrom AND vDatedTo OR (b.started <= vDatedFrom AND b.ended >= vDatedTo) ) AND b.departmentFk = vDepartmentFk ORDER BY b.ended DESC; - + CALL timeControl_calculate(vDatedFrom, vDatedTo); DROP TEMPORARY TABLE tmp.`user`; @@ -73833,19 +73835,19 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByUser`(vUserF BEGIN /** - * @param vUserFk + * @param vUserFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk - FROM account.user - WHERE id = vUserFk; + FROM account.user + WHERE id = vUserFk; CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73868,21 +73870,21 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_calculateByWorker`(vWor BEGIN /** - * @param vWorkerFk + * @param vWorkerFk * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl */ - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; - + CREATE TEMPORARY TABLE tmp.`user` SELECT u.id userFk FROM account.user u JOIN vn.worker w ON w.userFk = u.id WHERE w.id = vWorkerFk; - + CALL vn.timeControl_calculate(vDatedFrom, vDatedTo); - + DROP TEMPORARY TABLE tmp.`user`; END ;; @@ -73905,12 +73907,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `timeControl_getError`(vDatedFrom DA BEGIN /* * @param vDatedFrom - * @param vDatedTo + * @param vDatedTo * @table tmp.`user`(userFk) * Fichadas incorrectas de las cuales no se puede calcular horas trabajadas * @return tmp.timeControlError (id) */ - DECLARE vDayMaxTime INTEGER; + DECLARE vDayMaxTime INTEGER; SET @journeyCounter := 0; SET @lastUserFk := NULL; @@ -73918,16 +73920,16 @@ BEGIN SELECT dayMaxTime INTO vDayMaxTime FROM workerTimeControlConfig LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - CREATE TEMPORARY TABLE tmp.timeControl + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + CREATE TEMPORARY TABLE tmp.timeControl (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT sub.id, - sub.direction, + sub.direction, sub.timed, IF(sub.direction = 'in' OR @hasOut OR sub.userFk <> @lastUserFk, @journeyCounter := @journeyCounter + 1, @journeyCounter) journeyCounter, - @lastUserFk := sub.userFk workerFk, - IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) + @lastUserFk := sub.userFk workerFk, + IF(sub.direction = 'out', @hasOut:= TRUE, @hasOut:= FALSE) FROM ( SELECT DISTINCT wtc.id, wtc.direction, @@ -73938,36 +73940,36 @@ BEGIN WHERE wtc.timed BETWEEN DATE_SUB(vDatedFrom, INTERVAL 1 DAY) AND DATE_ADD(vDatedTo, INTERVAL 1 DAY) ORDER BY wtc.userFk, wtc.timed ) sub; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; CREATE TEMPORARY TABLE tmp.timeControlAux (INDEX(id), INDEX(journeyCounter)) ENGINE = MEMORY SELECT * FROM tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; - CREATE TEMPORARY TABLE tmp.timeControlError + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlError; + CREATE TEMPORARY TABLE tmp.timeControlError (INDEX(id)) ENGINE = MEMORY - SELECT id + SELECT id FROM tmp.timeControlAux tca JOIN ( - SELECT journeyCounter, + SELECT journeyCounter, UNIX_TIMESTAMP(MAX(timed)) - UNIX_TIMESTAMP(MIN(timed)) timeWork, - SUM(direction = 'in') totalIn, + SUM(direction = 'in') totalIn, SUM(direction = 'out') totalOut, timed FROM tmp.timeControl GROUP BY journeyCounter - HAVING COUNT(*) MOD 2 = 1 - OR totalIn <> 1 - OR totalOut <> 1 + HAVING COUNT(*) MOD 2 = 1 + OR totalIn <> 1 + OR totalOut <> 1 OR timeWork >= vDayMaxTime )sub ON sub.journeyCounter = tca.journeyCounter WHERE sub.timed BETWEEN vDatedFrom AND vDatedTo; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControl; + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlAux; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -73990,7 +73992,7 @@ proc: BEGIN * deprecated call workerTimeControl_check */ CALL vn.workerTimeControl_check(vUserFk,vDated,vTabletFk); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74046,12 +74048,12 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travelVolume`(vTravelFk INT) BEGIN - - SELECT w1.name AS ORI, - w2.name AS DES, + + SELECT w1.name AS ORI, + w2.name AS DES, tr.shipped shipment, tr.landed landing, - a.name Agencia, + a.name Agencia, s.name Proveedor, e.id Id_Entrada, e.invoiceNumber Referencia, @@ -74059,18 +74061,18 @@ BEGIN vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.trolleyM3 / 1000000 ,1) AS DECIMAL(10,2)) AS CC, CAST(ROUND(SUM(GREATEST(b.stickers ,b.quantity /b.packing ) * vn.item_getVolume(b.itemFk ,b.packageFk)) / vc.palletM3 / 1000000,1) AS DECIMAL(10,2)) AS espais - FROM vn.buy b - JOIN vn.entry e ON e.id = b.entryFk - JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.travel tr ON tr.id = e.travelFk + FROM vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.supplier s ON s.id = e.supplierFk + JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.agencyMode a ON a.id = tr.agencyModeFk - JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk - JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk - JOIN vn.volumeConfig vc - JOIN vn.item i ON i.id = b.itemFk + JOIN vn.warehouse w1 ON w1.id = tr.warehouseInFk + JOIN vn.warehouse w2 ON w2.id = tr.warehouseOutFk + JOIN vn.volumeConfig vc + JOIN vn.item i ON i.id = b.itemFk JOIN vn.itemType it ON it.id = i.typeFk WHERE tr.id = vTravelFk; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74126,11 +74128,11 @@ BEGIN * @param vShipped The shipment date * @param vLanded The landing date */ - + IF vLanded < vShipped THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Landing cannot be lesser than shipment'; - END IF; + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -74194,7 +74196,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_checkWarehouseIsFeedStock`(v proc: BEGIN /* * Check that the warehouse is not Feed Stock - * + * * @vWarehouseFk param warehouse id */ IF vWarehouseFk IS NULL THEN @@ -74282,13 +74284,13 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `travel_cloneWithEntries`( - IN vTravelFk INT, - IN vDateStart DATE, + IN vTravelFk INT, + IN vDateStart DATE, IN vDateEnd DATE, IN vWarehouseOutFk INT, - IN vWarehouseInFk INT, - IN vRef VARCHAR(255), - IN vAgencyModeFk INT, + IN vWarehouseInFk INT, + IN vRef VARCHAR(255), + IN vAgencyModeFk INT, OUT vNewTravelFk INT) BEGIN /** @@ -74312,29 +74314,29 @@ BEGIN FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.travelFk = vTravelFk; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN + BEGIN ROLLBACK; RESIGNAL; END; - + START TRANSACTION; INSERT INTO travel (shipped, landed, warehouseInFk, warehouseOutFk, agencyModeFk, `ref`, isDelivered, isReceived, m3, cargoSupplierFk, kg,clonedFrom) SELECT vDateStart, vDateEnd, vWarehouseInFk, vWarehouseOutFk, vAgencyModeFk, vRef, isDelivered, isReceived, m3,cargoSupplierFk, kg,vTravelFk FROM travel WHERE id = vTravelFk; - + SET vNewTravelFk = LAST_INSERT_ID(); SET vDone = FALSE; SET @isModeInventory = TRUE; OPEN vRsEntry; - + l: LOOP SET vDone = FALSE; FETCH vRsEntry INTO vAuxEntryFk; @@ -74403,11 +74405,11 @@ BEGIN SELECT COUNT(*) INTO vTotalEntries FROM entry WHERE travelFk = vTravelFk; - + UPDATE travel SET totalEntries = vTotalEntries WHERE id = vTravelFk; - + DELETE FROM travelRecalc WHERE travelFk = vTravelFk; END LOOP; @@ -74438,10 +74440,10 @@ BEGIN WHERE id = vSelf; SELECT e.id entryFk - FROM travel t - JOIN entry e ON e.travelFk = t.id - JOIN buy b ON b.entryFk = e.id - WHERE t.id = vTravelFk + FROM travel t + JOIN entry e ON e.travelFk = t.id + JOIN buy b ON b.entryFk = e.id + WHERE t.id = vTravelFk AND (b.packing IS NULL OR b.packageFk IS NULL); END ;; DELIMITER ; @@ -74464,7 +74466,7 @@ BEGIN /* * Desplaza al dia siguiente los travels que contengan redadas y avisa a los compradores - * + * */ DECLARE vDone BOOL DEFAULT FALSE; DECLARE vWorkerName VARCHAR(50); @@ -74476,7 +74478,7 @@ BEGIN SELECT GROUP_CONCAT( DISTINCT CONCAT('https://salix.verdnatura.es/#!/travel/', ttr.id, '/summary ') ORDER BY ttr.id SEPARATOR '\n\r'), u.name FROM tmp.travel ttr - JOIN entry e ON e.travelFk = ttr.id + JOIN entry e ON e.travelFk = ttr.id JOIN buy b ON b.entryFk = e.id JOIN item i ON i.id = b.itemFk JOIN itemType it ON it.id = i.typeFk @@ -74484,19 +74486,19 @@ BEGIN GROUP BY u.name; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; + SET vDone = TRUE; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN ROLLBACK; RESIGNAL; END; - + DROP TEMPORARY TABLE IF EXISTS tmp.travel; CREATE TEMPORARY TABLE tmp.travel SELECT tr.id,tr.landed FROM travel tr - JOIN entry e ON e.travelFk = tr.id + JOIN entry e ON e.travelFk = tr.id WHERE tr.landed = util.tomorrow() AND e.isRaid GROUP BY tr.id; @@ -74554,7 +74556,7 @@ proc: BEGIN IF vSelf IS NULL THEN LEAVE proc; END IF; - + INSERT IGNORE INTO travelRecalc SET travelFk = vSelf; END ;; DELIMITER ; @@ -74580,10 +74582,10 @@ BEGIN * @param vItemFk id del item * @param vPacking nuevo packing */ - + DECLARE vAuctionWarehouseFk INT; DECLARE vMainWarehouseFk INT; - + SELECT warehouseFk INTO vAuctionWarehouseFk FROM auctionConfig; @@ -74643,7 +74645,7 @@ BEGIN FROM travelClonedWeekly WHERE travelFk; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; SET vCounter = vSinceWeek; @@ -74705,12 +74707,12 @@ BEGIN /* * Plantilla para modificar reemplazar todos los tags * por los valores que tienen los articulos - * + * * @param vTypeFk tipo a modificar - * + * */ - DELETE it.* - FROM itemTag it + DELETE it.* + FROM itemTag it JOIN item i ON i.id = it.itemFk WHERE i.typeFk = vTypeFk; @@ -74719,40 +74721,40 @@ BEGIN FROM item i JOIN tag t ON t.name = 'Longitud' COLLATE utf8_general_ci WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, i.category, 5 FROM item i JOIN tag t ON t.name = 'Categoria' COLLATE utf8_general_ci WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, ink.name, 2 FROM item i JOIN tag t ON t.name = 'Color' COLLATE utf8_general_ci JOIN ink ON ink.id = i.inkFk WHERE i.typeFk = vTypeFk; - + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, p.name, 3 FROM item i JOIN tag t ON t.name = 'Productor' COLLATE utf8_general_ci JOIN producer p ON p.id = i.producerFk - WHERE i.typeFk = vTypeFk; - + WHERE i.typeFk = vTypeFk; + INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, o.name, 4 FROM item i JOIN tag t ON t.name = 'Origen' COLLATE utf8_general_ci JOIN origin o ON o.id = i.originFk WHERE i.typeFk = vTypeFk; - /* + /* INSERT INTO itemTag(itemFk, tagFk, value, priority) SELECT i.id, t.id, i.stems, 6 FROM item i JOIN tag t ON t.name = 'Tallos' COLLATE utf8_general_ci - WHERE i.typeFk = vTypeFk; - */ + WHERE i.typeFk = vTypeFk; + */ -- CALL itemTagArrangedUpdate(NULL); END ;; @@ -74775,7 +74777,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `updatePedidosInternos`(vItemFk INT) BEGIN UPDATE vn.item SET upToDown = 0 WHERE item.id = vItemFk; - + END ;; DELIMITER ; @@ -74803,7 +74805,7 @@ BEGIN SELECT vp.regex INTO vRegex FROM vehiclePlateRegex vp WHERE vp.countryCodeFk = vCountryCodeFk; - + IF NOT vNumberPlate REGEXP BINARY (vRegex)THEN CALL util.throw(CONCAT('Error: la matricula ', vNumberPlate, ' no es valida para ',vCountryCodeFk)); END IF; @@ -74836,7 +74838,7 @@ proc:BEGIN ROLLBACK; RESIGNAL; END; - + SELECT eventEarlyDays INTO vEventEarlyDays FROM vehicleConfig; @@ -74854,7 +74856,7 @@ proc:BEGIN IF NOT vHasEvents THEN LEAVE proc; END IF; - + START TRANSACTION; SELECT util.notification_send('vehicle-event-expired', @@ -74889,21 +74891,21 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `visible_getMisfit`(vSectorFk INT) BEGIN - + /* Devuelve una tabla temporal con los descuadres entre el visible teórico y lo ubicado en la práctica - * + * * @param vSectorFk Identificador de vn.sector - * + * * @return tmp.stockMisfit(itemFk, visible, parked) */ - + DECLARE vCalcVisibleFk INT; DECLARE vWarehouseFk INT; SELECT warehouseFk INTO vWarehouseFk - FROM vn.sector s + FROM vn.sector s WHERE s.id = vSectorFk; - + CALL cache.visible_refresh(vCalcVisibleFk, FALSE, vWarehouseFk); DROP TEMPORARY TABLE IF EXISTS tmp.stockMisfit; @@ -74916,17 +74918,17 @@ BEGIN INSERT INTO tmp.stockMisfit(itemFk, parked) SELECT iss.itemFk , sum(iss.visible ) - FROM vn.itemShelvingStock iss - JOIN vn.sector s ON s.id = iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk WHERE vSectorFk IN (s.id, s.sonFk) GROUP BY iss.itemFk; - + INSERT INTO tmp.stockMisfit(itemFk, visible) - SELECT v.item_id , v.visible - FROM cache.visible v - WHERE v.calc_id = vCalcVisibleFk + SELECT v.item_id , v.visible + FROM cache.visible v + WHERE v.calc_id = vCalcVisibleFk ON DUPLICATE KEY UPDATE visible = v.visible; - + DELETE FROM tmp.stockMisfit WHERE visible = parked; @@ -74950,17 +74952,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `warehouseFitting`(IN vWhOrigin INT BEGIN DECLARE vCacheVisibleOriginFk INT; DECLARE vCacheVisibleDestinyFk INT; - + CALL cache.visible_refresh(vCacheVisibleOriginFk, FALSE, vWhOrigin); CALL cache.visible_refresh(vCacheVisibleDestinyFk, FALSE, vWhDestiny); - + SELECT i.id itemFk, i.longName, i.size, i.subName, vOrigin.visible AS Origen, vDestiny.visible Destino - + FROM vn.item i JOIN vn.itemType it ON it.id = i.typeFk LEFT JOIN cache.visible vOrigin ON vOrigin.calc_id = vCacheVisibleOriginFk AND vOrigin.item_id = i.id @@ -74989,13 +74991,13 @@ BEGIN DECLARE vWhOrigin INT; DECLARE vWhDestiny INT; - + SELECT warehouseInFk, warehouseOutFk INTO vWhDestiny, vWhOrigin FROM vn.travel WHERE id = vTravelFk; - + CALL vn.warehouseFitting(vWhOrigin, vWhDestiny); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75059,7 +75061,7 @@ BEGIN * Calcula los días y horas de vacaciones en función de un contrato y año * * @param vYear - * @param vBusinessFk + * @param vBusinessFk * @return tmp.workerCalendarCalculateBusiness (days, hours, daysEnjoyed, hoursEnjoyed) */ DECLARE vStarted DATE; @@ -75071,17 +75073,17 @@ BEGIN DECLARE vPayedHolidays DECIMAL(5,2); DECLARE vDifDays INT; - SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), - IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), + SELECT IF(b.started < CONCAT(vYear,"-01-01"), CONCAT(vYear,"-01-01"),b.started), + IF(b.ended IS NULL OR YEAR(b.ended)>vYear , CONCAT(vYear,"-12-31"), b.ended), IF(wbt.hasHolidayEntitlement, w.days, 0), c.hoursWeek, IF(YEAR(b.ended) = vYear, b.payedHolidays, 0) payedHolidays - INTO vStarted, - vEnded, - vDaysHoliday, + INTO vStarted, + vEnded, + vDaysHoliday, vHoursWeek, vPayedHolidays - FROM business b + FROM business b JOIN workerBusinessType wbt ON wbt.id = b.workerBusinessTypeFk JOIN workCenterHoliday w ON w.workcenterFk = b.workcenterFk LEFT JOIN calendarType c ON c.id = b.calendarTypeFk @@ -75089,23 +75091,23 @@ BEGIN AND w.year = vYear; DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateBusiness; - + IF vStarted < vEnded THEN SET vDifDays = DAYOFYEAR(vEnded) - DAYOFYEAR(vStarted) + 1; - SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), + SELECT IFNULL(SUM(a.holidayEntitlementRate), 0), SUM(-(a.discountRate - 1)) + vPayedHolidays - INTO vDaysToSubtract, - vDaysHolidayEnjoyed + INTO vDaysToSubtract, + vDaysHolidayEnjoyed FROM calendar c JOIN absenceType a ON a.id = c.dayOffTypeFk JOIN business b ON b.id = c.businessFk - WHERE b.id = vBusinessFk + WHERE b.id = vBusinessFk AND YEAR(c.dated) = vYear; END IF; - CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness + CREATE TEMPORARY TABLE tmp.workerCalendarCalculateBusiness ENGINE = MEMORY SELECT @days := IFNULL(ROUND((vDaysHoliday * (vDifDays - vDaysToSubtract) / IF(util.isLeapYear(vYear) , 366, 365)), 1), 0) days, @days * (vHoursWeek / 5) hours, @@ -75133,32 +75135,32 @@ BEGIN /** * Calcula los días y horas de vacaciones en función de un trabajador y año * - * @param vYear - * @param vWorkerFk + * @param vYear + * @param vWorkerFk * @return tmp.workerCalendarCalculateYear (days, hours, daysEnjoyed, hoursEnjoyed) - */ + */ DECLARE vDone BOOL; DECLARE vBusinessFk INT; DECLARE cur CURSOR FOR - SELECT b.id + SELECT b.id FROM business b - WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) + WHERE vYear BETWEEN YEAR(b.started) AND IFNULL(YEAR(b.ended), vYear) AND b.workerFk = vWorkerFk; DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - + SET vDone = TRUE; + DROP TEMPORARY TABLE IF EXISTS tmp.workerCalendarCalculateYear; CREATE TEMPORARY TABLE tmp.workerCalendarCalculateYear - (days DEC(5,2), + (days DEC(5,2), hours DEC(5,2), - daysEnjoyed DEC(5,2), - hoursEnjoyed DEC(5,2)) + daysEnjoyed DEC(5,2), + hoursEnjoyed DEC(5,2)) ENGINE = MEMORY; INSERT INTO tmp.workerCalendarCalculateYear VALUES(0, 0, 0, 0); - + OPEN cur; l: LOOP @@ -75171,12 +75173,12 @@ BEGIN CALL workerCalendar_calculateBusiness(vYear, vBusinessFk); UPDATE tmp.workerCalendarCalculateYear w - JOIN tmp.workerCalendarCalculateBusiness wc + JOIN tmp.workerCalendarCalculateBusiness wc SET w.days = w.days + wc.days, w.hours = w.hours + wc.hours, w.daysEnjoyed = w.daysEnjoyed + wc.daysEnjoyed, w.hoursEnjoyed = w.hoursEnjoyed + wc.hoursEnjoyed; - + DROP TEMPORARY TABLE tmp.workerCalendarCalculateBusiness; END LOOP; @@ -75201,7 +75203,7 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerCreate`( vFirstname VARCHAR(50), - vLastName VARCHAR(50), + vLastName VARCHAR(50), vCode CHAR(3), vBossFk INT, vUserFk INT, @@ -75213,7 +75215,7 @@ BEGIN * Create new worker * */ - INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) + INSERT INTO worker(id, code, firstName, lastName, bossFk, fi, birth,userFk) VALUES (vUserFk, vCode, vFirstname, vLastName, vBossFk, vFi, vBirth,vUserFk); END ;; DELIMITER ; @@ -75279,20 +75281,20 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.workerDepartmentByDate; CREATE TEMPORARY TABLE tmp.workerDepartmentByDate ENGINE = MEMORY - SELECT w.id userFk, - w.lastName name, - w.firstName firstname, - d.name department, + SELECT w.id userFk, + w.lastName name, + w.firstName firstname, + d.name department, d.id departmentFk, - b.started, - d.isProduction, + b.started, + d.isProduction, CAST(12 * b.amount / ct.hoursWeek / 52 AS DECIMAL(10,2)) costeHora, w.fi nif FROM business b JOIN calendarType ct ON ct.id = b.calendarTypeFk JOIN department d ON d.id = b.departmentFk JOIN worker w ON w.id = b.workerFk - WHERE b.started <= vDate + WHERE b.started <= vDate AND (b.ended > vDate OR b.ended IS NULL); END ;; DELIMITER ; @@ -75319,18 +75321,18 @@ mainLabel:BEGIN DELETE FROM account.account WHERE id = vUserId; - UPDATE account.user + UPDATE account.user SET role = 2 - WHERE id = vUserId; + WHERE id = vUserId; - DELETE FROM pbx.sip - WHERE user_id = vUserId; + DELETE FROM pbx.sip + WHERE user_id = vUserId; UPDATE `client` c JOIN payMethod p ON p.name = 'CONTADO' SET c.credit = 0, c.payMethodFk = p.id, hasCoreVnl = FALSE WHERE c.id = vUserId; - + UPDATE `client` c SET c.salesPersonFk = null WHERE c.salesPersonFk = vUserId; @@ -75359,12 +75361,12 @@ BEGIN SELECT b.workerFk FROM business b JOIN vn.worker w ON w.id = b.workerFk - JOIN account.account a ON a.id = b.workerFk - LEFT JOIN (SELECT b.workerFk + JOIN account.account a ON a.id = b.workerFk + LEFT JOIN (SELECT b.workerFk FROM business b WHERE (ended IS NULL OR ended >=util.VN_CURDATE()) )sub ON sub.workerFk = a.id - LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk + LEFT JOIN vn.workerDisableExcluded wd ON wd.workerFk = b.workerFk WHERE sub.workerFk IS NULL AND wd.workerFk IS NULL GROUP BY w.id; @@ -75382,7 +75384,7 @@ BEGIN END WHILE; CLOSE rs; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75446,19 +75448,19 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerJourney_replace`( - vDatedFrom DATE, - vDatedTo DATE, + vDatedFrom DATE, + vDatedTo DATE, vWorkerFk INT) BEGIN /** - * Actualiza la tabla workerJourney para que actue como caché permanente revisable + * Actualiza la tabla workerJourney para que actue como caché permanente revisable * de las jornadas laborales. * @param vDatedFrom workerTimeControl * @param vDatedTo workerTimeControl * @param vWorkerFk, en caso de pasar 0 ó NULL se aplica a todos - */ + */ DECLARE vDatedTimeTo DATETIME; - DECLARE vMaxTimePerDay INT; + DECLARE vMaxTimePerDay INT; DECLARE vMinHoursToBreak DECIMAL(10,2); DECLARE vBreakHours DECIMAL(10,2); DECLARE vMonthByYear INT; @@ -75466,57 +75468,57 @@ BEGIN DECLARE vMonthsByYear INT DEFAULT 12; DECLARE vDaysByWeek INT DEFAULT 5; DECLARE vDatedFromYesterday DATETIME; - DECLARE vDatedToTomorrow DATETIME; - - SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) + DECLARE vDatedToTomorrow DATETIME; + + SELECT DATE_SUB(vDatedFrom, INTERVAL 1 DAY), DATE_ADD(vDatedTo, INTERVAL 1 DAY) INTO vDatedFromYesterday, vDatedToTomorrow; SET vDatedTimeTo = util.dayEnd(vDatedTo); - - SELECT minHoursToBreak, breakHours, maxTimePerDay + + SELECT minHoursToBreak, breakHours, maxTimePerDay INTO vMinHoursToBreak, vBreakHours, vMaxTimePerDay FROM workerTimeControlConfig; DELETE FROM workerJourney - WHERE dated BETWEEN vDatedFrom AND vDatedTo + WHERE dated BETWEEN vDatedFrom AND vDatedTo AND NOT isPaid AND NOT isUpdated - AND (vWorkerFk IS NULL OR userFK = vWorkerFk); + AND (vWorkerFk IS NULL OR userFK = vWorkerFk); - -- Se inserta todos los días del periodo por worker y business en el rango de fechas. + -- Se inserta todos los días del periodo por worker y business en el rango de fechas. INSERT IGNORE INTO workerJourney(userFk, dated, businessFk) SELECT b.workerFk, t.dated, b.id - FROM business b + FROM business b JOIN time t ON t.dated BETWEEN b.started AND IFNULL(b.ended,util.VN_CURDATE()) WHERE t.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR b.workerFk = vWorkerFk) ORDER BY b.workerFk, t.dated, b.id; - + DROP TEMPORARY TABLE IF EXISTS tmp.`user`; IF vWorkerFk THEN CALL timeControl_calculateByUser(vWorkerFk, vDatedFrom , vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` - SELECT vWorkerFk userFk; + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + SELECT vWorkerFk userFk; ELSE CALL timeControl_calculateAll(vDatedFrom, vDatedTimeTo); - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` + CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT id userFk FROM worker w; - END IF; + END IF; UPDATE workerJourney wj JOIN tmp.timeControlCalculate t ON wj.dated = t.dated AND wj.userFk = t.userFk - SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, - t.timeWorkDecimal - vBreakHours, + SET wj.total = CAST(IF(t.timeWorkDecimal >= vMinHoursToBreak, + t.timeWorkDecimal - vBreakHours, t.timeWorkDecimal) AS DECIMAL (10,2)), wj.lunch = IF(t.timeWorkDecimal >= vMinHoursToBreak , vBreakHours , 0) WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo AND NOT wj.isPaid AND NOT wj.isUpdated AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk); - - -- NOCTURNIDAD + + -- NOCTURNIDAD CALL timeControl_getError(vDatedFrom, vDatedTimeTo); SET @vIsOdd := TRUE; @@ -75526,9 +75528,9 @@ BEGIN CREATE TEMPORARY TABLE tmp.workerTimeControl (INDEX (userFk), INDEX (timed)) ENGINE = MEMORY - SELECT DISTINCT(wtc.id), - wtc.userFk, - wtc.timed, + SELECT DISTINCT(wtc.id), + wtc.userFk, + wtc.timed, wtc.direction FROM workerTimeControl wtc JOIN tmp.`user` w ON w.userFk = wtc.userFk @@ -75538,10 +75540,10 @@ BEGIN AND (vWorkerFk IS NULL OR wtc.userFk = vWorkerFk) ORDER BY wtc.userFk, wtc.timed ASC; - SELECT MAX(id) INTO @vCont + SELECT MAX(id) INTO @vCont FROM tmp.workerTimeControl; - DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; + DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlAux; CREATE TEMPORARY TABLE tmp.workerTimeControlAux ( `id` int(11) , `userFk` int(10) unsigned , @@ -75563,9 +75565,9 @@ BEGIN DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' - AND (DATE(@lastTimed) <> date(timed) + IF(@vIsOdd + AND @lastDirection = 'middle' + AND (DATE(@lastTimed) <> date(timed) OR @lastUserFk <> userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @lastUserFk := userFk, @@ -75579,16 +75581,16 @@ BEGIN SET @lastDirection := NULL; INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - lastUserFk, - DATE_ADD(sub.dated, INTERVAL 1 DAY), + SELECT @vCont:= @vCont + 1, + lastUserFk, + DATE_ADD(sub.dated, INTERVAL 1 DAY), 'middle' FROM (SELECT IF(@lastUserFk <> userFk, @vIsOdd := TRUE, NULL), DATE(@lastTimed) dated, @lastUserFk lastUserFk, IF(direction ='middle', @vIsOdd := NOT @vIsOdd, FALSE) isOdd, - IF(@vIsOdd - AND @lastDirection = 'middle' + IF(@vIsOdd + AND @lastDirection = 'middle' AND (DATE(@lastTimed)<>date(timed) OR @lastUserFk<>userFk), TRUE, FALSE) hasBreak, @lastTimed := wtc.timed, @@ -75601,7 +75603,7 @@ BEGIN -- Cambio de dia INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) SELECT @vCont:= @vCont + 1, - wtc.userFk, + wtc.userFk, util.dayEnd(date(wtc.timed)), 'out' FROM workerTimeControl wtc @@ -75612,8 +75614,8 @@ BEGIN GROUP BY wtc.userFk, DATE(wtc.timed); INSERT INTO tmp.workerTimeControlAux (id, userFk, timed, direction) - SELECT @vCont:= @vCont + 1, - wtc.userFk, + SELECT @vCont:= @vCont + 1, + wtc.userFk, DATE_ADD(date(wtc.timed), INTERVAL 1 DAY), 'in' FROM workerTimeControl wtc @@ -75639,8 +75641,8 @@ BEGIN IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed), IF(direction='in', @vDated := DATE(wtc.timed), @vDated ) dated, wtc.userFk, - IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, - workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), + IF(UNIX_TIMESTAMP(timed)- @vLastTimed < vMaxTimePerDay, + workerNigthlyHours_calculate(FROM_UNIXTIME(@vLastTimed), wtc.timed), 0) NigthlyHours, @lastUserFk := userFk FROM (SELECT DISTINCT(wtc.id), wtc.userFk, wtc.timed, wtc.direction @@ -75653,7 +75655,7 @@ BEGIN ) wtc ORDER BY wtc.userFk, wtc.timed )sub - WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo + WHERE sub.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY userFk, sub.dated )night ON night.userFk = wj.userFk AND night.dated = wj.dated SET wj.nocturn = night.NigthlyHours @@ -75665,8 +75667,8 @@ BEGIN UPDATE workerJourney wj JOIN business b ON b.id = wj.businessFk JOIN calendarType ct ON ct.id = b.calendarTypeFk - SET wj.priceOrdinaryHour = - (vMonthsByYear * b.amount) / + SET wj.priceOrdinaryHour = + (vMonthsByYear * b.amount) / (vWeeksByYear * ct.hoursWeek), wj.contractJourney = ct.hoursWeek / vDaysByWeek WHERE wj.dated BETWEEN vDatedFrom AND vDatedTo @@ -75674,7 +75676,7 @@ BEGIN AND NOT wj.isPaid AND NOT isUpdated; - -- Precio Extras, Vacaciones y Nocturnas + -- Precio Extras, Vacaciones y Nocturnas UPDATE workerJourney wj JOIN(SELECT MAX(w.dated), t.dated, w.holidayInc, w.nightInc, w.extraInc FROM time t @@ -75698,12 +75700,12 @@ BEGIN WHERE ct.isPartial AND wj.dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR wj.userFk = vWorkerFk) - AND NOT wj.isPaid + AND NOT wj.isPaid AND NOT wj.isUpdated; -- Ausencias UPDATE workerJourney wj - JOIN businessCalendar bc ON bc.businessFk = wj.businessFk + JOIN businessCalendar bc ON bc.businessFk = wj.businessFk AND bc.dated = wj.dated JOIN absenceType ab ON ab.id = bc.absenceTypeFk SET wj.permission = ab.permissionRate * wj.contractJourney, @@ -75718,7 +75720,7 @@ BEGIN UPDATE workerJourney SET holiday = IF(DAYNAME(dated)='sábado', 0, total), contractJourney = 0 - WHERE DAYNAME(dated) IN ('sábado', 'domingo') + WHERE DAYNAME(dated) IN ('sábado', 'domingo') AND dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) AND NOT isPaid @@ -75727,8 +75729,8 @@ BEGIN -- Festivos por centro de trabajo UPDATE workerJourney wj JOIN calendarHolidays ch ON ch.dated = wj.dated - JOIN business b ON b.id = wj.businessFk - AND b.workcenterFk = ch.workcenterFk + JOIN business b ON b.id = wj.businessFk + AND b.workcenterFk = ch.workcenterFk SET wj.holiday = wj.total, wj.permission = wj.contractJourney, wj.contractJourney = 0 @@ -75738,7 +75740,7 @@ BEGIN AND NOT wj.isUpdated; -- Horas extras - UPDATE workerJourney + UPDATE workerJourney SET extra = lunch + total - contractJourney WHERE dated BETWEEN vDatedFrom AND vDatedTo AND (vWorkerFk IS NULL OR userFk = vWorkerFk) @@ -75768,15 +75770,15 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerMistakeType_get`() BEGIN - + /** * Obtiene los tipos de error para los trabajadores */ - - SELECT code, description - FROM workerMistakeType + + SELECT code, description + FROM workerMistakeType ORDER BY description; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75803,7 +75805,7 @@ BEGIN * */ INSERT INTO vn.workerMistake(userFk, workerMistakeTypeFk) - VALUES(vWorkerFk, vWorkerMistakeTypeFk); + VALUES(vWorkerFk, vWorkerMistakeTypeFk); END ;; DELIMITER ; @@ -75826,11 +75828,11 @@ BEGIN /*INSERT INTO workerTimeControl(userFk, timed, manual, warehouseFk) VALUES(vUserFk, vDated, FALSE, vWarehouseFk); - + CALL vn.workerTimeControlSOWP(vUserFk , vDated);*/ - + CALL vn.workerTimeControl_add(vUserFk,vWarehouseFk,util.VN_NOW(),FALSE); - + END ;; DELIMITER ; @@ -75856,8 +75858,8 @@ BEGIN * */ - - + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75906,13 +75908,13 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControlSOWP`(IN vUserFk INT, IN vDated DATE) BEGIN SET @order := 0; - - UPDATE workerTimeControl - SET `order` = @order := @order + 1 - WHERE vUserFk =userFk + + UPDATE workerTimeControl + SET `order` = @order := @order + 1 + WHERE vUserFk =userFk AND vDated = DATE(timed) ORDER BY timed; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75931,8 +75933,8 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - - + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; @@ -76020,73 +76022,73 @@ proc: BEGIN DECLARE vTo VARCHAR(50) DEFAULT NULL; DECLARE vUserName VARCHAR(50) DEFAULT NULL; DECLARE vBody VARCHAR(255) DEFAULT NULL; - - SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax FROM workerTimeControlParams; SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk + FROM workerTimeControl + WHERE userFk = vUserFk AND direction = 'in'; - + SELECT MAX(timed) INTO vLastOut - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'out'; + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'out'; SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo FROM account.user u - WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); - + WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); + SELECT CONCAT(firstName,' ',lastName) INTO vUserName FROM worker w WHERE w.id = vUserFk; IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA - - -- VERIFICAR DESCANSO DIARIO - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + + -- VERIFICAR DESCANSO DIARIO + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; - END IF; - + END IF; + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ - IF (SELECT MOD(COUNT(*),2) -- <>0 - FROM workerTimeControl + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM workerTimeControl WHERE userFk = vUserFk AND timed >= vLastIn - ) THEN + ) THEN SELECT "Dias con fichadas impares" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; - + -- VERIFICAR VACACIONES SELECT at2.name INTO vCalendarStateType - FROM calendar c + FROM calendar c JOIN business b ON b.id = c.businessFk JOIN absenceType at2 ON at2.id = c.dayOffTypeFk WHERE c.dated = util.VN_CURDATE() AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; - + -- VERIFICAR CONTRATO EN VIGOR IF (SELECT COUNT(*) FROM business b @@ -76098,44 +76100,44 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; - + LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL SET @vHasBreakWeek:= FALSE; - SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); - + SET @vLastTimed:= UNIX_TIMESTAMP((util.VN_NOW() - INTERVAL vWeekScope SECOND)); + DROP TEMPORARY TABLE IF EXISTS tmp.trash; CREATE TEMPORARY TABLE tmp.trash SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, @vLastTimed:= UNIX_TIMESTAMP(timed) - FROM workerTimeControl + FROM workerTimeControl WHERE timed>= (util.VN_NOW() - INTERVAL vWeekScope SECOND) AND userFk= vUserFk AND direction IN ('in','out') - ORDER BY timed ASC; - - IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(util.VN_NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; - - DROP TEMPORARY TABLE tmp.trash; - ELSE -- DIA ACTUAL - + DROP TEMPORARY TABLE tmp.trash; + + ELSE -- DIA ACTUAL + -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO - SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked + SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(util.VN_NOW()), 0) INTO vTimedWorked FROM workerTimeControl wtc - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed >= vLastIn ORDER BY timed; - IF vTimedWorked > vDayWorkMax THEN + IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No ha podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; @@ -76158,10 +76160,10 @@ proc: BEGIN -- ENVIAMOS CORREO AL BOSSFK SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; CALL mail_insert(vTo,vTo,'error al fichar',vBody); - LEAVE proc; + LEAVE proc; END IF; END IF;*/ - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76181,7 +76183,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_checkBreak`(vStarted DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas * El sistema verificará el descanso corto en la siguiente semana * o el largo en las 2 siguientes semanas a partir de la fecha dada * @param vStarted día inicio de la semana en el que se quiere verificar @@ -76192,27 +76194,27 @@ BEGIN DECLARE vShortWeekBreak INT; DECLARE vLongWeekBreak INT; - SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), + SELECT util.dayEnd(DATE_ADD(vStarted, INTERVAL shortWeekDays DAY)), util.dayEnd(DATE_ADD(vStarted, INTERVAL longWeekDays DAY)), - shortWeekBreak, + shortWeekBreak, longWeekBreak INTO vShortEnded, vLongEnded, vShortWeekBreak, vLongWeekBreak FROM workerTimeControlConfig; - + SET @previousTimed:= UNIX_TIMESTAMP(vStarted); SET @lastUserFk := NULL; - + -- Descanso corto en la semana - + DROP TEMPORARY TABLE IF EXISTS tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT DISTINCT userFk workerFk - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out'); - + DROP TEMPORARY TABLE IF EXISTS tmp.worker2; CREATE TEMPORARY TABLE tmp.worker2 (PRIMARY KEY(workerFk)) @@ -76225,28 +76227,28 @@ BEGIN SELECT sub2.userFk workerFk FROM(SELECT sub.userFk, IF(sub.userFk <> @lastUserFk, - @previousTimed:= sub.timed, + @previousTimed:= sub.timed, FALSE), - IF(sub.timed - @previousTimed >= vShortWeekBreak, - TRUE, + IF(sub.timed - @previousTimed >= vShortWeekBreak, + TRUE, FALSE) hasShortWeekBreak, @previousTimed:= sub.timed, @lastUserFk:= sub.userFk FROM ( SELECT userFk, UNIX_TIMESTAMP(timed) timed - FROM workerTimeControl + FROM workerTimeControl WHERE timed BETWEEN vStarted AND vShortEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, UNIX_TIMESTAMP(IFNULL( - MIN(wtc.timed), + MIN(wtc.timed), DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN vShortEnded - AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN vShortEnded + AND DATE_ADD(vShortEnded, INTERVAL vShortWeekBreak SECOND) GROUP BY w.workerFk UNION SELECT w.workerFk, @@ -76254,10 +76256,10 @@ BEGIN MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND wtc.timed BETWEEN - DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND wtc.timed BETWEEN + DATE_SUB(vStarted, INTERVAL vShortWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -76267,7 +76269,7 @@ BEGIN GROUP BY sub2.userFk HAVING NOT SUM(hasShortWeekBreak); - -- Descanso largo en las 2 siguientes semanas + -- Descanso largo en las 2 siguientes semanas DROP TEMPORARY TABLE tmp.worker; CREATE TEMPORARY TABLE tmp.worker (PRIMARY KEY(workerFk)) @@ -76287,12 +76289,12 @@ BEGIN (PRIMARY KEY(workerFk)) ENGINE = MEMORY SELECT sub2.userFk workerFk - FROM(SELECT userFk, + FROM(SELECT userFk, IF(userFk <> @lastUserFk, - @previousTimed:= timed, + @previousTimed:= timed, TRUE), - IF(timed - @previousTimed >= vLongWeekBreak, - TRUE, + IF(timed - @previousTimed >= vLongWeekBreak, + TRUE, FALSE) hasLongWeekBreak, @previousTimed:= timed, @lastUserFk:= userFk @@ -76301,24 +76303,24 @@ BEGIN JOIN tmp.workerWithoutShortWeekBreak wws ON wws.workerFk = wtc.userFk WHERE timed BETWEEN vStarted AND vLongEnded AND direction IN ('in', 'out') - UNION + UNION SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), + UNIX_TIMESTAMP(IFNULL(MIN(wtc.timed), DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN vLongEnded - AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN vLongEnded + AND DATE_ADD(vLongEnded, INTERVAL vLongWeekBreak SECOND) GROUP BY w.workerFk UNION - SELECT w.workerFk, - UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), + SELECT w.workerFk, + UNIX_TIMESTAMP(IFNULL(MAX(wtc.timed), DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND))) FROM tmp.worker2 w - LEFT JOIN workerTimeControl wtc - ON wtc.userFk = w.workerFk - AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) + LEFT JOIN workerTimeControl wtc + ON wtc.userFk = w.workerFk + AND timed BETWEEN DATE_SUB(vStarted, INTERVAL vLongWeekBreak SECOND) AND vStarted GROUP BY w.workerFk ORDER BY userFk, timed @@ -76695,27 +76697,27 @@ BEGIN * Devuelve que direcciones de fichadas son lógicas a partir de la anterior fichada * @param vWorkerFk Identificador del trabajador * @return (option1, option2) - * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') + * Los valores posibles de retorno son ('in', 'inMiddle', 'outMiddle', 'out') */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; - IF (vTimed IS NULL) THEN + IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); END IF; - + SELECT timed INTO vLastIn - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'in' + AND direction = 'in' AND timed < vTimed ORDER BY timed DESC LIMIT 1; - + SELECT (COUNT(*)mod 2 = 1) INTO vIsMiddleOdd - FROM workerTimeControl + FROM workerTimeControl WHERE userFk = vWorkerFk - AND direction = 'middle' + AND direction = 'middle' AND timed BETWEEN vLastIn AND util.VN_NOW(); DROP TEMPORARY TABLE IF EXISTS tmp.workerTimeControlDirection; @@ -76764,7 +76766,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_getClockIn`( - vUserFk INT, + vUserFk INT, vDated DATE) BEGIN /** @@ -76774,9 +76776,9 @@ BEGIN * @param vDated Fecha proporcionada */ CALL timeControl_calculateByWorker( - vUserFk, + vUserFk, DATE_SUB(vDated, INTERVAL 6 DAY), util.dayEnd(vDated)); - + SET @position := 0; SET @lastDated := NULL; @@ -76793,7 +76795,7 @@ BEGIN MAX(2daysAgoDirection) 2daysAgoDirection, MAX(1daysAgo) 1daysAgo, MAX(1daysAgoDirection) 1daysAgoDirection, - MAX(0daysAgo) 0daysAgo, + MAX(0daysAgo) 0daysAgo, MAX(0daysAgoDirection) 0daysAgoDirection FROM(SELECT IF(daysAgo = 6, timed, '') 6daysAgo, IF(daysAgo = 5, timed, '') 5daysAgo, @@ -76813,7 +76815,7 @@ BEGIN direction, position FROM(SELECT DATEDIFF(vDated, timed) daysAgo, - TIME_FORMAT(timed,'%H:%i') timed, + TIME_FORMAT(timed,'%H:%i') timed, IF(DATE(timed) <> @lastDated, @position := 0, NULL), @position := @position+1 position, @lastDated := DATE(timed), @@ -76825,18 +76827,18 @@ BEGIN LIMIT 10000000000000000000 )sub )sub2 - GROUP BY position) sub3 + GROUP BY position) sub3 JOIN (SELECT MAX(IF(daysAgo = 6, timeWorkSeconds, 0)) 6daysAgoTotal, MAX(IF(daysAgo = 5, timeWorkSeconds, 0)) 5daysAgoTotal, MAX(IF(daysAgo = 4, timeWorkSeconds, 0)) 4daysAgoTotal, MAX(IF(daysAgo = 3, timeWorkSeconds, 0)) 3daysAgoTotal, MAX(IF(daysAgo = 2, timeWorkSeconds, 0)) 2daysAgoTotal, MAX(IF(daysAgo = 1, timeWorkSeconds, 0)) 1daysAgoTotal, - MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal + MAX(IF(daysAgo = 0, timeWorkSeconds, 0)) 0daysAgoTotal FROM (SELECT DATEDIFF(vDated, dated) daysAgo, timeWorkSeconds FROM tmp.timeControlCalculate) sub4)sub5 ON TRUE; - + DROP TEMPORARY TABLE tmp.timeControlCalculate; END ;; DELIMITER ; @@ -76900,45 +76902,45 @@ BEGIN DECLARE vDirectionPrevious VARCHAR(6); DECLARE vTimedPrevious DATETIME; - SELECT direction INTO vDirectionRemove - FROM vn.workerTimeControl - WHERE userFk = vUserFk + SELECT direction INTO vDirectionRemove + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed = vTimed ; IF vDirectionRemove = 'out' THEN - + SELECT timed, direction INTO vTimedPrevious, vDirectionPrevious - FROM vn.workerTimeControl - WHERE userFk = vUserFk + FROM vn.workerTimeControl + WHERE userFk = vUserFk AND timed < vTimed ORDER BY timed DESC - LIMIT 1; - + LIMIT 1; + IF vDirectionPrevious = "middle" THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "out" WHERE userFk = vUserFk AND timed = vTimedPrevious; END IF; - + ELSE IF vDirectionRemove = 'in' THEN - UPDATE vn.workerTimeControl + UPDATE vn.workerTimeControl SET direction = "in" WHERE userFk = vUserFk AND timed > vTimed ORDER BY timed ASC - LIMIT 1; + LIMIT 1; END IF; - + END IF; - + DELETE FROM vn.workerTimeControl - WHERE userFk = vUserFk + WHERE userFk = vUserFk AND timed = vTimed; - + CALL vn.workerTimeControlSOWP(vUserFk, vTimed); - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -76966,31 +76968,31 @@ proc: BEGIN UPDATE vn.workerTimeControl SET direction = 'middle'; /*2- poner los out*/ -UPDATE vn.workerTimeControl wtc - JOIN +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MAX(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "out" - WHERE wtc.userFk = sub.userFk + WHERE wtc.userFk = sub.userFk AND wtc.timed = sub.maxTimed; - - /*3- poner los in*/ -UPDATE vn.workerTimeControl wtc - JOIN + + /*3- poner los in*/ +UPDATE vn.workerTimeControl wtc + JOIN (SELECT userFk,MIN(timed) maxTimed FROM (SELECT id, userFk, timed, date(timed) dated - FROM vn.workerTimeControl - ) sub + FROM vn.workerTimeControl + ) sub GROUP BY userFk,dated )sub SET direction = "in" - WHERE wtc.userFk = sub.userFk - AND wtc.timed = sub.maxTimed ; - + WHERE wtc.userFk = sub.userFk + AND wtc.timed = sub.maxTimed ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -77063,7 +77065,7 @@ BEGIN AND w.businessFk GROUP BY tm.userFk,t.dated ORDER BY tm.userFk,t.dated; - + INSERT INTO vn.mail (receiver, replyTo, subject, body) SELECT eu.email, 'laboral@verdnatura.es', CONCAT('Registro de horas semana ', WEEK(vDatedFrom), ' año ', YEAR(vDatedFrom)) , CONCAT(' @@ -77155,7 +77157,7 @@ BEGIN IF (DAYNAME(util.VN_CURDATE()) = 'miércoles') THEN SELECT DATE_SUB(util.VN_CURDATE(), INTERVAL 9 DAY), CONCAT(DATE_SUB(util.VN_CURDATE(), INTERVAL 3 DAY), ' 23:59:59') INTO vDatedFrom, vDatedTo; - + CALL vn.workerTimeControl_sendMailByDepartment(vDatedFrom, vDatedTo, NULL); END IF; END ;; @@ -77205,9 +77207,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workerTimeControl_weekCheckBreak`(vStarted DATE, vEnded DATE) BEGIN /** - * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas - * El sistema verificará el descanso corto en la siguiente semana - * o el largo en las 2 siguientes semanas a partir de las fechas dadas + * Retorna los trabajadores que no han respetado el descanso semanal de 36/72 horas + * El sistema verificará el descanso corto en la siguiente semana + * o el largo en las 2 siguientes semanas a partir de las fechas dadas * @param vStarted día inicio para verificar * @param vEnded día final para verificar * @return tmp.workerWithoutWeekBreak (workerFk) @@ -77229,10 +77231,10 @@ BEGIN CALL workerTimeControl_checkBreak(vStarted); INSERT IGNORE INTO tmp.workerWithoutWeekBreakInWeek - SELECT workerFk + SELECT workerFk FROM tmp.workerWithoutWeekBreak; DROP TEMPORARY TABLE IF EXISTS tmp.workerWithoutWeekBreak; - SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); + SET vStarted = DATE_ADD(vStarted, INTERVAL 1 DAY); END WHILE; END ;; @@ -77270,7 +77272,7 @@ BEGIN DECLARE vDepartmentFk INT; DECLARE isEnabled BOOLEAN DEFAULT TRUE; - SELECT COUNT(*) INTO vHasSignedToday + SELECT COUNT(*) INTO vHasSignedToday FROM workerTimeControl WHERE timed >= vDated AND userFk = vUserFk; SET @day := 0; @@ -77283,16 +77285,16 @@ BEGIN SELECT fichada_anterior, fichada_actual, interval_in_minutes, jornadas FROM ( - SELECT @lastTimed fichada_anterior, + SELECT @lastTimed fichada_anterior, timed, CAST(time_to_sec(timediff(timed,@lastTimed )) / 60 AS UNSIGNED) as interval_in_minutes, IF(day(timed) != @day, 1, 0) as jornadas, @day := day(timed) dia_del_mes, - @lastTimed := timed fichada_actual + @lastTimed := timed fichada_actual FROM ( SELECT day(timed) as dayNumber, dayname(timed) as dayName, timed - FROM + FROM (SELECT TIMESTAMPADD(DAY, -11, util.VN_NOW()) as timed, vUserFk as userFk -- Fichada virtual para los en los que no se ha trabajado la semana anterior UNION ALL SELECT timed, userFk @@ -77300,18 +77302,18 @@ BEGIN WHERE userFk = vUserFk AND timed >= TIMESTAMPADD(DAY, -10,vDated) UNION ALL - SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk + SELECT IF(vHasSignedToday, '2000-01-01 00:00', util.VN_NOW()) as timed, vUserFk ) sub4 ORDER BY timed ) sub - + ) sub2 WHERE fichada_actual >= TIMESTAMPADD(WEEK, -1, vDated) ) sub3 ; SELECT IFNULL(SUM(impar),0) into vImpares FROM ( - SELECT day(timed) as dayNumber, + SELECT day(timed) as dayNumber, count(*) mod 2 as impar FROM vn.workerTimeControl wtc WHERE userFk = vUserFk @@ -77328,29 +77330,29 @@ BEGIN AND at2.isAllowedToWork = FALSE AND b.workerFk = vUserFk LIMIT 1; - + -- Contrato en vigor SELECT IF(COUNT(*),vCantWork,'Sin contrato') INTO vCantWork FROM business b WHERE b.workerFk = vUserFk AND b.started <= vDated AND IFNULL(b.ended, vDated) >= vDated; - + -- Departamento si vTabletFk es 0 no hacemos comprobacion (Madrid y Vilassar) IF vTabletFk <> '0' THEN -- 1 Obtener el departamento del usuario SELECT wtcu.departmentFk INTO vDepartmentFk FROM workerTimeControlUserInfo wtcu WHERE wtcu.userFk = vUserFk; - -- 2 Comprobar si la tablet pertenece al departamento + -- 2 Comprobar si la tablet pertenece al departamento SELECT COUNT(td.tabletFk) INTO isEnabled FROM tabletDepartment td WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk; - + END IF; - + IF vJornadas IS NOT NULL THEN - + SELECT 'Jornadas' as Item, vJornadas as Cantidad, 'Correcto' AS Análisis UNION ALL SELECT 'Descansos 12 h' as Item, vDescansos12h as Cantidad, IF(vDescansos12h >= vJornadas, 'Correcto','Error: 1 por jornada') as Análisis @@ -77359,9 +77361,9 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, IF(vImpares = 0, 'Correcto','Error') as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, - '' as Cantidad, - IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + '' as Cantidad, + IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -77375,7 +77377,7 @@ BEGIN UNION ALL SELECT 'Dias con fichadas impares' as Item, vImpares as Cantidad, 'Correcto' as Análisis UNION ALL - SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, + SELECT IF (LENGTH(vCantWork),CONCAT('Dia no laborable: ', vCantWork),'Dia laborable') as Item, '' as Cantidad, IF(LENGTH(vCantWork),'Error', 'Correcto') as Análisis UNION ALL SELECT 'El fichador no pertenece a tu departamento.' as Item, '' as Cantidad, IF(isEnabled, 'Correcto','Error') as Análisis; @@ -77405,11 +77407,11 @@ BEGIN * @param vDepartmentFk id del departamento * */ - - SELECT w.id,w.firstName, w.lastName,d.name - FROM worker w - JOIN workerDepartment wd ON wd.workerFk = w.id - JOIN department d ON d.id = wd.departmentFk + + SELECT w.id,w.firstName, w.lastName,d.name + FROM worker w + JOIN workerDepartment wd ON wd.workerFk = w.id + JOIN department d ON d.id = wd.departmentFk WHERE d.id = vDepartmentFk ORDER BY firstName; @@ -77440,7 +77442,7 @@ BEGIN (PRIMARY KEY (workerFk)) ENGINE = MEMORY SELECT vBoss AS workerFk; - + DROP TEMPORARY TABLE IF EXISTS tmp.workerHierarchyList; CREATE TEMPORARY TABLE tmp.workerHierarchyList (PRIMARY KEY (workerFk)) @@ -77451,7 +77453,7 @@ BEGIN WHILE (SELECT COUNT(*) FROM tmp.workerHierarchyList WHERE NOT isChecked) > 0 DO INSERT INTO tmp.workerHierarchyList - SELECT w.id, 0 + SELECT w.id, 0 FROM worker w JOIN workerHierarchy wh ON wh.workerFk = w.bossFk; @@ -77462,12 +77464,12 @@ BEGIN TRUNCATE workerHierarchy; INSERT INTO workerHierarchy - SELECT workerFk + SELECT workerFk FROM tmp.workerHierarchyList WHERE NOT isChecked; END WHILE; - + DROP TEMPORARY TABLE IF EXISTS workerHierarchy; END ;; DELIMITER ; @@ -77494,7 +77496,7 @@ BEGIN SELECT s.id,s.description,s.warehouseFk FROM sector s - JOIN operator o ON o.sectorFk = s.id + JOIN operator o ON o.sectorFk = s.id WHERE o.workerFk = account.myUser_getId(); END ;; @@ -77579,8 +77581,8 @@ BEGIN DECLARE vDone BOOL; DECLARE vCursor CURSOR FOR - SELECT DISTINCT b.workerFk - FROM business b + SELECT DISTINCT b.workerFk + FROM business b WHERE b.started > vBusinessUpdated AND b.started <= vCurdate OR b.ended >= vBusinessUpdated AND b.ended < vCurdate; @@ -77623,10 +77625,10 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `workingHours`(username varchar(255), logon boolean) BEGIN DECLARE userid int(11); - + SELECT vn.getUserId(username) INTO userid; SELECT username, userid; - IF userid IS NOT NULL THEN + IF userid IS NOT NULL THEN IF (logon) THEN CALL vn.workingHoursTimeIn(userid); ELSE @@ -77695,17 +77697,17 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `wrongEqualizatedClient`() BEGIN SELECT clientFk, c.name, c.isActive, c.isTaxDataChecked, count(ie) as num FROM vn.client c - JOIN + JOIN ( - SELECT DISTINCT + SELECT DISTINCT `a`.`clientFk` , a.isEqualizated = 0 as ie - + FROM `vn`.`address` `a` ) sub ON sub.clientFk = c.id WHERE c.hasToInvoiceByAddress = FALSE - + GROUP BY clientFk HAVING num > 1 UNION ALL @@ -77789,27 +77791,27 @@ proc: BEGIN SELECT scope INTO vScope FROM zoneConfig; - + DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone (INDEX (id)) ENGINE = MEMORY SELECT id FROM zone; - + TRUNCATE TABLE zoneClosure; - + WHILE vCounter <= vScope DO - + CALL zone_getOptionsForShipment(vShipped, TRUE); - + REPLACE zoneClosure(zoneFk, dated, `hour`) - SELECT zoneFk, vShipped, `hour` + SELECT zoneFk, vShipped, `hour` FROM tmp.zoneOption; - + SET vCounter = vCounter + 1; SET vShipped = TIMESTAMPADD(DAY, 1, vShipped); END WHILE; - + -- DROP TEMPORARY TABLE tmp.zone; DO RELEASE_LOCK('vn.zoneClosure_recalc'); END ;; @@ -77903,7 +77905,7 @@ BEGIN OR (vSelf IS NOT NULL AND parentFk = vSelf); DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - + SET vSons = 0; OPEN vChildren; @@ -77914,11 +77916,11 @@ BEGIN IF vDone THEN LEAVE myLoop; END IF; - + SET vIndex = vIndex + 1; SET vLft = vIndex; SET vSons = vSons + 1; - + CALL zoneGeo_calcTreeRec( vChildFk, CONCAT(vPath, vChildFk, '/'), @@ -78021,7 +78023,7 @@ proc: BEGIN SELECT isChanged INTO vIsChanged FROM zoneGeoRecalc; - + IF vIsChanged THEN UPDATE zoneGeoRecalc SET isChanged = FALSE; CALL vn.zoneGeo_calcTree; @@ -78209,7 +78211,7 @@ proc:BEGIN * @table tmp.closedZones(zoneFk, warehouseFk); */ DROP TEMPORARY TABLE IF EXISTS tmp.closedZones; - + CREATE TEMPORARY TABLE tmp.closedZones ( `zoneFk` int(11) NOT NULL, `warehouseFk` smallint(6) unsigned NOT NULL, @@ -78251,7 +78253,7 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getCollisions`() BEGIN /** - * Calcula si para un mismo codigo postal y dia + * Calcula si para un mismo codigo postal y dia * hay mas de una zona configurada y manda correo * */ @@ -78260,16 +78262,16 @@ BEGIN DECLARE vIsDone INT DEFAULT FALSE; DECLARE vTableCollisions TEXT; DECLARE cur1 CURSOR FOR SELECT zoneFk from tmp.zoneOption; - + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vIsDone = TRUE; DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone - SELECT z.id + SELECT z.id FROM zone z JOIN agencyMode am ON am.id = z.agencyModeFk JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN ('AGENCY','DELIVERY'); + WHERE dm.code IN ('AGENCY','DELIVERY'); CALL zone_getOptionsForShipment(util.VN_CURDATE(),FALSE); @@ -78284,7 +78286,7 @@ BEGIN PRIMARY KEY zoneFkk (zoneFk, geoFk), INDEX(geoFk)) ENGINE = MyISAM; - + OPEN cur1; cur1Loop: LOOP SET vIsDone = FALSE; @@ -78292,40 +78294,40 @@ BEGIN IF vIsDone THEN LEAVE cur1Loop; END IF; - + CALL zone_getLeaves(vZoneFk, NULL, NULL, TRUE); - myLoop: LOOP + myLoop: LOOP SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk + SELECT geoFk INTO vGeoFk FROM tmp.zoneNodes zn WHERE NOT isChecked LIMIT 1; - + IF vGeoFk IS NULL THEN LEAVE myLoop; END IF; - + CALL zone_getLeaves(vZoneFk, vGeoFk, NULL, TRUE); UPDATE tmp.zoneNodes - SET isChecked = TRUE + SET isChecked = TRUE WHERE geoFk = vGeoFk; END LOOP; END LOOP; CLOSE cur1; - DELETE FROM tmp.zoneNodes + DELETE FROM tmp.zoneNodes WHERE sons > 0; - + DROP TEMPORARY TABLE IF EXISTS geoCollision; CREATE TEMPORARY TABLE geoCollision SELECT z.agencyModeFk, zn.geoFk, zw.warehouseFk FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk - JOIN zoneWarehouse zw ON z.id = zw.zoneFk + JOIN zoneWarehouse zw ON z.id = zw.zoneFk GROUP BY z.agencyModeFk, zn.geoFk, zw.warehouseFk HAVING count(*) > 1; - + SELECT ' @@ -78335,39 +78337,39 @@ BEGIN ' INTO vTableCollisions; - - INSERT INTO mail (receiver,replyTo,subject,body) + + INSERT INTO mail (receiver,replyTo,subject,body) SELECT 'pepe@verdnatura.es' receiver, 'noreply@verdnatura.es' replyTo, CONCAT('Colisiones en zonas ', util.VN_CURDATE()) subject, CONCAT(vTableCollisions, GROUP_CONCAT(sub.td SEPARATOR ''), '
C.PostalAlmacén Salix
') body - FROM(SELECT + FROM(SELECT CONCAT(' ', zn.name, ' ', zoneFk,' ', z.price,' ', z.name,' ', w.name, ' - ', CONCAT('' - 'https://salix.verdnatura.es/#!/zone/', + 'https://salix.verdnatura.es/#!/zone/', zoneFk, '/location?q=%7B%22search%22:%22', - zn.name, + zn.name, '%22%7D'),' ') td FROM tmp.zoneNodes zn JOIN zone z ON z.id = zn.zoneFk JOIN geoCollision gc ON gc.agencyModeFk = z.agencyModeFk AND zn.geoFk = gc.geoFk JOIN warehouse w ON w.id = gc.warehouseFk) sub; - - DROP TEMPORARY TABLE - geoCollision, + + DROP TEMPORARY TABLE + geoCollision, tmp.zone, tmp.zoneNodes; END ;; @@ -78474,18 +78476,18 @@ BEGIN DECLARE vChildFk INT DEFAULT vGeoFk; DECLARE vParentFk INT; DECLARE vLevel INT DEFAULT 1; - + DROP TEMPORARY TABLE IF EXISTS tNodes; CREATE TEMPORARY TABLE tNodes (PRIMARY KEY (id)) ENGINE = MEMORY SELECT vGeoFk id, vLevel `level`; - + myLoop: LOOP SELECT parentFk INTO vParentFk FROM zoneGeo WHERE id = vChildFk; - + SET vChildFk = vParentFk; SET vLevel = vLevel + 1; @@ -78493,7 +78495,7 @@ BEGIN SELECT vChildFk, vLevel FROM DUAL WHERE vChildFk IS NOT NULL; - + IF ROW_COUNT() = 0 THEN LEAVE myLoop; END IF; @@ -78592,126 +78594,126 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255), - vHasInsert BOOL +CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getLeaves`( + vSelf INT, + vParentFk INT, + vSearch VARCHAR(255), + vHasInsert BOOL ) -BEGIN -/** - * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. - * @param vSelf Id de la zona - * @param vParentFk Id del geo a calcular - * @param vSearch Cadena a buscar - * @param vHasInsert Indica si inserta en tmp.zoneNodes - * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - */ - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; - - CREATE OR REPLACE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id - FROM zoneGeo - LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id - FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk - FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - CREATE OR REPLACE TEMPORARY TABLE tChilds - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM tNodes; - - CREATE OR REPLACE TEMPORARY TABLE tParents - (INDEX(id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF NOT ROW_COUNT() THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE tChilds, tParents; - END IF; - - IF NOT vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id - FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - CREATE OR REPLACE TEMPORARY TABLE tZones - SELECT g.id, - g.name, - g.parentFk, - g.sons, - NOT g.sons OR `type` = 'country' isChecked, - i.isIncluded selected, - g.`depth`, - vSelf - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i ON i.geoFk = g.id - AND i.zoneFk = vSelf - ORDER BY g.`depth`, selected DESC, g.name; - - IF vHasInsert THEN - INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) - SELECT id, - name, - parentFk, - sons, - isChecked, - vSelf - FROM tZones - WHERE selected - OR (selected IS NULL AND vParentFk IS NOT NULL); - ELSE - SELECT id, - name, - parentFk, - sons, - selected - FROM tZones - ORDER BY `depth`, selected DESC, name; - END IF; - - DROP TEMPORARY TABLE tNodes, tZones; +BEGIN +/** + * Devuelve las ubicaciones incluidas en la ruta y que sean hijos de parentFk. + * @param vSelf Id de la zona + * @param vParentFk Id del geo a calcular + * @param vSearch Cadena a buscar + * @param vHasInsert Indica si inserta en tmp.zoneNodes + * Optional @table tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + */ + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch <> ''; + + CREATE OR REPLACE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id + FROM zoneGeo + LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id + FROM zoneGeo + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + + ELSEIF vParentFk IS NULL THEN + INSERT INTO tNodes + SELECT geoFk + FROM zoneIncluded + WHERE zoneFk = vSelf; + END IF; + + IF vParentFk IS NULL THEN + CREATE OR REPLACE TEMPORARY TABLE tChilds + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM tNodes; + + CREATE OR REPLACE TEMPORARY TABLE tParents + (INDEX(id)) + ENGINE = MEMORY + SELECT id FROM zoneGeo LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM zoneGeo g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF NOT ROW_COUNT() THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE tChilds, tParents; + END IF; + + IF NOT vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id + FROM zoneGeo + WHERE parentFk <=> vParentFk; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tZones + SELECT g.id, + g.name, + g.parentFk, + g.sons, + NOT g.sons OR `type` = 'country' isChecked, + i.isIncluded selected, + g.`depth`, + vSelf + FROM zoneGeo g + JOIN tNodes n ON n.id = g.id + LEFT JOIN zoneIncluded i ON i.geoFk = g.id + AND i.zoneFk = vSelf + ORDER BY g.`depth`, selected DESC, g.name; + + IF vHasInsert THEN + INSERT IGNORE INTO tmp.zoneNodes(geoFk, name, parentFk, sons, isChecked, zoneFk) + SELECT id, + name, + parentFk, + sons, + isChecked, + vSelf + FROM tZones + WHERE selected + OR (selected IS NULL AND vParentFk IS NOT NULL); + ELSE + SELECT id, + name, + parentFk, + sons, + selected + FROM tZones + ORDER BY `depth`, selected DESC, name; + END IF; + + DROP TEMPORARY TABLE tNodes, tZones; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78736,7 +78738,7 @@ BEGIN * @table tmp.zone(id) The zones ids * @param vLanded The delivery date * @return tmp.zoneOption The computed options - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY @@ -78777,13 +78779,13 @@ BEGIN END LIMIT 10000000000000000000 ) t - GROUP BY zoneFk; - + GROUP BY zoneFk; + DELETE t FROM tmp.zoneOption t JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + IF NOT vShowExpiredZones THEN DELETE FROM tmp.zoneOption WHERE shipped < util.VN_CURDATE() @@ -78815,7 +78817,7 @@ BEGIN * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options */ DECLARE vHour TIME DEFAULT TIME(util.VN_NOW()); - + DROP TEMPORARY TABLE IF EXISTS tLandings; CREATE TEMPORARY TABLE tLandings (INDEX (eventFk)) @@ -78894,53 +78896,53 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getPostalCode`(vSelf INT) -BEGIN -/** - * Devuelve los códigos postales incluidos en una zona - */ - DECLARE vGeoFk INT DEFAULT NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; - CREATE TEMPORARY TABLE tmp.zoneNodes ( - geoFk INT, - name VARCHAR(100), - parentFk INT, - sons INT, - isChecked BOOL DEFAULT 0, - zoneFk INT, - PRIMARY KEY zoneNodesPk (zoneFk, geoFk), - INDEX(geoFk)) - ENGINE = MEMORY; - - CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); - - UPDATE tmp.zoneNodes zn - SET isChecked = 0 - WHERE parentFk IS NULL; - - myLoop: LOOP - SET vGeoFk = NULL; - SELECT geoFk INTO vGeoFk - FROM tmp.zoneNodes zn - WHERE NOT isChecked - LIMIT 1; - - CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); - UPDATE tmp.zoneNodes - SET isChecked = TRUE - WHERE geoFk = vGeoFk; - - IF vGeoFk IS NULL THEN - LEAVE myLoop; - END IF; - END LOOP; - - DELETE FROM tmp.zoneNodes - WHERE sons > 0; - - SELECT zn.geoFk, zn.name - FROM tmp.zoneNodes zn - JOIN zone z ON z.id = zn.zoneFk; +BEGIN +/** + * Devuelve los códigos postales incluidos en una zona + */ + DECLARE vGeoFk INT DEFAULT NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneNodes; + CREATE TEMPORARY TABLE tmp.zoneNodes ( + geoFk INT, + name VARCHAR(100), + parentFk INT, + sons INT, + isChecked BOOL DEFAULT 0, + zoneFk INT, + PRIMARY KEY zoneNodesPk (zoneFk, geoFk), + INDEX(geoFk)) + ENGINE = MEMORY; + + CALL zone_getLeaves(vSelf, NULL , NULL, TRUE); + + UPDATE tmp.zoneNodes zn + SET isChecked = 0 + WHERE parentFk IS NULL; + + myLoop: LOOP + SET vGeoFk = NULL; + SELECT geoFk INTO vGeoFk + FROM tmp.zoneNodes zn + WHERE NOT isChecked + LIMIT 1; + + CALL zone_getLeaves(vSelf, vGeoFk, NULL, TRUE); + UPDATE tmp.zoneNodes + SET isChecked = TRUE + WHERE geoFk = vGeoFk; + + IF vGeoFk IS NULL THEN + LEAVE myLoop; + END IF; + END LOOP; + + DELETE FROM tmp.zoneNodes + WHERE sons > 0; + + SELECT zn.geoFk, zn.name + FROM tmp.zoneNodes zn + JOIN zone z ON z.id = zn.zoneFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -78971,7 +78973,7 @@ BEGIN DECLARE vZoneGeo INT; SELECT address_getGeo(vAddressFk) INTO vZoneGeo; - + CALL vn.zone_getFromGeo(vZoneGeo); CALL vn.zone_getOptionsForLanding(vLanded, vShowExpiredZones); CALL vn.zone_excludeFromGeo(vZoneGeo); @@ -78991,7 +78993,7 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zoneWarehouse zw ON zw.zoneFk = zo.zoneFk JOIN vn.`zone` z ON z.id = zo.zoneFk - LEFT JOIN tmp.closedZones cz + LEFT JOIN tmp.closedZones cz ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zw.zoneFk AND zo.shipped = util.VN_CURDATE() @@ -79025,9 +79027,9 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_getState`(vDated DATE) BEGIN /** * Devuelve las zonas y el estado para la fecha solicitada - * + * * @param vDated Fecha en cuestión - */ + */ DROP TEMPORARY TABLE IF EXISTS tmp.zone; CREATE TEMPORARY TABLE tmp.zone ( @@ -79041,7 +79043,7 @@ BEGIN CALL vn.zone_getOptionsForShipment(vDated, TRUE); CALL vn.zone_getClosed(); - + SELECT zo.zoneFk, zo.`hour`etd, (zo.`hour` <= TIME(util.VN_NOW())) isLate, @@ -79051,11 +79053,11 @@ BEGIN FROM tmp.zoneOption zo JOIN vn.zone z ON z.id = zo.zoneFk JOIN vn.zoneWarehouse zw ON zw.zoneFk = z.id - LEFT JOIN tmp.closedZones cz - ON cz.warehouseFk = zw.warehouseFk + LEFT JOIN tmp.closedZones cz + ON cz.warehouseFk = zw.warehouseFk AND cz.zoneFk = zo.zoneFk; - - DROP TEMPORARY TABLE + + DROP TEMPORARY TABLE tmp.closedZones, tmp.zoneOption, tmp.zone; @@ -79081,21 +79083,21 @@ BEGIN /** * Devuelve el listado de agencias disponibles para la fecha, * dirección y almacén pasados. - * + * * @param vAddress * @param vWarehouse warehouse * @param vLanded Fecha de recogida * @select Listado de agencias disponibles */ - + CALL zone_getFromGeo(address_getGeo(vAddress)); CALL zone_getOptionsForLanding(vLanded, FALSE); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, zw.warehouseFk, z.id zoneFk FROM tmp.zoneOption zo @@ -79105,11 +79107,11 @@ BEGIN WHERE zw.warehouseFk = vWarehouse GROUP BY z.agencyModeFk ORDER BY agencyMode; - + DROP TEMPORARY TABLE tmp.zone, tmp.zoneOption; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -79130,7 +79132,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `zone_upcomingDeliveries`() BEGIN DECLARE vForwardDays INT; - + SELECT forwardDays INTO vForwardDays FROM zoneConfig; CALL util.time_createTable(util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL vForwardDays DAY)); @@ -79146,7 +79148,7 @@ BEGIN JOIN zoneEvent e ON e.zoneFk = z.id JOIN tmp.time ti ON ti.dated BETWEEN util.VN_CURDATE() AND TIMESTAMPADD(DAY, vForwardDays, util.VN_CURDATE()); - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; CREATE TEMPORARY TABLE tmp.zoneOption ENGINE = MEMORY SELECT * @@ -79187,7 +79189,7 @@ BEGIN JOIN zoneExclusion e ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed LEFT JOIN zoneExclusionGeo eg ON eg.zoneExclusionFk = e.id WHERE eg.zoneExclusionFk IS NULL; - + SELECT MAX(zo.`hour`) `hour`, zg.`name`, zo.shipped, zo.zoneFk FROM tmp.zoneOption zo JOIN `zone` z ON z.id = zo.zoneFk @@ -79198,7 +79200,7 @@ BEGIN WHERE dm.code = 'DELIVERY' GROUP BY shipped, zg.`name` ORDER BY shipped, zg.`name`; - + DROP TEMPORARY TABLE tmp.time, tLandings; END ;; DELIMITER ; diff --git a/db/tests/vn/item_getBalance.spec.js b/db/tests/vn/item_getBalance.spec.js index 2e24d5ce7..74e1e6659 100644 --- a/db/tests/vn/item_getBalance.spec.js +++ b/db/tests/vn/item_getBalance.spec.js @@ -6,13 +6,13 @@ describe('item_getBalance()', () => { let stmts = []; let params = { - warehouseFk: 1, - itemFk: 1 + itemFk: 1, + warehouseFk: 1 }; const conn = await app.models.Item.dataSource.connector; - stmts.push(new ParameterizedSQL('CALL vn.item_getBalance(?, ?)', [ + stmts.push(new ParameterizedSQL('CALL vn.item_getBalance(?, ?, NULL)', [ params.warehouseFk, params.itemFk ])); diff --git a/db/tests/vn/logAddWithUser.spec.js b/db/tests/vn/logAddWithUser.spec.js deleted file mode 100644 index 8711769d0..000000000 --- a/db/tests/vn/logAddWithUser.spec.js +++ /dev/null @@ -1,42 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -describe('logAddWithUser()', () => { - it('should log any action taken by the user in a table ending in Log', async() => { - let stmts = []; - let stmt; - - stmts.push('START TRANSACTION'); - - let params = { - ticketFk: 1, - userId: 9, - actionCode: 'update', - targetEntity: 'ticket', - description: 'we are testing stuff' - }; - - stmt = new ParameterizedSQL('CALL vn.logAddWithUser(?, ?, ?, ?, ?)', [ - params.ticketFk, - params.userId, - params.actionCode, - params.targetEntity, - params.description - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('SELECT * FROM vn.ticketLog WHERE description = ?', [ - params.description - ]); - let ticketLogIndex = stmts.push(stmt) - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - savedDescription = result[ticketLogIndex][0].description; - - expect(savedDescription).toEqual(params.description); - }); -}); diff --git a/db/tests/vn/ticketCalculateClon.spec.js b/db/tests/vn/ticketCalculateClon.spec.js index 9116d805f..665d52ed0 100644 --- a/db/tests/vn/ticketCalculateClon.spec.js +++ b/db/tests/vn/ticketCalculateClon.spec.js @@ -53,7 +53,8 @@ describe('ticket ticketCalculateClon()', () => { expect(result[orderIndex][0].ticketFk).toBeGreaterThan(newestTicketIdInFixtures); }); - it('should add the ticket to the order containing the original ticket and generate landed value if it was null', async() => { + it('should add the ticket to the order containing the original ' + + 'ticket and generate landed value if it was null', async() => { let stmts = []; let stmt; diff --git a/db/tests/vn/timeControl_calculateByUser.spec.js b/db/tests/vn/timeControl_calculateByUser.spec.js deleted file mode 100644 index 73e00ec3a..000000000 --- a/db/tests/vn/timeControl_calculateByUser.spec.js +++ /dev/null @@ -1,107 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -describe('timeControl_calculateByUser()', () => { - it(`should return today's worked hours`, async() => { - let start = Date.vnNew(); - start.setHours(0, 0, 0, 0); - start.setDate(start.getDate() - 1); - - let end = Date.vnNew(); - end.setHours(0, 0, 0, 0); - end.setDate(end.getDate() + 1); - - let stmts = []; - let stmt; - - stmts.push('START TRANSACTION'); - - stmts.push(` - DROP TEMPORARY TABLE IF EXISTS - tmp.timeControlCalculate, - tmp.timeBusinessCalculate - `); - - let params = { - workerID: 1106, - start: start, - end: end - }; - - stmt = new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ - params.workerID, - params.start, - params.end - ]); - stmts.push(stmt); - - let tableIndex = stmts.push('SELECT * FROM tmp.timeControlCalculate') - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - let [timeControlCalculateTable] = result[tableIndex]; - - expect(timeControlCalculateTable.timeWorkSeconds).toEqual(29400); - }); - - it(`should return the worked hours between last sunday and monday`, async() => { - let lastSunday = Date.vnNew(); - let daysSinceSunday = lastSunday.getDay(); - if (daysSinceSunday === 0) // this means today is sunday but you need the previous sunday :) - daysSinceSunday = 7; - lastSunday.setHours(23, 0, 0, 0); - lastSunday.setDate(lastSunday.getDate() - daysSinceSunday); - - let monday = Date.vnNew(); - let daysSinceMonday = daysSinceSunday - 1; // aiming for monday (today could be monday) - monday.setHours(7, 0, 0, 0); - monday.setDate(monday.getDate() - daysSinceMonday); - - let stmts = []; - let stmt; - - stmts.push('START TRANSACTION'); - - stmts.push(` - DROP TEMPORARY TABLE IF EXISTS - tmp.timeControlCalculate, - tmp.timeBusinessCalculate - `); - - const workerID = 1107; - - stmt = new ParameterizedSQL(` - INSERT INTO vn.workerTimeControl(userFk, timed, manual, direction) - VALUES - (?, ?, 1, 'in'), - (?, ?, 1, 'out') - `, [ - workerID, - lastSunday, - workerID, - monday - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ - workerID, - lastSunday, - monday - ]); - stmts.push(stmt); - - let tableIndex = stmts.push('SELECT * FROM tmp.timeControlCalculate') - 1; - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Ticket.rawStmt(sql); - - let [timeControlCalculateTable] = result[tableIndex]; - - expect(timeControlCalculateTable.timeWorkSeconds).toEqual(30000); - }); -}); diff --git a/db/tests/vn/workerTimeControlCheck.spec.js b/db/tests/vn/workerTimeControlCheck.spec.js deleted file mode 100644 index 0ca1429d4..000000000 --- a/db/tests/vn/workerTimeControlCheck.spec.js +++ /dev/null @@ -1,580 +0,0 @@ -const app = require('vn-loopback/server/server'); -const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; - -// #2261 xdescribe dbtest workerTimeControl_check() -xdescribe('worker workerTimeControl_check()', () => { - it(`should throw an error if the worker can't sign on that tablet`, async() => { - let stmts = []; - let stmt; - const workerId = 1110; - const tabletId = 2; - let err; - stmts.push('START TRANSACTION'); - try { - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - await app.models.Worker.rawStmt(sql); - } catch (e) { - err = e; - } - - expect(err.sqlMessage).toEqual('No perteneces a este departamento.'); - }); - - it('should check that the worker can sign on that tablet', async() => { - let stmts = []; - let stmt; - const workerId = 1110; - const tabletId = 1; - let err; - stmts.push('START TRANSACTION'); - try { - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - await app.models.Worker.rawStmt(sql); - } catch (e) { - err = e; - } - - expect(err).not.toBeDefined(); - }); - - it('should throw an error if the worker with a special category has not finished the 9h break', async() => { - const workerId = 1110; - const tabletId = 1; - let stmts = []; - let stmt; - let sql; - let error; - - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-17,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-32399,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - error = e; - } - - expect(error.sqlMessage).toEqual('Descansos 9 h'); - }); - - it('should check f the worker with a special category has finished the 9h break', async() => { - const workerId = 1110; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-17,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-32401,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err).not.toBeDefined(); - }); - - it('should throw an error if the worker has not finished the 12h break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let sql; - let error; - - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-43199,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - error = e; - } - - expect(error.sqlMessage).toEqual('Descansos 12 h'); - }); - - it('should throw an error if the worker has finished the 12h break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"in"), - (?,TIMESTAMPADD(SECOND,-43201,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err).not.toBeDefined(); - }); - - it('should throw an error if the worker has odd entry records', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in")`, [ - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('Dias con fichadas impares'); - }); - - it('should throw an error if the worker try to sign on a holiday day', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('Holidays'); - }); - - it('should throw an error if the worker try to sign with your contract ended', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`UPDATE vn.business SET ended = DATE_ADD(CURDATE(), INTERVAL -1 DAY) WHERE id = ?`, [ - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-20,NOW()),0,"out")`, [ - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('No hay un contrato en vigor'); - }); - - it('should throw an error if the worker has not finished the 36h weekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - - stmts.push('SET @warn := NULL'); - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-120,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-112,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-144,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-136,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-168,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-160,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-192,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-184,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - - let warningMessageIndex = stmts.push('SELECT @warn AS warning') - 1; - stmts.push('ROLLBACK'); - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Worker.rawStmt(sql); - - expect(result[warningMessageIndex][0].warning).toEqual('Descansos 36 h'); - }); - - it('should check if the worker has finished the 36h weekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - - stmts.push('SET @warn := NULL'); - - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - let warningMessageIndex = stmts.push('SELECT @warn AS warning') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - let result = await app.models.Worker.rawStmt(sql); - - expect(result[warningMessageIndex][0].warning).toBe(null); - }); - - it('should throw an error if the worker has not finished the 72h biweekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-120,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-112,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-144,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-136,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-168,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-160,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-192,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-184,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-216,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-208,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-240,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-232,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-264,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-256,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-289,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-280,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - stmts.push('SELECT @warn AS warning') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err.sqlMessage).toEqual('Descansos 72 h'); - }); - - it('should check if the worker has finished the 72h biweekly break', async() => { - const workerId = 1109; - const tabletId = 1; - let stmts = []; - let stmt; - let err; - stmts.push('START TRANSACTION'); - - stmt = new ParameterizedSQL(`INSERT INTO vn.workerTimeControl(userFk,timed,manual,direction) - VALUES - (?,TIMESTAMPADD(HOUR,-24,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-16,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-48,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-40,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-72,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-64,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-96,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-88,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-120,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-112,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-144,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-136,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-168,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-160,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-192,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-184,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-216,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-208,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-240,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-232,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-264,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-256,NOW()),0,"out"), - (?,TIMESTAMPADD(HOUR,-288,NOW()),0,"in"), - (?,TIMESTAMPADD(HOUR,-280,NOW()),0,"out")`, [ - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId, - workerId - ]); - stmts.push(stmt); - - stmt = new ParameterizedSQL('CALL vn.workerTimeControl_check(?, ?, NULL)', [ - workerId, - tabletId - ]); - stmts.push(stmt); - stmts.push('ROLLBACK'); - - stmts.push('SELECT @warn AS warning') - 1; - - let sql = ParameterizedSQL.join(stmts, ';'); - - try { - await app.models.Worker.rawStmt(sql); - } catch (e) { - await app.models.Worker.rawSql('ROLLBACK'); - err = e; - } - - expect(err).not.toBeDefined(); - }); -}); diff --git a/db/tests/vn/zone_getFromGeo.spec.js b/db/tests/vn/zone_getFromGeo.spec.js index 0dccf92cc..74b6e00cc 100644 --- a/db/tests/vn/zone_getFromGeo.spec.js +++ b/db/tests/vn/zone_getFromGeo.spec.js @@ -7,7 +7,7 @@ describe('zone zone_getFromGeo()', () => { let stmt; stmts.push('START TRANSACTION'); - let geoFk = 17; + let geoFk = 16; stmt = new ParameterizedSQL('CALL zone_getFromGeo(?)', [ geoFk, diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index 1b18eb866..cec0545a0 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -409,11 +409,11 @@ export default { inactiveIcon: 'vn-item-descriptor vn-icon[icon="icon-unavailable"]' }, itemRequest: { - firstRequestItemID: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(7)', - firstRequestQuantity: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(8)', - firstRequestConcept: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(9)', - firstRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(10)', - secondRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(10)', + firstRequestItemID: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(8)', + firstRequestQuantity: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td-editable:nth-child(9)', + firstRequestConcept: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(10)', + firstRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(1) > vn-td:nth-child(11)', + secondRequestStatus: 'vn-item-request vn-tbody > vn-tr:nth-child(2) > vn-td:nth-child(11)', secondRequestDecline: 'vn-item-request vn-tr:nth-child(2) vn-icon-button[icon="thumb_down"]', declineReason: 'vn-textarea[ng-model="$ctrl.denyObservation"]' }, @@ -520,8 +520,7 @@ export default { searchResultDate: 'vn-ticket-summary [label=Landed] span', topbarSearch: 'vn-searchbar', moreMenu: 'vn-ticket-index vn-icon-button[icon=more_vert]', - fourthWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(5)', - fiveWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(6)', + thirdWeeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(4)', weeklyTicket: 'vn-ticket-weekly-index vn-card smart-table slot-table table tbody tr', firstWeeklyTicketDeleteIcon: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) vn-icon-button[icon="delete"]', firstWeeklyTicketAgency: 'vn-ticket-weekly-index vn-card smart-table slot-table tr:nth-child(2) [ng-model="weekly.agencyModeFk"]', @@ -1193,7 +1192,7 @@ export default { secondBuyPacking: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.packing"]', secondBuyWeight: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.weight"]', secondBuyStickers: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.stickers"]', - secondBuyPackage: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-autocomplete[ng-model="buy.packageFk"]', + secondBuyPackage: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-autocomplete[ng-model="buy.packagingFk"]', secondBuyQuantity: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-input-number[ng-model="buy.quantity"]', secondBuyItem: 'vn-entry-buy-index tbody:nth-child(3) > tr:nth-child(1) vn-autocomplete[ng-model="buy.itemFk"]', importButton: 'vn-entry-buy-index vn-icon[icon="publish"]', diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index 3274ae8f1..744b11a72 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule(' deliveryBoss', 'client'); + await page.loginAndModule('deliveryAssistant', 'client'); }); afterAll(async() => { diff --git a/e2e/paths/03-worker/06_create.spec.js b/e2e/paths/03-worker/06_create.spec.js index 07eb57fe4..2accdfc31 100644 --- a/e2e/paths/03-worker/06_create.spec.js +++ b/e2e/paths/03-worker/06_create.spec.js @@ -45,7 +45,7 @@ describe('Worker create path', () => { // should create a new worker and go to worker basic data' await page.pickDate(selectors.workerCreate.birth, new Date(1962, 8, 5)); - await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryBoss'); + await page.autocompleteSearch(selectors.workerCreate.boss, 'deliveryAssistant'); await page.waitToClick(selectors.workerCreate.createButton); message = await page.waitForSnackbar(); await page.waitForState('worker.card.basicData'); diff --git a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js index 6264073f6..5e82306cc 100644 --- a/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js +++ b/e2e/paths/05-ticket/01-sale/02_edit_sale.spec.js @@ -134,14 +134,6 @@ describe('Ticket Edit sale path', () => { await page.accessToSection('ticket.card.sale'); }); - it('should try to add a higher quantity value and then receive an error', async() => { - await page.waitToClick(selectors.ticketSales.firstSaleQuantityCell); - await page.type(selectors.ticketSales.firstSaleQuantity, '11\u000d'); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('The new quantity should be smaller than the old one'); - }); - it('should remove 1 from the first sale quantity', async() => { await page.waitToClick(selectors.ticketSales.firstSaleQuantityCell); await page.waitForSelector(selectors.ticketSales.firstSaleQuantity); @@ -220,7 +212,7 @@ describe('Ticket Edit sale path', () => { it('should log in as salesAssistant and navigate to ticket sales', async() => { await page.loginAndModule('salesAssistant', 'ticket'); - await page.accessToSearchResult('17'); + await page.accessToSearchResult('15'); await page.accessToSection('ticket.card.sale'); }); @@ -324,7 +316,7 @@ describe('Ticket Edit sale path', () => { }); it('should confirm the transfered quantity is the correct one', async() => { - const result = await page.waitToGetProperty(selectors.ticketSales.secondSaleQuantityCell, 'innerText'); + const result = await page.waitToGetProperty(selectors.ticketSales.firstSaleQuantityCell, 'innerText'); expect(result).toContain('20'); }); @@ -378,7 +370,7 @@ describe('Ticket Edit sale path', () => { await page.waitToClick(selectors.ticketSales.moveToNewTicketButton); const message = await page.waitForSnackbar(); - expect(message.text).toContain(`You can't create a ticket for a inactive client`); + expect(message.text).toContain(`You can't create a ticket for an inactive client`); await page.closePopup(); }); diff --git a/e2e/paths/05-ticket/06_basic_data_steps.spec.js b/e2e/paths/05-ticket/06_basic_data_steps.spec.js index 55aec45fb..77f0e0459 100644 --- a/e2e/paths/05-ticket/06_basic_data_steps.spec.js +++ b/e2e/paths/05-ticket/06_basic_data_steps.spec.js @@ -75,7 +75,7 @@ describe('Ticket Edit basic data path', () => { const result = await page .waitToGetProperty(selectors.ticketBasicData.stepTwoTotalPriceDif, 'innerText'); - expect(result).toContain('-€232.75'); + expect(result).toContain('-€228.25'); }); it(`should select a new reason for the changes made then click on finalize`, async() => { diff --git a/e2e/paths/05-ticket/09_weekly.spec.js b/e2e/paths/05-ticket/09_weekly.spec.js index a9cce2ead..74febfd01 100644 --- a/e2e/paths/05-ticket/09_weekly.spec.js +++ b/e2e/paths/05-ticket/09_weekly.spec.js @@ -19,7 +19,7 @@ describe('Ticket descriptor path', () => { it('should count the amount of tickets in the turns section', async() => { const result = await page.countElement(selectors.ticketsIndex.weeklyTicket); - expect(result).toEqual(7); + expect(result).toEqual(5); }); it('should go back to the ticket index then search and access a ticket summary', async() => { @@ -45,7 +45,7 @@ describe('Ticket descriptor path', () => { it('should confirm the ticket 11 was added to thursday', async() => { await page.accessToSection('ticket.weekly.index'); - const result = await page.waitToGetProperty(selectors.ticketsIndex.fourthWeeklyTicket, 'value'); + const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); expect(result).toEqual('Thursday'); }); @@ -80,7 +80,9 @@ describe('Ticket descriptor path', () => { it('should confirm the ticket 11 was added on saturday', async() => { await page.accessToSection('ticket.weekly.index'); - const result = await page.waitToGetProperty(selectors.ticketsIndex.fiveWeeklyTicket, 'value'); + await page.waitForTimeout(5000); + + const result = await page.waitToGetProperty(selectors.ticketsIndex.thirdWeeklyTicket, 'value'); expect(result).toEqual('Saturday'); }); @@ -104,7 +106,7 @@ describe('Ticket descriptor path', () => { await page.doSearch(); const nResults = await page.countElement(selectors.ticketsIndex.searchWeeklyResult); - expect(nResults).toEqual(7); + expect(nResults).toEqual(5); }); it('should update the agency then remove it afterwards', async() => { diff --git a/e2e/paths/06-claim/03_detail.spec.js b/e2e/paths/06-claim/02_detail.spec.js similarity index 98% rename from e2e/paths/06-claim/03_detail.spec.js rename to e2e/paths/06-claim/02_detail.spec.js index ddcfd9302..eb4ac5d71 100644 --- a/e2e/paths/06-claim/03_detail.spec.js +++ b/e2e/paths/06-claim/02_detail.spec.js @@ -1,5 +1,5 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; // #1528 e2e claim/detail xdescribe('Claim detail', () => { diff --git a/e2e/paths/06-claim/02_development.spec.js b/e2e/paths/06-claim/02_development.spec.js deleted file mode 100644 index b7352dcc2..000000000 --- a/e2e/paths/06-claim/02_development.spec.js +++ /dev/null @@ -1,97 +0,0 @@ -import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; - -describe('Claim development', () => { - let browser; - let page; - - beforeAll(async() => { - browser = await getBrowser(); - page = browser.page; - await page.loginAndModule('claimManager', 'claim'); - await page.accessToSearchResult('1'); - await page.accessToSection('claim.card.development'); - }); - - afterAll(async() => { - await browser.close(); - }); - - it('should delete a development and create a new one', async() => { - await page.waitToClick(selectors.claimDevelopment.firstDeleteDevelopmentButton); - await page.waitToClick(selectors.claimDevelopment.addDevelopmentButton); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimReason, 'Baja calidad'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimResult, 'Deshidratacion'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimResponsible, 'Calidad general'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimWorker, 'deliveryNick'); - await page.autocompleteSearch(selectors.claimDevelopment.secondClaimRedelivery, 'Reparto'); - await page.waitToClick(selectors.claimDevelopment.saveDevelopmentButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it(`should redirect to the next section of claims as the role is claimManager`, async() => { - await page.waitForState('claim.card.action'); - }); - - it('should edit a development', async() => { - await page.reloadSection('claim.card.development'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimReason, 'Calor'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimResult, 'Cocido'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimResponsible, 'Calidad general'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimWorker, 'adminAssistantNick'); - await page.autocompleteSearch(selectors.claimDevelopment.firstClaimRedelivery, 'Cliente'); - await page.waitToClick(selectors.claimDevelopment.saveDevelopmentButton); - const message = await page.waitForSnackbar(); - - expect(message.text).toContain('Data saved!'); - }); - - it('should confirm the first development is the expected one', async() => { - await page.reloadSection('claim.card.development'); - const reason = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimReason, 'value'); - - const result = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimResult, 'value'); - - const responsible = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimResponsible, 'value'); - - const worker = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimWorker, 'value'); - - const redelivery = await page - .waitToGetProperty(selectors.claimDevelopment.firstClaimRedelivery, 'value'); - - expect(reason).toEqual('Calor'); - expect(result).toEqual('Baboso/Cocido'); - expect(responsible).toEqual('Calidad general'); - expect(worker).toEqual('adminAssistantNick'); - expect(redelivery).toEqual('Cliente'); - }); - - it('should confirm the second development is the expected one', async() => { - const reason = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimReason, 'value'); - - const result = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimResult, 'value'); - - const responsible = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimResponsible, 'value'); - - const worker = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimWorker, 'value'); - - const redelivery = await page - .waitToGetProperty(selectors.claimDevelopment.secondClaimRedelivery, 'value'); - - expect(reason).toEqual('Baja calidad'); - expect(result).toEqual('Deshidratacion'); - expect(responsible).toEqual('Calidad general'); - expect(worker).toEqual('deliveryNick'); - expect(redelivery).toEqual('Reparto'); - }); -}); diff --git a/e2e/paths/06-claim/04_claim_action.spec.js b/e2e/paths/06-claim/03_claim_action.spec.js similarity index 97% rename from e2e/paths/06-claim/04_claim_action.spec.js rename to e2e/paths/06-claim/03_claim_action.spec.js index 62a0ac232..ac6f72e37 100644 --- a/e2e/paths/06-claim/04_claim_action.spec.js +++ b/e2e/paths/06-claim/03_claim_action.spec.js @@ -1,5 +1,5 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; describe('Claim action path', () => { let browser; diff --git a/e2e/paths/06-claim/05_summary.spec.js b/e2e/paths/06-claim/04_summary.spec.js similarity index 98% rename from e2e/paths/06-claim/05_summary.spec.js rename to e2e/paths/06-claim/04_summary.spec.js index 1333ed01a..dda8484a6 100644 --- a/e2e/paths/06-claim/05_summary.spec.js +++ b/e2e/paths/06-claim/04_summary.spec.js @@ -1,6 +1,6 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; describe('Claim summary path', () => { let browser; diff --git a/e2e/paths/06-claim/06_descriptor.spec.js b/e2e/paths/06-claim/05_descriptor.spec.js similarity index 97% rename from e2e/paths/06-claim/06_descriptor.spec.js rename to e2e/paths/06-claim/05_descriptor.spec.js index 059bd68dd..49912b26a 100644 --- a/e2e/paths/06-claim/06_descriptor.spec.js +++ b/e2e/paths/06-claim/05_descriptor.spec.js @@ -1,5 +1,5 @@ import selectors from '../../helpers/selectors.js'; -import getBrowser from '../../helpers/puppeteer'; +import getBrowser from '../../helpers/puppeteer.js'; describe('Claim descriptor path', () => { let browser; diff --git a/e2e/paths/06-claim/07_note.spec.js b/e2e/paths/06-claim/06_note.spec.js similarity index 100% rename from e2e/paths/06-claim/07_note.spec.js rename to e2e/paths/06-claim/06_note.spec.js diff --git a/e2e/paths/11-zone/01_basic-data.spec.js b/e2e/paths/11-zone/01_basic-data.spec.js index ded40579d..34d08c57f 100644 --- a/e2e/paths/11-zone/01_basic-data.spec.js +++ b/e2e/paths/11-zone/01_basic-data.spec.js @@ -8,7 +8,9 @@ describe('Zone basic data path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryBoss', 'zone'); // turns up the zone module name and route aint the same lol + + await page.loginAndModule('deliveryAssistant', + 'zone'); // turns up the zone module name and route aint the same lol await page.accessToSearchResult('10'); await page.accessToSection('zone.card.basicData'); }); diff --git a/e2e/paths/11-zone/02_descriptor.spec.js b/e2e/paths/11-zone/02_descriptor.spec.js index f3c0e7740..baccc910f 100644 --- a/e2e/paths/11-zone/02_descriptor.spec.js +++ b/e2e/paths/11-zone/02_descriptor.spec.js @@ -8,7 +8,7 @@ describe('Zone descriptor path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('deliveryBoss', 'zone'); + await page.loginAndModule('deliveryAssistant', 'zone'); await page.accessToSearchResult('13'); }); diff --git a/e2e/paths/13-supplier/03_fiscal_data.spec.js b/e2e/paths/13-supplier/03_fiscal_data.spec.js index 891b769c9..96977e708 100644 --- a/e2e/paths/13-supplier/03_fiscal_data.spec.js +++ b/e2e/paths/13-supplier/03_fiscal_data.spec.js @@ -1,20 +1,5 @@ import getBrowser from '../../helpers/puppeteer'; -const $ = { - saveButton: 'vn-supplier-fiscal-data button[type="submit"]', -}; -const $inputs = { - province: 'vn-supplier-fiscal-data [name="province"]', - country: 'vn-supplier-fiscal-data [name="country"]', - postcode: 'vn-supplier-fiscal-data [name="postcode"]', - city: 'vn-supplier-fiscal-data [name="city"]', - socialName: 'vn-supplier-fiscal-data [name="socialName"]', - taxNumber: 'vn-supplier-fiscal-data [name="taxNumber"]', - account: 'vn-supplier-fiscal-data [name="account"]', - sageWithholding: 'vn-supplier-fiscal-data [ng-model="$ctrl.supplier.sageWithholdingFk"]', - sageTaxType: 'vn-supplier-fiscal-data [ng-model="$ctrl.supplier.sageTaxTypeFk"]' -}; - describe('Supplier fiscal data path', () => { let browser; let page; @@ -30,7 +15,7 @@ describe('Supplier fiscal data path', () => { await browser.close(); }); - it('should attempt to edit the fiscal data and check data is saved', async() => { + it('should attempt to edit the fiscal data and check data iss saved', async() => { await page.accessToSection('supplier.card.fiscalData'); const form = 'vn-supplier-fiscal-data form'; @@ -40,16 +25,16 @@ describe('Supplier fiscal data path', () => { postcode: null, city: 'Valencia', socialName: 'Farmer King SL', - taxNumber: 'Wrong tax number', + taxNumber: '12345678Z', account: '0123456789', sageWithholding: 'retencion estimacion objetiva', sageTaxType: 'operaciones no sujetas' }; - const errorMessage = await page.sendForm(form, values); - const message = await page.sendForm(form, { - taxNumber: '12345678Z' + const errorMessage = await page.sendForm(form, { + taxNumber: 'Wrong tax number' }); + const message = await page.sendForm(form, values); await page.reloadSection('supplier.card.fiscalData'); const formValues = await page.fetchForm(form, Object.keys(values)); diff --git a/front/Dockerfile b/front/Dockerfile index 098ee161e..d0ee26904 100644 --- a/front/Dockerfile +++ b/front/Dockerfile @@ -1,4 +1,4 @@ -FROM debian:stretch-slim +FROM debian:bookworm-slim EXPOSE 80 ENV TZ Europe/Madrid diff --git a/front/core/components/index.js b/front/core/components/index.js index eb40d5e1f..cfa46f0cb 100644 --- a/front/core/components/index.js +++ b/front/core/components/index.js @@ -39,6 +39,7 @@ import './range'; import './input-time'; import './input-file'; import './label'; +import './link-phone'; import './list'; import './popover'; import './popup'; diff --git a/front/core/components/link-phone/index.html b/front/core/components/link-phone/index.html new file mode 100644 index 000000000..2789ab75c --- /dev/null +++ b/front/core/components/link-phone/index.html @@ -0,0 +1,14 @@ + + {{$ctrl.phoneNumber}} + + + + + +- diff --git a/front/core/components/link-phone/index.js b/front/core/components/link-phone/index.js new file mode 100644 index 000000000..6f3eec5b1 --- /dev/null +++ b/front/core/components/link-phone/index.js @@ -0,0 +1,15 @@ +import ngModule from '../../module'; +import './style.scss'; +class Controller { + constructor() { + this.phoneNumber = null; + } +} + +ngModule.vnComponent('vnLinkPhone', { + template: require('./index.html'), + controller: Controller, + bindings: { + phoneNumber: '<', + } +}); diff --git a/front/core/components/link-phone/style.scss b/front/core/components/link-phone/style.scss new file mode 100644 index 000000000..22beaf8fd --- /dev/null +++ b/front/core/components/link-phone/style.scss @@ -0,0 +1,7 @@ +vn-link-phone { + vn-icon { + font-size: 1.1em; + vertical-align: bottom; +} +} + diff --git a/front/salix/components/index.js b/front/salix/components/index.js index 555a18450..38b0d0e1f 100644 --- a/front/salix/components/index.js +++ b/front/salix/components/index.js @@ -18,8 +18,8 @@ import './section'; import './summary'; import './topbar/topbar'; import './user-popover'; +import './user-photo'; import './upload-photo'; import './bank-entity'; import './log'; -import './instance-log'; import './sendSms'; diff --git a/front/salix/components/instance-log/index.html b/front/salix/components/instance-log/index.html deleted file mode 100644 index 9794f75c2..000000000 --- a/front/salix/components/instance-log/index.html +++ /dev/null @@ -1,12 +0,0 @@ - - - - - - diff --git a/front/salix/components/instance-log/index.js b/front/salix/components/instance-log/index.js deleted file mode 100644 index 6d8497c2d..000000000 --- a/front/salix/components/instance-log/index.js +++ /dev/null @@ -1,21 +0,0 @@ -import ngModule from '../../module'; -import Section from '../section'; -import './style.scss'; - -export default class Controller extends Section { - open() { - this.$.instanceLog.show(); - } -} - -ngModule.vnComponent('vnInstanceLog', { - controller: Controller, - template: require('./index.html'), - bindings: { - model: '<', - originId: '<', - changedModelId: '<', - changedModel: '@', - url: '@' - } -}); diff --git a/front/salix/components/instance-log/style.scss b/front/salix/components/instance-log/style.scss deleted file mode 100644 index f355e0ac8..000000000 --- a/front/salix/components/instance-log/style.scss +++ /dev/null @@ -1,9 +0,0 @@ -vn-log.vn-instance-log { - vn-card { - width: 900px; - visibility: hidden; - & > * { - visibility: visible; - } - } -} diff --git a/front/salix/components/log/index.html b/front/salix/components/log/index.html index 6a1367e28..c75030100 100644 --- a/front/salix/components/log/index.html +++ b/front/salix/components/log/index.html @@ -28,7 +28,7 @@ + ng-click="$ctrl.showDescriptor($event, userLog)"> @@ -260,3 +260,6 @@ + + diff --git a/front/salix/components/log/index.js b/front/salix/components/log/index.js index 176815eef..854c57f00 100644 --- a/front/salix/components/log/index.js +++ b/front/salix/components/log/index.js @@ -72,6 +72,7 @@ export default class Controller extends Section { $postLink() { this.resetFilter(); + this.defaultFilter(); this.$.$watch( () => this.$.filter, () => this.applyFilter(), @@ -79,6 +80,14 @@ export default class Controller extends Section { ); } + defaultFilter() { + const defaultFilters = ['changedModel', 'changedModelId']; + for (const defaultFilter of defaultFilters) { + if (this[defaultFilter]) + this.$.filter[defaultFilter] = this[defaultFilter]; + } + } + get logs() { return this._logs; } @@ -362,9 +371,11 @@ export default class Controller extends Section { } } - showWorkerDescriptor(event, userLog) { - if (userLog.user?.worker) - this.$.workerDescriptor.show(event.target, userLog.userFk); + showDescriptor(event, userLog) { + if (userLog.user?.worker && this.$state.current.name.split('.')[0] != 'account') + return this.$.workerDescriptor.show(event.target, userLog.userFk); + + this.$.accountDescriptor.show(event.target, userLog.userFk); } } diff --git a/front/salix/components/user-photo/index.html b/front/salix/components/user-photo/index.html new file mode 100644 index 000000000..2d7bbcb82 --- /dev/null +++ b/front/salix/components/user-photo/index.html @@ -0,0 +1,15 @@ +

+ + + +
+ + + diff --git a/front/salix/components/user-photo/index.js b/front/salix/components/user-photo/index.js new file mode 100644 index 000000000..23190c1b6 --- /dev/null +++ b/front/salix/components/user-photo/index.js @@ -0,0 +1,31 @@ +import ngModule from '../../module'; + +export default class Controller { + constructor($element, $, $rootScope) { + Object.assign(this, { + $element, + $, + $rootScope, + }); + } + + onUploadResponse() { + const timestamp = Date.vnNew().getTime(); + const src = this.$rootScope.imagePath('user', '520x520', this.userId); + const zoomSrc = this.$rootScope.imagePath('user', '1600x1600', this.userId); + const newSrc = `${src}&t=${timestamp}`; + const newZoomSrc = `${zoomSrc}&t=${timestamp}`; + + this.$.photo.setAttribute('src', newSrc); + this.$.photo.setAttribute('zoom-image', newZoomSrc); + } +} +Controller.$inject = ['$element', '$scope', '$rootScope']; + +ngModule.vnComponent('vnUserPhoto', { + template: require('./index.html'), + controller: Controller, + bindings: { + userId: '@?', + } +}); diff --git a/front/salix/components/user-photo/locale/es.yml b/front/salix/components/user-photo/locale/es.yml new file mode 100644 index 000000000..7518a98bc --- /dev/null +++ b/front/salix/components/user-photo/locale/es.yml @@ -0,0 +1,6 @@ +My account: Mi cuenta +Local warehouse: Almacén local +Local bank: Banco local +Local company: Empresa local +User warehouse: Almacén del usuario +User company: Empresa del usuario \ No newline at end of file diff --git a/loopback/common/models/application.json b/loopback/common/models/application.json index bc72df315..f79001585 100644 --- a/loopback/common/models/application.json +++ b/loopback/common/models/application.json @@ -13,6 +13,6 @@ "principalType": "ROLE", "principalId": "$everyone", "permission": "ALLOW" - } + } ] } diff --git a/loopback/locale/en.json b/loopback/locale/en.json index fb4e72bd6..26650175d 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -14,7 +14,7 @@ "The default consignee can not be unchecked": "The default consignee can not be unchecked", "Enter an integer different to zero": "Enter an integer different to zero", "Package cannot be blank": "Package cannot be blank", - "The new quantity should be smaller than the old one": "The new quantity should be smaller than the old one", + "The price of the item changed": "The price of the item changed", "The sales of this ticket can't be modified": "The sales of this ticket can't be modified", "Cannot check Equalization Tax in this NIF/CIF": "Cannot check Equalization Tax in this NIF/CIF", "You can't create an order for a frozen client": "You can't create an order for a frozen client", @@ -23,7 +23,7 @@ "Agency cannot be blank": "Agency cannot be blank", "The IBAN does not have the correct format": "The IBAN does not have the correct format", "You can't make changes on the basic data of an confirmed order or with rows": "You can't make changes on the basic data of an confirmed order or with rows", - "You can't create a ticket for a inactive client": "You can't create a ticket for a inactive client", + "You can't create a ticket for an inactive client": "You can't create a ticket for an inactive client", "Worker cannot be blank": "Worker cannot be blank", "You must delete the claim id %d first": "You must delete the claim id %d first", "You don't have enough privileges": "You don't have enough privileges", @@ -187,5 +187,15 @@ "This ticket is not editable.": "This ticket is not editable.", "The ticket doesn't exist.": "The ticket doesn't exist.", "The sales do not exists": "The sales do not exists", - "Ticket without Route": "Ticket without route" + "Ticket without Route": "Ticket without route", + "Select a different client": "Select a different client", + "Fill all the fields": "Fill all the fields", + "Error while generating PDF": "Error while generating PDF", + "Can't invoice to future": "Can't invoice to future", + "This ticket is already invoiced": "This ticket is already invoiced", + "Negative basis of tickets: 23": "Negative basis of tickets: 23", + "Booking completed": "Booking complete", + "The ticket is in preparation": "The ticket [{{ticketId}}]({{{ticketUrl}}}) of the sales person {{salesPersonId}} is in preparation", + "You can only add negative amounts in refund tickets": "You can only add negative amounts in refund tickets" } + diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 73a3920d2..3cc9a9627 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -5,10 +5,10 @@ "The default consignee can not be unchecked": "No se puede desmarcar el consignatario predeterminado", "Unable to default a disabled consignee": "No se puede poner predeterminado un consignatario desactivado", "Can't be blank": "No puede estar en blanco", - "Invalid TIN": "NIF/CIF invalido", + "Invalid TIN": "NIF/CIF inválido", "TIN must be unique": "El NIF/CIF debe ser único", "A client with that Web User name already exists": "Ya existe un cliente con ese Usuario Web", - "Is invalid": "Is invalid", + "Is invalid": "Es inválido", "Quantity cannot be zero": "La cantidad no puede ser cero", "Enter an integer different to zero": "Introduce un entero distinto de cero", "Package cannot be blank": "El embalaje no puede estar en blanco", @@ -35,7 +35,7 @@ "The grade must be an integer greater than or equal to zero": "El grade debe ser un entero mayor o igual a cero", "Sample type cannot be blank": "El tipo de plantilla no puede quedar en blanco", "Description cannot be blank": "Se debe rellenar el campo de texto", - "The new quantity should be smaller than the old one": "La nueva cantidad debe de ser menor que la anterior", + "The price of the item changed": "El precio del artículo cambió", "The value should not be greater than 100%": "El valor no debe de ser mayor de 100%", "The value should be a number": "El valor debe ser un numero", "This order is not editable": "Esta orden no se puede modificar", @@ -55,17 +55,17 @@ "You must delete the claim id %d first": "Antes debes borrar la reclamación %d", "You don't have enough privileges": "No tienes suficientes permisos", "Cannot check Equalization Tax in this NIF/CIF": "No se puede marcar RE en este NIF/CIF", - "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos basicos de una orden con artículos", - "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no esta permitido el uso de la letra ñ", + "You can't make changes on the basic data of an confirmed order or with rows": "No puedes cambiar los datos básicos de una orden con artículos", + "INVALID_USER_NAME": "El nombre de usuario solo debe contener letras minúsculas o, a partir del segundo carácter, números o subguiones, no está permitido el uso de la letra ñ", "You can't create a ticket for a frozen client": "No puedes crear un ticket para un cliente congelado", - "You can't create a ticket for a inactive client": "No puedes crear un ticket para un cliente inactivo", + "You can't create a ticket for an inactive client": "No puedes crear un ticket para un cliente inactivo", "Tag value cannot be blank": "El valor del tag no puede quedar en blanco", "ORDER_EMPTY": "Cesta vacía", "You don't have enough privileges to do that": "No tienes permisos para cambiar esto", "NO SE PUEDE DESACTIVAR EL CONSIGNAT": "NO SE PUEDE DESACTIVAR EL CONSIGNAT", "Error. El NIF/CIF está repetido": "Error. El NIF/CIF está repetido", "Street cannot be empty": "Dirección no puede estar en blanco", - "City cannot be empty": "Cuidad no puede estar en blanco", + "City cannot be empty": "Ciudad no puede estar en blanco", "Code cannot be blank": "Código no puede estar en blanco", "You cannot remove this department": "No puedes eliminar este departamento", "The extension must be unique": "La extensión debe ser unica", @@ -102,8 +102,8 @@ "You can't delete a confirmed order": "No puedes borrar un pedido confirmado", "The social name has an invalid format": "El nombre fiscal tiene un formato incorrecto", "Invalid quantity": "Cantidad invalida", - "This postal code is not valid": "This postal code is not valid", - "is invalid": "is invalid", + "This postal code is not valid": "Este código postal no es válido", + "is invalid": "es inválido", "The postcode doesn't exist. Please enter a correct one": "El código postal no existe. Por favor, introduce uno correcto", "The department name can't be repeated": "El nombre del departamento no puede repetirse", "This phone already exists": "Este teléfono ya existe", @@ -112,8 +112,8 @@ "You cannot delete a ticket that part of it is being prepared": "No puedes eliminar un ticket en el que una parte que está siendo preparada", "You must delete all the buy requests first": "Debes eliminar todas las peticiones de compra primero", "You should specify a date": "Debes especificar una fecha", - "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fín", - "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fín", + "You should specify at least a start or end date": "Debes especificar al menos una fecha de inicio o de fin", + "Start date should be lower than end date": "La fecha de inicio debe ser menor que la fecha de fin", "You should mark at least one week day": "Debes marcar al menos un día de la semana", "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", @@ -144,15 +144,15 @@ "Unable to clone this travel": "No ha sido posible clonar este travel", "This thermograph id already exists": "La id del termógrafo ya existe", "Choose a date range or days forward": "Selecciona un rango de fechas o días en adelante", - "ORDER_ALREADY_CONFIRMED": "ORDER_ALREADY_CONFIRMED", + "ORDER_ALREADY_CONFIRMED": "ORDEN YA CONFIRMADA", "Invalid password": "Invalid password", "Password does not meet requirements": "La contraseña no cumple los requisitos", - "Role already assigned": "Role already assigned", - "Invalid role name": "Invalid role name", - "Role name must be written in camelCase": "Role name must be written in camelCase", - "Email already exists": "Email already exists", - "User already exists": "User already exists", - "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", + "Role already assigned": "Rol ya asignado", + "Invalid role name": "Nombre de rol no válido", + "Role name must be written in camelCase": "El nombre del rol debe escribirse en camelCase", + "Email already exists": "El correo ya existe", + "User already exists": "El/La usuario/a ya existe", + "Absence change notification on the labour calendar": "Notificación de cambio de ausencia en el calendario laboral", "Record of hours week": "Registro de horas semana {{week}} año {{year}} ", "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", @@ -216,6 +216,7 @@ "The worker has hours recorded that day": "El trabajador tiene horas fichadas ese día", "The worker has a marked absence that day": "El trabajador tiene marcada una ausencia ese día", "You can not modify is pay method checked": "No se puede modificar el campo método de pago validado", + "The account size must be exactly 10 characters": "El tamaño de la cuenta debe ser exactamente de 10 caracteres", "Can't transfer claimed sales": "No puedes transferir lineas reclamadas", "You don't have privileges to create refund": "No tienes permisos para crear un abono", "The item is required": "El artículo es requerido", @@ -314,7 +315,15 @@ "This ticket is locked.": "Este ticket está bloqueado.", "This ticket is not editable.": "Este ticket no es editable.", "The ticket doesn't exist.": "No existe el ticket.", - "Social name should be uppercase": "La razón social debe ir en mayúscula", + "Social name should be uppercase": "La razón social debe ir en mayúscula", "Street should be uppercase": "La dirección fiscal debe ir en mayúscula", - "Ticket without Route": "Ticket sin ruta" + "Ticket without Route": "Ticket sin ruta", + "Select a different client": "Seleccione un cliente distinto", + "Fill all the fields": "Rellene todos los campos", + "The response is not a PDF": "La respuesta no es un PDF", + "Ticket without Route": "Ticket sin ruta", + "Booking completed": "Reserva completada", + "The ticket is in preparation": "El ticket [{{ticketId}}]({{{ticketUrl}}}) del comercial {{salesPersonId}} está en preparación", + "The amount cannot be less than the minimum": "La cantidad no puede ser menor que la cantidad mímina", + "quantityLessThanMin": "La cantidad no puede ser menor que la cantidad mímina" } diff --git a/modules/account/back/models/mail-forward.json b/modules/account/back/models/mail-forward.json index edef1bf08..874810b7a 100644 --- a/modules/account/back/models/mail-forward.json +++ b/modules/account/back/models/mail-forward.json @@ -21,5 +21,16 @@ "model": "VnUser", "foreignKey": "account" } - } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$owner", + "permission": "ALLOW" + }, { + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "$owner", + "permission": "ALLOW" + }] } diff --git a/modules/account/front/basic-data/index.html b/modules/account/front/basic-data/index.html index 6f757753e..9fd3506fe 100644 --- a/modules/account/front/basic-data/index.html +++ b/modules/account/front/basic-data/index.html @@ -1,9 +1,9 @@ + + form="form" + save="patch">
diff --git a/modules/account/front/basic-data/index.js b/modules/account/front/basic-data/index.js index 77d3eab26..f6b266bbc 100644 --- a/modules/account/front/basic-data/index.js +++ b/modules/account/front/basic-data/index.js @@ -18,5 +18,8 @@ ngModule.component('vnUserBasicData', { controller: Controller, require: { card: '^vnUserCard' + }, + bindings: { + user: '<' } }); diff --git a/modules/account/front/descriptor-popover/index.html b/modules/account/front/descriptor-popover/index.html new file mode 100644 index 000000000..f3131a84b --- /dev/null +++ b/modules/account/front/descriptor-popover/index.html @@ -0,0 +1,4 @@ + + + + diff --git a/modules/account/front/descriptor-popover/index.js b/modules/account/front/descriptor-popover/index.js new file mode 100644 index 000000000..d7b052473 --- /dev/null +++ b/modules/account/front/descriptor-popover/index.js @@ -0,0 +1,9 @@ +import ngModule from '../module'; +import DescriptorPopover from 'salix/components/descriptor-popover'; + +class Controller extends DescriptorPopover {} + +ngModule.vnComponent('vnAccountDescriptorPopover', { + slotTemplate: require('./index.html'), + controller: Controller +}); diff --git a/modules/account/front/descriptor/index.html b/modules/account/front/descriptor/index.html index 381b2991c..94497aaa9 100644 --- a/modules/account/front/descriptor/index.html +++ b/modules/account/front/descriptor/index.html @@ -2,6 +2,9 @@ module="account" description="$ctrl.user.nickname" summary="$ctrl.$.summary"> + + + this.hasAccount = res.data.exists); } + loadData() { + const filter = { + where: {id: this.$params.id}, + include: { + relation: 'role', + scope: { + fields: ['id', 'name'] + } + } + }; + + return Promise.all([ + this.$http.get(`VnUsers/preview`, {filter}) + .then(res => { + const [user] = res.data; + this.user = user; + }), + this.$http.get(`Accounts/${this.$params.id}/exists`) + .then(res => this.hasAccount = res.data.exists) + ]); + } + onDelete() { return this.$http.delete(`VnUsers/${this.id}`) .then(() => this.$state.go('account.index')) diff --git a/modules/account/front/index.js b/modules/account/front/index.js index 695f36967..4d6aedcae 100644 --- a/modules/account/front/index.js +++ b/modules/account/front/index.js @@ -9,6 +9,7 @@ import './acl'; import './summary'; import './card'; import './descriptor'; +import './descriptor-popover'; import './search-panel'; import './create'; import './basic-data'; diff --git a/modules/account/front/routes.json b/modules/account/front/routes.json index fd33e7122..d7845090b 100644 --- a/modules/account/front/routes.json +++ b/modules/account/front/routes.json @@ -78,7 +78,9 @@ "state": "account.card.basicData", "component": "vn-user-basic-data", "description": "Basic data", - "acl": ["itManagement"] + "params": { + "user": "$ctrl.user" + } }, { "url" : "/log", diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js index cdf3fc2c3..be3baccd7 100644 --- a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.js @@ -75,7 +75,7 @@ module.exports = Self => { try { const worker = await models.Worker.findOne({ - where: {userFk: userId} + where: {id: userId} }, myOptions); const obsevationType = await models.ObservationType.findOne({ diff --git a/modules/claim/back/methods/claim/claimPickupEmail.js b/modules/claim/back/methods/claim/claimPickupEmail.js index 1fd8eb99e..596102a24 100644 --- a/modules/claim/back/methods/claim/claimPickupEmail.js +++ b/modules/claim/back/methods/claim/claimPickupEmail.js @@ -43,9 +43,8 @@ module.exports = Self => { Self.claimPickupEmail = async ctx => { const models = Self.app.models; - const userId = ctx.req.accessToken.userId; const $t = ctx.req.__; // $translate - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const args = Object.assign({}, ctx.args); const params = { @@ -70,9 +69,8 @@ module.exports = Self => { const message = $t('Claim pickup order sent', { claimId: args.id, clientName: claim.client().name, - claimUrl: `${origin}/#!/claim/${args.id}/summary`, + claimUrl: `${url}claim/${args.id}/summary`, }); - const salesPersonId = claim.client().salesPersonFk; if (salesPersonId) await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); diff --git a/modules/claim/back/methods/claim/createFromSales.js b/modules/claim/back/methods/claim/createFromSales.js index 07bdb30aa..30093e43d 100644 --- a/modules/claim/back/methods/claim/createFromSales.js +++ b/modules/claim/back/methods/claim/createFromSales.js @@ -94,13 +94,13 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Created claim', { claimId: newClaim.id, ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, - claimUrl: `${origin}/#!/claim/${newClaim.id}/summary`, + ticketUrl: `${url}ticket/${ticketId}/sale`, + claimUrl: `${url}claim/${newClaim.id}/summary`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); diff --git a/modules/claim/back/methods/claim/getSummary.js b/modules/claim/back/methods/claim/getSummary.js index d384f7ebb..2731f1e8f 100644 --- a/modules/claim/back/methods/claim/getSummary.js +++ b/modules/claim/back/methods/claim/getSummary.js @@ -35,7 +35,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { @@ -109,7 +109,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/claim/back/methods/claim/logs.js b/modules/claim/back/methods/claim/logs.js index f47513e9e..4d1b37822 100644 --- a/modules/claim/back/methods/claim/logs.js +++ b/modules/claim/back/methods/claim/logs.js @@ -1,7 +1,7 @@ const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; -const { mergeFilters, mergeWhere } = require('vn-loopback/util/filter'); +const {mergeFilters, mergeWhere} = require('vn-loopback/util/filter'); module.exports = Self => { Self.remoteMethodCtx('logs', { @@ -12,27 +12,27 @@ module.exports = Self => { arg: 'id', type: 'Number', description: 'The claim id', - http: { source: 'path' } + http: {source: 'path'} }, { arg: 'filter', type: 'object', - http: { source: 'query' } + http: {source: 'query'} }, { arg: 'search', type: 'string', - http: { source: 'query' } + http: {source: 'query'} }, { arg: 'userFk', type: 'number', - http: { source: 'query' } + http: {source: 'query'} }, { arg: 'created', type: 'date', - http: { source: 'query' } + http: {source: 'query'} }, ], returns: { @@ -45,7 +45,7 @@ module.exports = Self => { } }); - Self.logs = async (ctx, id, filter, options) => { + Self.logs = async(ctx, id, filter, options) => { const conn = Self.dataSource.connector; const args = ctx.args; const myOptions = {}; @@ -56,25 +56,25 @@ module.exports = Self => { let where = buildFilter(args, (param, value) => { switch (param) { - case 'search': - return { - or: [ - { changedModel: { like: `%${value}%` } }, - { oldInstance: { like: `%${value}%` } } - ] - }; - case 'userFk': - return { 'cl.userFk': value }; - case 'created': - value.setHours(0, 0, 0, 0); - to = new Date(value); - to.setHours(23, 59, 59, 999); + case 'search': + return { + or: [ + {changedModel: {like: `%${value}%`}}, + {oldInstance: {like: `%${value}%`}} + ] + }; + case 'userFk': + return {'cl.userFk': value}; + case 'created': + value.setHours(0, 0, 0, 0); + to = new Date(value); + to.setHours(23, 59, 59, 999); - return { creationDate: { between: [value, to] } }; + return {creationDate: {between: [value, to]}}; } }); - where = mergeWhere(where, { ['cl.originFk']: id }); - filter = mergeFilters(args.filter, { where }); + where = mergeWhere(where, {['cl.originFk']: id}); + filter = mergeFilters(args.filter, {where}); const stmts = []; diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index 672c94947..a51b114ef 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -56,15 +56,15 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { const nickname = address && address.nickname || destination.description; - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Sent units from ticket', { quantity: sale.quantity, concept: sale.concept, itemId: sale.itemFk, ticketId: sale.ticketFk, nickname: nickname, - ticketUrl: `${origin}/#!/ticket/${sale.ticketFk}/sale`, - itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + ticketUrl: `${url}ticket/${sale.ticketFk}/sale`, + itemUrl: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); } diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 276843c32..95c356374 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -64,7 +64,7 @@ describe('claim regularizeClaim()', () => { claimEnds = await importTicket(ticketId, claimId, userId, options); - for (claimEnd of claimEnds) + for (const claimEnd of claimEnds) await claimEnd.updateAttributes({claimDestinationFk: trashDestination}, options); let claimBefore = await models.Claim.findById(claimId, null, options); diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index d367fb89f..85ada869a 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -2,7 +2,9 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Update Claim', () => { + let url; beforeAll(async() => { + url = await app.models.Url.getUrl(); const activeCtx = { accessToken: {userId: 9}, http: { @@ -29,7 +31,6 @@ describe('Update Claim', () => { it(`should throw an error as the user doesn't have rights`, async() => { const tx = await app.models.Claim.beginTransaction({}); - let error; try { @@ -77,7 +78,7 @@ describe('Update Claim', () => { const ctx = { req: { accessToken: {userId: claimManagerId}, - headers: {origin: 'http://localhost'} + headers: {origin: url} }, args: { observation: 'valid observation', @@ -118,7 +119,7 @@ describe('Update Claim', () => { const ctx = { req: { accessToken: {userId: claimManagerId}, - headers: {origin: 'http://localhost'} + headers: {origin: url} }, args: { observation: 'valid observation', diff --git a/modules/claim/back/methods/claim/updateClaim.js b/modules/claim/back/methods/claim/updateClaim.js index 5486b8eff..d99528413 100644 --- a/modules/claim/back/methods/claim/updateClaim.js +++ b/modules/claim/back/methods/claim/updateClaim.js @@ -91,16 +91,16 @@ module.exports = Self => { // When hasToPickUp has been changed if (salesPerson && changedHasToPickUp && updatedClaim.hasToPickUp) - notifyPickUp(ctx, salesPerson.id, claim); + await notifyPickUp(ctx, salesPerson.id, claim); // When claimState has been changed if (args.claimStateFk) { const newState = await models.ClaimState.findById(args.claimStateFk, null, myOptions); if (newState.hasToNotify) { if (newState.code == 'incomplete') - notifyStateChange(ctx, salesPerson.id, claim, newState.code); + await notifyStateChange(ctx, salesPerson.id, claim, newState.code); if (newState.code == 'canceled') - notifyStateChange(ctx, claim.workerFk, claim, newState.code); + await notifyStateChange(ctx, claim.workerFk, claim, newState.code); } } @@ -115,26 +115,26 @@ module.exports = Self => { async function notifyStateChange(ctx, workerId, claim, state) { const models = Self.app.models; - const origin = ctx.req.headers.origin; + const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t(`Claim state has changed to ${state}`, { claimId: claim.id, clientName: claim.client().name, - claimUrl: `${origin}/#!/claim/${claim.id}/summary` + claimUrl: `${url}claim/${claim.id}/summary` }); await models.Chat.sendCheckingPresence(ctx, workerId, message); } async function notifyPickUp(ctx, workerId, claim) { - const origin = ctx.req.headers.origin; const models = Self.app.models; + const url = await models.Url.getUrl(); const $t = ctx.req.__; // $translate const message = $t('Claim will be picked', { claimId: claim.id, clientName: claim.client().name, - claimUrl: `${origin}/#!/claim/${claim.id}/summary` + claimUrl: `${url}claim/${claim.id}/summary` }); await models.Chat.sendCheckingPresence(ctx, workerId, message); } diff --git a/modules/claim/front/card/index.js b/modules/claim/front/card/index.js index 4a8677c90..5dad0dfc2 100644 --- a/modules/claim/front/card/index.js +++ b/modules/claim/front/card/index.js @@ -8,7 +8,7 @@ class Controller extends ModuleCard { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/claim/front/descriptor/index.html b/modules/claim/front/descriptor/index.html index 5fd198440..8ff1fd791 100644 --- a/modules/claim/front/descriptor/index.html +++ b/modules/claim/front/descriptor/index.html @@ -45,7 +45,7 @@ {{$ctrl.claim.worker.user.name}} diff --git a/modules/claim/front/development/index.html b/modules/claim/front/development/index.html index 1684541ea..7fb3b870e 100644 --- a/modules/claim/front/development/index.html +++ b/modules/claim/front/development/index.html @@ -1,116 +1,2 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + diff --git a/modules/claim/front/development/index.js b/modules/claim/front/development/index.js index 04569f0aa..7b31bd17f 100644 --- a/modules/claim/front/development/index.js +++ b/modules/claim/front/development/index.js @@ -1,17 +1,14 @@ import ngModule from '../module'; import Section from 'salix/components/section'; -import './style.scss'; class Controller extends Section { - onSubmit() { - this.$.watcher.check(); - this.$.model.save().then(() => { - this.$.watcher.notifySaved(); - this.$.watcher.updateOriginalData(); + constructor($element, $) { + super($element, $); + } - if (this.aclService.hasAny(['claimManager'])) - this.$state.go('claim.card.action'); - }); + async $onInit() { + this.$state.go('claim.card.summary', {id: this.$params.id}); + window.location.href = await this.vnApp.getUrl(`claim/${this.$params.id}/development`); } } diff --git a/modules/claim/front/development/index.spec.js b/modules/claim/front/development/index.spec.js deleted file mode 100644 index e2574ccb9..000000000 --- a/modules/claim/front/development/index.spec.js +++ /dev/null @@ -1,31 +0,0 @@ -import './index.js'; -import watcher from 'core/mocks/watcher'; -import crudModel from 'core/mocks/crud-model'; - -describe('Claim', () => { - describe('Component vnClaimDevelopment', () => { - let controller; - let $scope; - - beforeEach(ngModule('claim')); - - beforeEach(inject(($componentController, $rootScope) => { - $scope = $rootScope.$new(); - $scope.watcher = watcher; - $scope.model = crudModel; - const $element = angular.element(''); - controller = $componentController('vnClaimDevelopment', {$element, $scope}); - })); - - describe('onSubmit()', () => { - it(`should redirect to 'claim.card.action' state`, () => { - jest.spyOn(controller.aclService, 'hasAny').mockReturnValue(true); - jest.spyOn(controller.$state, 'go'); - - controller.onSubmit(); - - expect(controller.$state.go).toHaveBeenCalledWith('claim.card.action'); - }); - }); - }); -}); diff --git a/modules/claim/front/development/locale/es.yml b/modules/claim/front/development/locale/es.yml deleted file mode 100644 index c0c4ed184..000000000 --- a/modules/claim/front/development/locale/es.yml +++ /dev/null @@ -1,8 +0,0 @@ -Destination: Destino -Development: Trazabilidad -Reason: Motivo -Result: Consecuencia -Responsible: Responsable -Worker: Trabajador -Redelivery: Devolución -Add line: Añadir Linea \ No newline at end of file diff --git a/modules/claim/front/locale/es.yml b/modules/claim/front/locale/es.yml index f6dac2b83..83ccf1e7b 100644 --- a/modules/claim/front/locale/es.yml +++ b/modules/claim/front/locale/es.yml @@ -17,6 +17,7 @@ Search claim by id or client name: Buscar reclamaciones por identificador o nomb Claim deleted!: Reclamación eliminada! claim: reclamación Photos: Fotos +Development: Trazabilidad Go to the claim: Ir a la reclamación Sale tracking: Líneas preparadas Ticket tracking: Estados del ticket diff --git a/modules/client/back/methods/client/creditRequestEmail.js b/modules/client/back/methods/client/creditRequestEmail.js index 0255949e0..60047de77 100644 --- a/modules/client/back/methods/client/creditRequestEmail.js +++ b/modules/client/back/methods/client/creditRequestEmail.js @@ -1,5 +1,5 @@ module.exports = Self => { - Self.remoteMethodCtx('clientCreditEmail', { + Self.remoteMethodCtx('creditRequestEmail', { description: 'Sends the credit request email with an attached PDF', accessType: 'WRITE', accepts: [ @@ -40,5 +40,5 @@ module.exports = Self => { }, }); - Self.clientCreditEmail = ctx => Self.sendTemplate(ctx, 'credit-request'); + Self.creditRequestEmail = ctx => Self.sendTemplate(ctx, 'credit-request'); }; diff --git a/modules/client/back/methods/client/filter.js b/modules/client/back/methods/client/filter.js index 3bf29501b..eaf4ecf30 100644 --- a/modules/client/back/methods/client/filter.js +++ b/modules/client/back/methods/client/filter.js @@ -80,10 +80,15 @@ module.exports = Self => { Object.assign(myOptions, options); if (args.zoneFk) { - query = `CALL vn.zone_getPostalCode(?)`; - const [geos] = await Self.rawSql(query, [args.zoneFk]); - for (let geo of geos) - postalCode.push(geo.name); + let stmts = []; + stmts.push(new ParameterizedSQL('CALL vn.zone_getPostalCode(?)', [args.zoneFk])); + stmts.push(`SELECT name FROM tmp.zoneNodes`); + stmts.push(`DROP TEMPORARY TABLE tmp.zoneNodes`); + const sql = ParameterizedSQL.join(stmts, ';'); + const [results] = await conn.executeStmt(sql); + + for (let result of results) + postalCode.push(result.name); } const where = buildFilter(ctx.args, (param, value) => { diff --git a/modules/client/back/methods/client/incotermsAuthorizationEmail.js b/modules/client/back/methods/client/incotermsAuthorizationEmail.js index 4a21f20b0..9b3686b07 100644 --- a/modules/client/back/methods/client/incotermsAuthorizationEmail.js +++ b/modules/client/back/methods/client/incotermsAuthorizationEmail.js @@ -33,6 +33,12 @@ module.exports = Self => { type: 'number', description: 'The company id', required: true + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + required: true } ], returns: { diff --git a/modules/client/back/methods/client/incotermsAuthorizationHtml.js b/modules/client/back/methods/client/incotermsAuthorizationHtml.js index 0a6bba0a8..af585b1ae 100644 --- a/modules/client/back/methods/client/incotermsAuthorizationHtml.js +++ b/modules/client/back/methods/client/incotermsAuthorizationHtml.js @@ -21,6 +21,12 @@ module.exports = Self => { type: 'number', description: 'The company id', required: true + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + required: true } ], returns: [ diff --git a/modules/client/back/methods/client/incotermsAuthorizationPdf.js b/modules/client/back/methods/client/incotermsAuthorizationPdf.js index d37e473f1..ffe17c72f 100644 --- a/modules/client/back/methods/client/incotermsAuthorizationPdf.js +++ b/modules/client/back/methods/client/incotermsAuthorizationPdf.js @@ -21,6 +21,12 @@ module.exports = Self => { type: 'number', description: 'The company id', required: true + }, + { + arg: 'addressId', + type: 'number', + description: 'The address id', + required: true } ], returns: [ diff --git a/modules/client/back/methods/client/specs/transactions.spec.js b/modules/client/back/methods/client/specs/transactions.spec.js index 45fffc1de..54e088929 100644 --- a/modules/client/back/methods/client/specs/transactions.spec.js +++ b/modules/client/back/methods/client/specs/transactions.spec.js @@ -1,15 +1,24 @@ const models = require('vn-loopback/server/server').models; describe('Client transactions', () => { + const ctx = {}; + it('should call transactions() method to receive a list of Web Payments from BRUCE WAYNE', async() => { const tx = await models.Client.beginTransaction({}); - try { const options = {transaction: tx}; - const ctx = {}; const filter = {where: {clientFk: 1101}}; - const result = await models.Client.transactions(ctx, filter, options); + const result = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + undefined, + undefined, + undefined, + options + ); expect(result[1].id).toBeTruthy(); @@ -26,9 +35,17 @@ describe('Client transactions', () => { try { const options = {transaction: tx}; - const ctx = {args: {orderFk: 6}}; const filter = {}; - const result = await models.Client.transactions(ctx, filter, options); + const result = await models.Client.transactions( + ctx, + filter, + 6, + undefined, + undefined, + undefined, + undefined, + options + ); const firstRow = result[0]; @@ -47,10 +64,17 @@ describe('Client transactions', () => { try { const options = {transaction: tx}; - - const ctx = {args: {amount: 40}}; const filter = {}; - const result = await models.Client.transactions(ctx, filter, options); + const result = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + 40, + undefined, + undefined, + options + ); const randomIndex = Math.floor(Math.random() * result.length); const transaction = result[randomIndex]; @@ -63,4 +87,43 @@ describe('Client transactions', () => { throw e; } }); + + it('should call transactions() method filtering by date', async() => { + const tx = await models.Client.beginTransaction({}); + + try { + const options = {transaction: tx}; + const filter = {}; + const withResults = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + undefined, + '2000/12/31', + undefined, + options + ); + + expect(withResults.length).toEqual(6); + + const noResults = await models.Client.transactions( + ctx, + filter, + undefined, + undefined, + undefined, + '2099/12/31', + undefined, + options + ); + + expect(noResults.length).toEqual(0); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); diff --git a/modules/client/back/methods/client/transactions.js b/modules/client/back/methods/client/transactions.js index 691910721..a643d69f4 100644 --- a/modules/client/back/methods/client/transactions.js +++ b/modules/client/back/methods/client/transactions.js @@ -12,22 +12,26 @@ module.exports = Self => { arg: 'filter', type: 'object', description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', - http: {source: 'query'} }, { arg: 'orderFk', type: 'number', - http: {source: 'query'} }, { arg: 'clientFk', type: 'number', - http: {source: 'query'} }, { arg: 'amount', type: 'number', - http: {source: 'query'} + }, + { + arg: 'from', + type: 'date', + }, + { + arg: 'to', + type: 'date', } ], returns: { @@ -40,14 +44,15 @@ module.exports = Self => { } }); - Self.transactions = async(ctx, filter, options) => { - const args = ctx.args; + Self.transactions = async(ctx, filter, orderFk, clientFk, amount, from, to, options) => { const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const where = buildFilter(args, (param, value) => { + if (to) to.setHours(23, 59, 59, 999); + + const where = buildFilter({orderFk, clientFk, amount, from, to}, (param, value) => { switch (param) { case 'orderFk': return {'t.id': value}; @@ -55,6 +60,10 @@ module.exports = Self => { return {'t.clientFk': value}; case 'amount': return {'t.amount': (value * 100)}; + case 'from': + return {'t.created': {gte: value}}; + case 'to': + return {'t.created': {lte: value}}; } }); diff --git a/modules/client/back/methods/receipt/filter.js b/modules/client/back/methods/receipt/filter.js index 6df5e73f8..7b5d73dae 100644 --- a/modules/client/back/methods/receipt/filter.js +++ b/modules/client/back/methods/receipt/filter.js @@ -60,7 +60,7 @@ module.exports = Self => { at2.id IS NOT NULL as isCompensation FROM vn.receipt r LEFT JOIN vn.worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN account.user u ON u.id = w.id JOIN vn.company c ON c.id = r.companyFk LEFT JOIN vn.accounting a ON a.id = r.bankFk LEFT JOIN vn.accountingType at2 ON at2.id = a.accountingTypeFk AND at2.code = 'compensation' diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index 296b5e6a7..0cc5df9a2 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -5,6 +5,9 @@ "AddressObservation": { "dataSource": "vn" }, + "AddressShortage": { + "dataSource": "vn" + }, "BankEntity": { "dataSource": "vn" }, diff --git a/modules/client/back/models/addressShortage.json b/modules/client/back/models/addressShortage.json new file mode 100644 index 000000000..1ae8d986c --- /dev/null +++ b/modules/client/back/models/addressShortage.json @@ -0,0 +1,22 @@ +{ + "name": "AddressShortage", + "base": "VnModel", + "options": { + "mysql": { + "table": "addressShortage" + } + }, + "properties": { + "addressFk": { + "type": "number", + "id": true + } + }, + "relations": { + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" + } + } +} \ No newline at end of file diff --git a/modules/client/back/models/client-config.json b/modules/client/back/models/client-config.json index 90d47333d..6c5eae7d7 100644 --- a/modules/client/back/models/client-config.json +++ b/modules/client/back/models/client-config.json @@ -17,6 +17,9 @@ }, "maxCreditRows": { "type": "number" + }, + "defaultCredit": { + "type": "number" } } } \ No newline at end of file diff --git a/modules/client/back/models/client-observation.js b/modules/client/back/models/client-observation.js index f208cb552..e34eedca9 100644 --- a/modules/client/back/models/client-observation.js +++ b/modules/client/back/models/client-observation.js @@ -9,7 +9,7 @@ module.exports = function(Self) { let token = ctx.options.accessToken; let userId = token && token.userId; - Self.app.models.Worker.findOne({where: {userFk: userId}}, (err, user) => { + Self.app.models.Worker.findOne({where: {id: userId}}, (err, user) => { if (err) return next(err); ctx.instance.workerFk = user.id; next(); diff --git a/modules/client/back/models/client-observation.json b/modules/client/back/models/client-observation.json index b8852b186..95d00d374 100644 --- a/modules/client/back/models/client-observation.json +++ b/modules/client/back/models/client-observation.json @@ -41,7 +41,7 @@ "include": { "relation": "worker", "scope": { - "fields": ["userFk"], + "fields": ["id"], "include": { "relation": "user", "scope": { diff --git a/modules/client/back/models/client.js b/modules/client/back/models/client.js index 8e720484f..72b702779 100644 --- a/modules/client/back/models/client.js +++ b/modules/client/back/models/client.js @@ -250,7 +250,12 @@ module.exports = Self => { const loopBackContext = LoopBackContext.getCurrentContext(); const accessToken = {req: loopBackContext.active.accessToken}; - const editVerifiedDataWithoutTaxDataChecked = models.ACL.checkAccessAcl(accessToken, 'Client', 'editVerifiedDataWithoutTaxDataCheck', 'WRITE'); + const editVerifiedDataWithoutTaxDataChecked = models.ACL.checkAccessAcl( + accessToken, + 'Client', + 'editVerifiedDataWithoutTaxDataCheck', + 'WRITE' + ); const hasChanges = orgData && changes; const isTaxDataChecked = hasChanges && (changes.isTaxDataChecked || orgData.isTaxDataChecked); @@ -263,7 +268,9 @@ module.exports = Self => { const sageTransactionTypeChanged = hasChanges && orgData.sageTransactionTypeFk != sageTransactionType; const cantEditVerifiedData = isTaxDataCheckedChanged && !editVerifiedDataWithoutTaxDataChecked; - const cantChangeSageData = (sageTaxTypeChanged || sageTransactionTypeChanged) && !editVerifiedDataWithoutTaxDataChecked; + const cantChangeSageData = (sageTaxTypeChanged || + sageTransactionTypeChanged + ) && !editVerifiedDataWithoutTaxDataChecked; if (cantEditVerifiedData || cantChangeSageData) throw new UserError(`You don't have enough privileges`); @@ -346,8 +353,7 @@ module.exports = Self => { const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const headers = httpRequest.headers; - const origin = headers.origin; + const url = await Self.app.models.Url.getUrl(); const salesPersonId = instance.salesPersonFk; @@ -366,7 +372,7 @@ module.exports = Self => { await email.send(); } - const fullUrl = `${origin}/#!/client/${instance.id}/billing-data`; + const fullUrl = `${url}client/${instance.id}/billing-data`; const message = $t('Changed client paymethod', { clientId: instance.id, clientName: instance.name, @@ -389,8 +395,7 @@ module.exports = Self => { const httpCtx = {req: loopBackContext.active}; const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const headers = httpRequest.headers; - const origin = headers.origin; + const url = await Self.app.models.Url.getUrl(); const models = Self.app.models; let previousWorker = {name: $t('None')}; @@ -411,7 +416,7 @@ module.exports = Self => { currentWorker.name = worker && worker.user().nickname; } - const fullUrl = `${origin}/#!/client/${client.id}/basic-data`; + const fullUrl = `${url}client/${client.id}/basic-data`; const message = $t('Client assignment has changed', { clientId: client.id, clientName: client.name, @@ -445,14 +450,14 @@ module.exports = Self => { if (lastCredit && lastCredit.amount == 0) { const zeroCreditEditor = - await models.ACL.checkAccessAcl(accessToken, 'Client', 'zeroCreditEditor', 'WRITE'); + await models.ACL.checkAccessAcl(accessToken, 'Client', 'zeroCreditEditor', 'WRITE'); const lastCreditIsNotEditable = - await models.ACL.checkAccessAcl( - {req: {accessToken: {userId: lastCredit.workerFk}}}, - 'Client', - 'zeroCreditEditor', - 'WRITE' - ); + await models.ACL.checkAccessAcl( + {req: {accessToken: {userId: lastCredit.workerFk}}}, + 'Client', + 'zeroCreditEditor', + 'WRITE' + ); if (lastCreditIsNotEditable && !zeroCreditEditor) throw new UserError(`You can't change the credit set to zero from a financialBoss`); @@ -478,12 +483,6 @@ module.exports = Self => { if (userRequiredRoles <= 0) throw new UserError(`You don't have enough privileges to set this credit amount`); } - - await models.ClientCredit.create({ - amount: changes.credit, - clientFk: finalState.id, - workerFk: userId - }, ctx.options); }; Self.changeCreditManagement = async function changeCreditManagement(ctx, finalState, changes) { diff --git a/modules/client/back/models/credit-insurance.js b/modules/client/back/models/credit-insurance.js index 6f656d382..84bd90424 100644 --- a/modules/client/back/models/credit-insurance.js +++ b/modules/client/back/models/credit-insurance.js @@ -57,8 +57,8 @@ module.exports = function(Self) { const httpRequest = httpCtx.req.http.req; const $t = httpRequest.__; - const origin = httpRequest.headers.origin; - const fullPath = `${origin}/#!/client/${client.id}/credit-insurance/index`; + const url = await Self.app.models.Url.getUrl(); + const fullPath = `${url}client/${client.id}/credit-insurance/index`; const message = $t('MESSAGE_INSURANCE_CHANGE', { clientId: client.id, clientName: client.name, diff --git a/modules/client/back/models/specs/client.spec.js b/modules/client/back/models/specs/client.spec.js index 201d14bb4..bf134fbf9 100644 --- a/modules/client/back/models/specs/client.spec.js +++ b/modules/client/back/models/specs/client.spec.js @@ -62,13 +62,13 @@ describe('Client Model', () => { const options = {transaction: tx}; const ctx = {options}; - // Set credit to zero by a financialBoss const financialBoss = await models.VnUser.findOne({ where: {name: 'financialBoss'} }, options); ctx.options.accessToken = {userId: financialBoss.id}; - await models.Client.changeCredit(ctx, instance, {credit: 0}); + const testClient = await models.Client.findById(instance.id, options); + await testClient.updateAttributes({credit: 0}, ctx.options); const salesAssistant = await models.VnUser.findOne({ where: {name: 'salesAssistant'} diff --git a/modules/client/front/address/create/index.html b/modules/client/front/address/create/index.html index 96bd8f114..20e7b38e1 100644 --- a/modules/client/front/address/create/index.html +++ b/modules/client/front/address/create/index.html @@ -31,7 +31,7 @@ - + - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) @@ -68,12 +68,12 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> - - @@ -190,4 +190,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/address/edit/index.html b/modules/client/front/address/edit/index.html index 1f0b7d30a..e6b1dc71e 100644 --- a/modules/client/front/address/edit/index.html +++ b/modules/client/front/address/edit/index.html @@ -73,20 +73,20 @@ show-field="code" rule> - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) - - - + @@ -197,12 +197,12 @@ - - @@ -234,4 +234,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/create/index.html b/modules/client/front/create/index.html index e6bf561ef..b5c23ecff 100644 --- a/modules/client/front/create/index.html +++ b/modules/client/front/create/index.html @@ -73,7 +73,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/client/front/credit-management/index.js b/modules/client/front/credit-management/index.js index 856acd27b..7733319e8 100644 --- a/modules/client/front/credit-management/index.js +++ b/modules/client/front/credit-management/index.js @@ -9,7 +9,7 @@ export default class Controller extends Section { include: [{ relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/client/front/credit/index/index.html b/modules/client/front/credit/index/index.html index 989a0129f..d11449268 100644 --- a/modules/client/front/credit/index/index.html +++ b/modules/client/front/credit/index/index.html @@ -24,8 +24,8 @@ {{::credit.created | date:'dd/MM/yyyy HH:mm'}} - {{::credit.worker.user.name}} @@ -41,10 +41,10 @@ ui-sref="client.card.credit.create" vn-acl="teamBoss" vn-acl-action="remove" - vn-tooltip="New credit" + vn-tooltip="New credit" vn-bind="+" fixed-bottom-right> - - \ No newline at end of file + diff --git a/modules/client/front/credit/index/index.js b/modules/client/front/credit/index/index.js index 28160dfeb..3083ac598 100644 --- a/modules/client/front/credit/index/index.js +++ b/modules/client/front/credit/index/index.js @@ -9,7 +9,7 @@ class Controller extends Section { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/client/front/dms/index/index.js b/modules/client/front/dms/index/index.js index a18f195bb..aff64aa4f 100644 --- a/modules/client/front/dms/index/index.js +++ b/modules/client/front/dms/index/index.js @@ -28,7 +28,7 @@ class Controller extends Section { }, { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index d1de87309..c2bf86f70 100644 --- a/modules/client/front/fiscal-data/index.html +++ b/modules/client/front/fiscal-data/index.html @@ -94,7 +94,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/client/front/postcode/index.html b/modules/client/front/postcode/index.html index 8f9f35eb8..b3dbb74d8 100644 --- a/modules/client/front/postcode/index.html +++ b/modules/client/front/postcode/index.html @@ -27,7 +27,7 @@ icon="add_circle" vn-tooltip="New city" ng-click="city.open($event)" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> @@ -45,7 +45,7 @@ icon="add_circle" vn-tooltip="New province" ng-click="province.open($event)" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> @@ -73,4 +73,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index 5df2b29ef..9dce7ec72 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -8,11 +8,12 @@ auto-load="true" url="Samples/visible" fields="[ - 'id', + 'id', 'code', - 'description', + 'description', 'model', 'hasCompany', + 'hasAddress', 'hasPreview', 'datepickerEnabled' ]" @@ -65,10 +66,36 @@ model="ClientSample.companyFk" data="companiesData" show-field="code" - label="Company" + label="Company" ng-if="sampleType.selection.hasCompany" required="true"> + + + {{::!isActive ? '(Inactive)' : ''}} + {{::nickname}} + + , {{::street}}, {{::city}}, {{::province.name}} - {{::agencyMode.name}} + + + + + + + { + if (res.data) + this.addresses = res.data; + }); + } + + getClientDefaultAddress(value) { + let query = `Clients/${value}`; + this.$http.get(query).then(res => { + if (res.data) + this.addressId = res.data.defaultAddressFk; + }); + } } Controller.$inject = ['$element', '$scope', 'vnEmail']; diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index c622913bb..a42e192d0 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -45,11 +45,18 @@ - + + + + - + + + diff --git a/modules/entry/back/locale/buy/en.yml b/modules/entry/back/locale/buy/en.yml index 2db7c7be5..949aa8ed0 100644 --- a/modules/entry/back/locale/buy/en.yml +++ b/modules/entry/back/locale/buy/en.yml @@ -15,4 +15,4 @@ columns: weight: weight entryFk: entry itemFk: item - packageFk: package + packagingFk: package diff --git a/modules/entry/back/locale/buy/es.yml b/modules/entry/back/locale/buy/es.yml index 666bf7640..2aa7688eb 100644 --- a/modules/entry/back/locale/buy/es.yml +++ b/modules/entry/back/locale/buy/es.yml @@ -15,4 +15,4 @@ columns: weight: peso entryFk: entrada itemFk: artículo - packageFk: paquete + packagingFk: paquete diff --git a/modules/entry/back/methods/entry/addFromBuy.js b/modules/entry/back/methods/entry/addFromBuy.js index 82645b166..307c04b97 100644 --- a/modules/entry/back/methods/entry/addFromBuy.js +++ b/modules/entry/back/methods/entry/addFromBuy.js @@ -80,7 +80,7 @@ module.exports = Self => { comissionValue: buyUltimate.comissionValue, packageValue: buyUltimate.packageValue, location: buyUltimate.location, - packageFk: buyUltimate.packageFk, + packagingFk: buyUltimate.packagingFk, price1: buyUltimate.price1, price2: buyUltimate.price2, price3: buyUltimate.price3, diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index ebb271df1..90c1bb9d0 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -44,7 +44,7 @@ module.exports = Self => { 'grouping', 'groupingMode', 'quantity', - 'packageFk', + 'packagingFk', 'weight', 'buyingValue', 'price2', diff --git a/modules/entry/back/methods/entry/importBuys.js b/modules/entry/back/methods/entry/importBuys.js index 1e6f01a5e..812775a1b 100644 --- a/modules/entry/back/methods/entry/importBuys.js +++ b/modules/entry/back/methods/entry/importBuys.js @@ -108,7 +108,7 @@ module.exports = Self => { packing: buy.packing, grouping: buy.grouping, buyingValue: buy.buyingValue, - packageFk: buy.packageFk, + packagingFk: buy.packagingFk, groupingMode: lastBuy.groupingMode, weight: lastBuy.weight }); diff --git a/modules/entry/back/methods/entry/importBuysPreview.js b/modules/entry/back/methods/entry/importBuysPreview.js index 730ecab0a..de8fa732d 100644 --- a/modules/entry/back/methods/entry/importBuysPreview.js +++ b/modules/entry/back/methods/entry/importBuysPreview.js @@ -39,7 +39,7 @@ module.exports = Self => { }, myOptions); if (packaging) - buy.packageFk = packaging.id; + buy.packagingFk = packaging.id; const reference = await models.ItemMatchProperties.findOne({ fields: ['itemFk'], diff --git a/modules/entry/back/methods/entry/latestBuysFilter.js b/modules/entry/back/methods/entry/latestBuysFilter.js index 30d47a2a3..dbf7d2b17 100644 --- a/modules/entry/back/methods/entry/latestBuysFilter.js +++ b/modules/entry/back/methods/entry/latestBuysFilter.js @@ -153,64 +153,63 @@ module.exports = Self => { const date = Date.vnNew(); date.setHours(0, 0, 0, 0); stmt = new ParameterizedSQL(` - SELECT - i.image, - i.id AS itemFk, - i.size, - i.weightByPiece, - it.code, - i.typeFk, - i.family, - i.isActive, - i.minPrice, - i.description, - i.name, - i.subName, - i.packingOut, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7, - i.tag8, - i.value8, - i.tag9, - i.value9, - i.tag10, - i.value10, - t.name AS type, - intr.description AS intrastat, - ori.code AS origin, - b.entryFk, - b.id, - b.quantity, - b.buyingValue, - b.freightValue, - b.isIgnored, - b.packing, - b.grouping, - b.groupingMode, - b.comissionValue, - b.packageValue, - b.price2, - b.price3, - b.ektFk, - b.weight, - b.packageFk, - lb.landing - FROM cache.last_buy lb - LEFT JOIN cache.visible v ON v.item_id = lb.item_id - AND v.calc_id = @calc_id - JOIN item i ON i.id = lb.item_id - JOIN itemType it ON it.id = i.typeFk AND lb.warehouse_id = ? - JOIN buy b ON b.id = lb.buy_id - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN itemType t ON t.id = i.typeFk - LEFT JOIN intrastat intr ON intr.id = i.intrastatFk - LEFT JOIN origin ori ON ori.id = i.originFk - LEFT JOIN entry e ON e.id = b.entryFk AND e.created >= DATE_SUB(? ,INTERVAL 1 YEAR) - LEFT JOIN supplier s ON s.id = e.supplierFk` + SELECT i.image, + i.id AS itemFk, + i.size, + i.weightByPiece, + it.code, + i.typeFk, + i.family, + i.isActive, + i.minPrice, + i.description, + i.name, + i.subName, + i.packingOut, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + i.tag9, + i.value9, + i.tag10, + i.value10, + t.name AS type, + intr.description AS intrastat, + ori.code AS origin, + b.entryFk, + b.id, + b.quantity, + b.buyingValue, + b.freightValue, + b.isIgnored, + b.packing, + b.grouping, + b.groupingMode, + b.comissionValue, + b.packageValue, + b.price2, + b.price3, + b.ektFk, + b.weight, + b.packagingFk, + lb.landing + FROM cache.last_buy lb + LEFT JOIN cache.visible v ON v.item_id = lb.item_id + AND v.calc_id = @calc_id + JOIN item i ON i.id = lb.item_id + JOIN itemType it ON it.id = i.typeFk AND lb.warehouse_id = ? + JOIN buy b ON b.id = lb.buy_id + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN itemType t ON t.id = i.typeFk + LEFT JOIN intrastat intr ON intr.id = i.intrastatFk + LEFT JOIN origin ori ON ori.id = i.originFk + LEFT JOIN entry e ON e.id = b.entryFk AND e.created >= DATE_SUB(? ,INTERVAL 1 YEAR) + LEFT JOIN supplier s ON s.id = e.supplierFk` , [userConfig.warehouseFk, date]); if (ctx.args.tags) { diff --git a/modules/entry/back/methods/entry/specs/importBuys.spec.js b/modules/entry/back/methods/entry/specs/importBuys.spec.js index 4f9204c6a..a352294b9 100644 --- a/modules/entry/back/methods/entry/specs/importBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuys.spec.js @@ -33,7 +33,7 @@ describe('entry import()', () => { packing: 1, size: 1, volume: 1200, - packageFk: '94' + packagingFk: '94' }, { itemFk: 4, @@ -43,7 +43,7 @@ describe('entry import()', () => { packing: 1, size: 25, volume: 1125, - packageFk: '94' + packagingFk: '94' } ] } diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index 41971a64c..c860e228e 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -10,12 +10,12 @@ describe('entry importBuysPreview()', () => { }); }); - it('should return the buys with the calculated packageFk', async() => { + it('should return the buys with the calculated packagingFk', async() => { const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; try { - const expectedPackageFk = '3'; + const expectedPackagingFk = '3'; const buys = [ { itemFk: 1, @@ -39,7 +39,7 @@ describe('entry importBuysPreview()', () => { const randomIndex = Math.floor(Math.random() * result.length); const buy = result[randomIndex]; - expect(buy.packageFk).toEqual(expectedPackageFk); + expect(buy.packagingFk).toEqual(expectedPackagingFk); await tx.rollback(); } catch (e) { diff --git a/modules/entry/back/models/buy.json b/modules/entry/back/models/buy.json index af205533f..30379eaf6 100644 --- a/modules/entry/back/models/buy.json +++ b/modules/entry/back/models/buy.json @@ -103,7 +103,7 @@ "package": { "type": "belongsTo", "model": "Packaging", - "foreignKey": "packageFk" + "foreignKey": "packagingFk" }, "worker": { "type": "belongsTo", diff --git a/modules/entry/front/buy/import/index.html b/modules/entry/front/buy/import/index.html index ccb1a5dac..28396434c 100644 --- a/modules/entry/front/buy/import/index.html +++ b/modules/entry/front/buy/import/index.html @@ -83,14 +83,14 @@ {{::buy.packing | dashIfEmpty}} {{::buy.grouping | dashIfEmpty}} {{::buy.buyingValue | currency: 'EUR':2}} - + + ng-model="buy.packagingFk"> diff --git a/modules/entry/front/buy/index/index.html b/modules/entry/front/buy/index/index.html index 28fdabdb4..203d6c522 100644 --- a/modules/entry/front/buy/index/index.html +++ b/modules/entry/front/buy/index/index.html @@ -88,12 +88,12 @@ diff --git a/modules/entry/front/buy/index/index.js b/modules/entry/front/buy/index/index.js index 649e69286..c991b745b 100644 --- a/modules/entry/front/buy/index/index.js +++ b/modules/entry/front/buy/index/index.js @@ -4,7 +4,7 @@ import Section from 'salix/components/section'; export default class Controller extends Section { saveBuy(buy) { - const missingData = !buy.itemFk || !buy.quantity || !buy.packageFk; + const missingData = !buy.itemFk || !buy.quantity || !buy.packagingFk; if (missingData) return; let options; diff --git a/modules/entry/front/buy/index/index.spec.js b/modules/entry/front/buy/index/index.spec.js index 0e221302c..b9d5fab51 100644 --- a/modules/entry/front/buy/index/index.spec.js +++ b/modules/entry/front/buy/index/index.spec.js @@ -17,7 +17,7 @@ describe('Entry buy', () => { describe('saveBuy()', () => { it(`should call the buys patch route if the received buy has an ID`, () => { - const buy = {id: 1, itemFk: 1, quantity: 1, packageFk: 1}; + const buy = {id: 1, itemFk: 1, quantity: 1, packagingFk: 1}; const query = `Buys/${buy.id}`; diff --git a/modules/entry/front/latest-buys/index.html b/modules/entry/front/latest-buys/index.html index a2cf62da2..16e039cf0 100644 --- a/modules/entry/front/latest-buys/index.html +++ b/modules/entry/front/latest-buys/index.html @@ -104,7 +104,7 @@ Weight - + Package @@ -207,7 +207,7 @@ {{::buy.minPrice | currency: 'EUR':3}} {{::buy.ektFk | dashIfEmpty}} {{::buy.weight}} - {{::buy.packageFk}} + {{::buy.packagingFk}} {{::buy.packingOut}} {{::buy.landing | date: 'dd/MM/yyyy'}} diff --git a/modules/entry/front/latest-buys/index.js b/modules/entry/front/latest-buys/index.js index d9065193e..292c5b805 100644 --- a/modules/entry/front/latest-buys/index.js +++ b/modules/entry/front/latest-buys/index.js @@ -48,7 +48,7 @@ export default class Controller extends Section { } }, { - field: 'packageFk', + field: 'packagingFk', autocomplete: { url: 'Packagings', showField: 'id' @@ -133,7 +133,7 @@ export default class Controller extends Section { case 'price3': case 'ektFk': case 'weight': - case 'packageFk': + case 'packagingFk': return {[`b.${param}`]: value}; } } diff --git a/modules/entry/front/summary/index.html b/modules/entry/front/summary/index.html index d5d3ebf1e..655dcd66f 100644 --- a/modules/entry/front/summary/index.html +++ b/modules/entry/front/summary/index.html @@ -105,7 +105,7 @@ Quantity Stickers - Package + Package Weight Packing Grouping @@ -118,7 +118,7 @@ {{::line.quantity}} {{::line.stickers | dashIfEmpty}} - {{::line.packageFk | dashIfEmpty}} + {{::line.packagingFk | dashIfEmpty}} {{::line.weight}} diff --git a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js index a48664b30..4bba2498f 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js +++ b/modules/invoiceOut/back/methods/invoiceOut/makePdfAndNotify.js @@ -23,7 +23,7 @@ module.exports = Self => { } }); - Self.makePdfAndNotify = async function(ctx, id, printerFk) { + Self.makePdfAndNotify = async function(ctx, id, printerFk, options) { const models = Self.app.models; options = typeof options == 'object' @@ -59,10 +59,10 @@ module.exports = Self => { }; await Self.invoiceEmail(ctx, ref); } catch (err) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = ctx.req.__('Mail not sent', { clientId: client.id, - clientUrl: `${origin}/#!/claim/${id}/summary` + clientUrl: `${url}claim/${id}/summary` }); const salesPersonId = client.salesPersonFk; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js index 6ecfe6015..22891f161 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/refund.spec.js @@ -3,7 +3,7 @@ const LoopBackContext = require('loopback-context'); describe('InvoiceOut refund()', () => { const userId = 5; - const ctx = {req: {accessToken: userId}}; + const ctx = {req: {accessToken: userId}, args: {}}; const withWarehouse = true; const activeCtx = { accessToken: {userId: userId}, diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js new file mode 100644 index 000000000..04f6df299 --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/transferinvoice.spec.js @@ -0,0 +1,68 @@ + +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('InvoiceOut tranferInvoice()', () => { + const activeCtx = { + accessToken: {userId: 5}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + }; + const ctx = {req: activeCtx}; + + beforeEach(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + + it('should return the id of the created issued invoice', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + const args = { + id: '1', + ref: 'T4444444', + newClientFk: 1, + cplusRectificationId: 1, + cplusInvoiceType477Id: 1, + invoiceCorrectionTypeId: 1 + }; + ctx.args = args; + try { + const result = await models.InvoiceOut.transferInvoice( + ctx, + options); + + expect(result).toBeDefined(); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an UserError when it is the same client', async() => { + const tx = await models.InvoiceOut.beginTransaction({}); + const options = {transaction: tx}; + const args = { + id: '1', + ref: 'T1111111', + newClientFk: 1101, + cplusRectificationId: 1, + cplusInvoiceType477Id: 1, + invoiceCorrectionTypeId: 1 + }; + ctx.args = args; + try { + await models.InvoiceOut.transferInvoice( + ctx, + options); + } catch (e) { + expect(e.message).toBe(`Select a different client`); + await tx.rollback(); + } + }); +}); diff --git a/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js new file mode 100644 index 000000000..8a0609b8d --- /dev/null +++ b/modules/invoiceOut/back/methods/invoiceOut/transferInvoice.js @@ -0,0 +1,111 @@ +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('transferInvoice', { + description: 'Transfer an issued invoice to another client', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'Issued invoice id' + }, + { + arg: 'ref', + type: 'string', + required: true + }, + { + arg: 'newClientFk', + type: 'number', + required: true + }, + { + arg: 'cplusRectificationId', + type: 'number', + required: true + }, + { + arg: 'cplusInvoiceType477Id', + type: 'number', + required: true + }, + { + arg: 'invoiceCorrectionTypeId', + type: 'number', + required: true + }, + ], + returns: { + type: 'boolean', + root: true + }, + http: { + path: '/transferInvoice', + verb: 'post' + } + }); + + Self.transferInvoice = async(ctx, options) => { + const models = Self.app.models; + const myOptions = {userId: ctx.req.accessToken.userId}; + const args = ctx.args; + let tx; + if (typeof options == 'object') + Object.assign(myOptions, options); + + const {clientFk} = await models.InvoiceOut.findById(args.id); + + if (clientFk == args.newClientFk) + throw new UserError(`Select a different client`); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + try { + const filterRef = {where: {refFk: args.ref}}; + const tickets = await models.Ticket.find(filterRef, myOptions); + const ticketsIds = tickets.map(ticket => ticket.id); + await models.Ticket.refund(ctx, ticketsIds, null, myOptions); + + const filterTicket = {where: {ticketFk: {inq: ticketsIds}}}; + + const services = await models.TicketService.find(filterTicket, myOptions); + const servicesIds = services.map(service => service.id); + + const sales = await models.Sale.find(filterTicket, myOptions); + const salesIds = sales.map(sale => sale.id); + + const clonedTickets = await models.Sale.clone(ctx, salesIds, servicesIds, null, false, false, myOptions); + const clonedTicketIds = []; + + for (const clonedTicket of clonedTickets) { + await clonedTicket.updateAttribute('clientFk', args.newClientFk, myOptions); + clonedTicketIds.push(clonedTicket.id); + } + + const invoiceIds = await models.Ticket.invoiceTickets(ctx, clonedTicketIds, myOptions); + const [invoiceId] = invoiceIds; + + await models.InvoiceCorrection.create({ + correctingFk: invoiceId, + correctedFk: args.id, + cplusRectificationTypeFk: args.cplusRectificationId, + cplusInvoiceType477Fk: args.cplusInvoiceType477Id, + invoiceCorrectionTypeFk: args.invoiceCorrectionTypeId + }, myOptions); + + if (tx) { + await tx.commit(); + await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + } + + return invoiceId; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/invoiceOut/back/model-config.json b/modules/invoiceOut/back/model-config.json index 9e8b119ab..23246893b 100644 --- a/modules/invoiceOut/back/model-config.json +++ b/modules/invoiceOut/back/model-config.json @@ -31,5 +31,17 @@ }, "ZipConfig": { "dataSource": "vn" + }, + "CplusRectificationType": { + "dataSource": "vn" + }, + "InvoiceCorrectionType": { + "dataSource": "vn" + }, + "InvoiceCorrection": { + "dataSource": "vn" + }, + "CplusInvoiceType477": { + "dataSource": "vn" } } diff --git a/modules/invoiceOut/back/models/cplus-invoice-type-477.json b/modules/invoiceOut/back/models/cplus-invoice-type-477.json new file mode 100644 index 000000000..840a9a7e4 --- /dev/null +++ b/modules/invoiceOut/back/models/cplus-invoice-type-477.json @@ -0,0 +1,19 @@ +{ + "name": "CplusInvoiceType477", + "base": "VnModel", + "options": { + "mysql": { + "table": "cplusInvoiceType477" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "description": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/cplus-rectification-type.json b/modules/invoiceOut/back/models/cplus-rectification-type.json new file mode 100644 index 000000000..e7bfb957f --- /dev/null +++ b/modules/invoiceOut/back/models/cplus-rectification-type.json @@ -0,0 +1,19 @@ +{ + "name": "CplusRectificationType", + "base": "VnModel", + "options": { + "mysql": { + "table": "cplusRectificationType" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "description": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/invoice-correction-type.json b/modules/invoiceOut/back/models/invoice-correction-type.json new file mode 100644 index 000000000..ad3f034ea --- /dev/null +++ b/modules/invoiceOut/back/models/invoice-correction-type.json @@ -0,0 +1,19 @@ +{ + "name": "InvoiceCorrectionType", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceCorrectionType" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "description": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/invoice-correction.json b/modules/invoiceOut/back/models/invoice-correction.json new file mode 100644 index 000000000..48bd172a6 --- /dev/null +++ b/modules/invoiceOut/back/models/invoice-correction.json @@ -0,0 +1,28 @@ +{ + "name": "InvoiceCorrection", + "base": "VnModel", + "options": { + "mysql": { + "table": "invoiceCorrection" + } + }, + "properties": { + "correctingFk": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "correctedFk": { + "type": "number" + }, + "cplusRectificationTypeFk": { + "type": "number" + }, + "cplusInvoiceType477Fk": { + "type": "number" + }, + "invoiceCorrectionTypeFk": { + "type": "number" + } + } +} \ No newline at end of file diff --git a/modules/invoiceOut/back/models/invoice-out.js b/modules/invoiceOut/back/models/invoice-out.js index d3aaf3b3d..ca77c856f 100644 --- a/modules/invoiceOut/back/models/invoice-out.js +++ b/modules/invoiceOut/back/models/invoice-out.js @@ -23,6 +23,7 @@ module.exports = Self => { require('../methods/invoiceOut/getInvoiceDate')(Self); require('../methods/invoiceOut/negativeBases')(Self); require('../methods/invoiceOut/negativeBasesCsv')(Self); + require('../methods/invoiceOut/transferInvoice')(Self); Self.filePath = async function(id, options) { const fields = ['ref', 'issued']; diff --git a/modules/invoiceOut/back/models/printer.json b/modules/invoiceOut/back/models/printer.json index 99003560d..46a031f65 100644 --- a/modules/invoiceOut/back/models/printer.json +++ b/modules/invoiceOut/back/models/printer.json @@ -18,6 +18,13 @@ "isLabeler": { "type": "boolean" } + }, + "relations": { + "sector": { + "type": "belongsTo", + "model": "Sector", + "foreignKey": "sectorFk" + } }, "acls": [{ "accessType": "READ", diff --git a/modules/invoiceOut/front/descriptor-menu/index.html b/modules/invoiceOut/front/descriptor-menu/index.html index 106f8e3cc..7d465f4ea 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.html +++ b/modules/invoiceOut/front/descriptor-menu/index.html @@ -1,3 +1,19 @@ + + + + + + + + Transfer invoice to... + Confirm + + + +
+ + + + #{{id}} - {{::name}} + + + + + {{::description}} + + + + + + + + + +
+
+ + + +
\ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor-menu/index.js b/modules/invoiceOut/front/descriptor-menu/index.js index 38c3c9434..7d2644158 100644 --- a/modules/invoiceOut/front/descriptor-menu/index.js +++ b/modules/invoiceOut/front/descriptor-menu/index.js @@ -125,6 +125,22 @@ class Controller extends Section { this.$state.go('ticket.card.sale', {id: refundTicket.id}); }); } + + transferInvoice() { + const params = { + id: this.invoiceOut.id, + ref: this.invoiceOut.ref, + newClientFk: this.invoiceOut.client.id, + cplusRectificationId: this.cplusRectificationType, + cplusInvoiceType477Id: this.cplusInvoiceType477, + invoiceCorrectionTypeId: this.invoiceCorrectionType + }; + this.$http.post(`InvoiceOuts/transferInvoice`, params).then(res => { + const invoiceId = res.data; + this.vnApp.showSuccess(this.$t('Invoice trasfered!')); + this.$state.go('invoiceOut.card.summary', {id: invoiceId}); + }); + } } Controller.$inject = ['$element', '$scope', 'vnReport', 'vnEmail']; diff --git a/modules/invoiceOut/front/descriptor-menu/locale/en.yml b/modules/invoiceOut/front/descriptor-menu/locale/en.yml index d299155d7..8fad5f25e 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/en.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/en.yml @@ -1 +1,3 @@ The following refund tickets have been created: "The following refund tickets have been created: {{ticketIds}}" +Transfer invoice to...: Transfer invoice to... +Cplus Type: Cplus Type \ No newline at end of file diff --git a/modules/invoiceOut/front/descriptor-menu/locale/es.yml b/modules/invoiceOut/front/descriptor-menu/locale/es.yml index 393efd58c..0f74b5fec 100644 --- a/modules/invoiceOut/front/descriptor-menu/locale/es.yml +++ b/modules/invoiceOut/front/descriptor-menu/locale/es.yml @@ -21,3 +21,5 @@ The invoice PDF document has been regenerated: El documento PDF de la factura ha The email can't be empty: El correo no puede estar vacío The following refund tickets have been created: "Se han creado los siguientes tickets de abono: {{ticketIds}}" Refund...: Abono... +Transfer invoice to...: Transferir factura a... +Cplus Type: Cplus Tipo diff --git a/modules/invoiceOut/front/descriptor-menu/style.scss b/modules/invoiceOut/front/descriptor-menu/style.scss index b68301961..9e4cf4297 100644 --- a/modules/invoiceOut/front/descriptor-menu/style.scss +++ b/modules/invoiceOut/front/descriptor-menu/style.scss @@ -21,4 +21,10 @@ vn-invoice-out-descriptor-menu { font-size: 1.75rem; } } -} \ No newline at end of file + +} +@media screen and (min-width: 1000px) { + .transferInvoice { + min-width: $width-md; + } +} diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js new file mode 100644 index 000000000..2059c28c9 --- /dev/null +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleByCollection.js @@ -0,0 +1,28 @@ +module.exports = Self => { + Self.remoteMethodCtx('itemShelvingSaleByCollection', { + description: 'Insert sales of the collection in itemShelvingSale', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'number', + description: 'The collection id', + required: true, + http: {source: 'path'} + } + ], + http: { + path: `/:id/itemShelvingSaleByCollection`, + verb: 'POST' + } + }); + + Self.itemShelvingSaleByCollection = async(ctx, id, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + await Self.rawSql(`CALL vn.itemShelvingSale_addByCollection(?)`, [id], myOptions); + }; +}; diff --git a/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js new file mode 100644 index 000000000..90e66c066 --- /dev/null +++ b/modules/item/back/methods/item-shelving-sale/itemShelvingSaleSetQuantity.js @@ -0,0 +1,41 @@ +module.exports = Self => { + Self.remoteMethodCtx('itemShelvingSaleSetQuantity', { + description: 'Set quanitity of a sale in itemShelvingSale', + accessType: 'WRITE', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The sale id', + }, + { + arg: 'quantity', + type: 'number', + required: true, + description: 'The quantity to set', + }, + { + arg: 'isItemShelvingSaleEmpty', + type: 'boolean', + required: true, + description: 'True if the shelvingFk is empty ', + } + ], + http: { + path: `/itemShelvingSaleSetQuantity`, + verb: 'POST' + } + }); + + Self.itemShelvingSaleSetQuantity = async(ctx, id, quantity, isItemShelvingSaleEmpty, options) => { + const myOptions = {userId: ctx.req.accessToken.userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + await Self.rawSql(`CALL vn.itemShelvingSale_setQuantity(?, ?, ? )`, + [id, quantity, isItemShelvingSaleEmpty], + myOptions); + }; +}; diff --git a/modules/item/back/methods/item/filter.js b/modules/item/back/methods/item/filter.js index d5de6a954..909b3dff8 100644 --- a/modules/item/back/methods/item/filter.js +++ b/modules/item/back/methods/item/filter.js @@ -180,7 +180,7 @@ module.exports = Self => { LEFT JOIN itemType it ON it.id = i.typeFk LEFT JOIN itemCategory ic ON ic.id = it.categoryFk LEFT JOIN worker w ON w.id = it.workerFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN account.user u ON u.id = w.id LEFT JOIN intrastat intr ON intr.id = i.intrastatFk LEFT JOIN producer pr ON pr.id = i.producerFk LEFT JOIN origin ori ON ori.id = i.originFk diff --git a/modules/item/back/methods/item/getCard.js b/modules/item/back/methods/item/getCard.js index c4ee09d95..49ce3636f 100644 --- a/modules/item/back/methods/item/getCard.js +++ b/modules/item/back/methods/item/getCard.js @@ -34,7 +34,7 @@ module.exports = Self => { include: [{ relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js index 6cd9d9511..17a38cf07 100644 --- a/modules/item/back/methods/item/getSummary.js +++ b/modules/item/back/methods/item/getSummary.js @@ -38,7 +38,7 @@ module.exports = Self => { include: [{ relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/item/back/methods/item/lastEntriesFilter.js b/modules/item/back/methods/item/lastEntriesFilter.js index 83a8fe7a2..5aafbb4f6 100644 --- a/modules/item/back/methods/item/lastEntriesFilter.js +++ b/modules/item/back/methods/item/lastEntriesFilter.js @@ -29,44 +29,44 @@ module.exports = Self => { Object.assign(myOptions, options); const stmt = new ParameterizedSQL( - `SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.id AS buyFk, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.grouping, - b.groupingMode, - b.weight, - i.stems, - b.quantity, - b.buyingValue + - b.freightValue + - b.comissionValue + - b.packageValue AS cost, - b.buyingValue, - b.freightValue, - b.comissionValue, - b.packageValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id`); + `SELECT w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.id AS buyFk, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.grouping, + b.groupingMode, + b.weight, + i.stems, + b.quantity, + b.buyingValue + + b.freightValue + + b.comissionValue + + b.packageValue AS cost, + b.buyingValue, + b.freightValue, + b.comissionValue, + b.packageValue, + b.packagingFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id` + ); stmt.merge(conn.makeSuffix(filter)); return conn.executeStmt(stmt, myOptions); diff --git a/modules/item/back/methods/item/setVisibleDiscard.js b/modules/item/back/methods/item/setVisibleDiscard.js index bcdda1ced..08cc507c3 100644 --- a/modules/item/back/methods/item/setVisibleDiscard.js +++ b/modules/item/back/methods/item/setVisibleDiscard.js @@ -32,6 +32,6 @@ module.exports = Self => { Self.setVisibleDiscard = async(ctx, itemFk, warehouseFk, quantity, addressFk) => { const query = `CALL vn.item_setVisibleDiscard(?, ?, ?, ?)`; - await Self.rawSql(query, [itemFk, warehouseFk, quantity, addressFk]); + await Self.rawSql(query, [itemFk, warehouseFk, quantity, addressFk], {userId: ctx.req.accessToken.userId}); }; }; diff --git a/modules/item/back/models/item-shelving-placement-supply.json b/modules/item/back/models/item-shelving-placement-supply.json index a54013e05..18d0a8d56 100644 --- a/modules/item/back/models/item-shelving-placement-supply.json +++ b/modules/item/back/models/item-shelving-placement-supply.json @@ -26,11 +26,17 @@ "shelving": { "type": "string" }, + "subName": { + "type": "string" + }, "packing": { "type": "number" }, "stock": { "type": "number" + }, + "size": { + "type": "number" } } } \ No newline at end of file diff --git a/modules/item/back/models/item-shelving-sale.js b/modules/item/back/models/item-shelving-sale.js index b89be9f00..e2d27564a 100644 --- a/modules/item/back/models/item-shelving-sale.js +++ b/modules/item/back/models/item-shelving-sale.js @@ -1,3 +1,5 @@ module.exports = Self => { require('../methods/item-shelving-sale/filter')(Self); + require('../methods/item-shelving-sale/itemShelvingSaleByCollection')(Self); + require('../methods/item-shelving-sale/itemShelvingSaleSetQuantity')(Self); }; diff --git a/modules/item/back/models/item-shelving.json b/modules/item/back/models/item-shelving.json index ff9ecabe3..61d05539e 100644 --- a/modules/item/back/models/item-shelving.json +++ b/modules/item/back/models/item-shelving.json @@ -20,10 +20,16 @@ }, "created": { "type": "date" + }, + "grouping": { + "type": "number" }, "isChecked": { "type": "boolean" }, + "packing": { + "type": "number" + }, "visible": { "type": "number" }, @@ -41,6 +47,11 @@ "type": "belongsTo", "model": "VnUser", "foreignKey": "userFk" + }, + "shelving": { + "type": "belongsTo", + "model": "Shelving", + "foreignKey": "shelvingFk" } } } diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index e99dcd996..6db1f5efc 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -131,6 +131,9 @@ "nonRecycledPlastic": { "type": "number" }, + "minQuantity": { + "type": "number" + }, "packingOut": { "type": "number" }, @@ -154,6 +157,10 @@ "mysql":{ "columnName": "doPhoto" } + }, + "minQuantity": { + "type": "number", + "description": "Min quantity" } }, "relations": { diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index fba4d679c..426c17800 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -33,6 +33,8 @@ rule info="Full name calculates based on tags 1-3. Is not recommended to change it manually"> + + + + +
{{::name}}
+
+ #{{::id}} +
+
+ + + + +
- - -
{{::name}}
-
- #{{::id}} -
-
- - - - -
+ +
{{$ctrl.item.itemType.worker.user.name}} diff --git a/modules/item/front/last-entries/index.html b/modules/item/front/last-entries/index.html index 609cdb7fa..429955ef5 100644 --- a/modules/item/front/last-entries/index.html +++ b/modules/item/front/last-entries/index.html @@ -45,7 +45,7 @@ Quantity Cost Kg. - Cube + Cube Provider
@@ -94,7 +94,7 @@ {{::entry.weight | dashIfEmpty}} - {{::entry.packageFk | dashIfEmpty}} + {{::entry.packagingFk | dashIfEmpty}} {{::entry.supplier | dashIfEmpty}} diff --git a/modules/item/front/last-entries/index.js b/modules/item/front/last-entries/index.js index 0c6804838..31616f8a7 100644 --- a/modules/item/front/last-entries/index.js +++ b/modules/item/front/last-entries/index.js @@ -71,7 +71,7 @@ class Controller extends Section { switch (param) { case 'id': case 'quantity': - case 'packageFk': + case 'packagingFk': return {[`b.${param}`]: value}; case 'supplierFk': return {[`s.id`]: value}; diff --git a/modules/item/front/request/index.html b/modules/item/front/request/index.html index c505b3a09..03c8db8ec 100644 --- a/modules/item/front/request/index.html +++ b/modules/item/front/request/index.html @@ -26,6 +26,7 @@ Ticket ID Shipped Description + Requester Requested Price Atender @@ -51,6 +52,13 @@ {{::request.description}} + + + {{::request.requesterName}} + + {{::request.quantity}} {{::request.price | currency: 'EUR':2}} @@ -78,8 +86,8 @@ - {{request.itemDescription}} @@ -106,13 +114,13 @@ - - - @@ -141,24 +149,24 @@ ng-click="contextmenu.filterBySelection()"> Filter by selection
- Exclude selection - Remove filter - Remove all filters - Copy value
- \ No newline at end of file + diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html index fcc267b4d..5fe84591f 100644 --- a/modules/item/front/summary/index.html +++ b/modules/item/front/summary/index.html @@ -70,7 +70,7 @@ {{$ctrl.summary.item.itemType.worker.user.name}} @@ -128,6 +128,9 @@ + +

diff --git a/modules/item/front/summary/locale/es.yml b/modules/item/front/summary/locale/es.yml index 2e78841ae..80988c491 100644 --- a/modules/item/front/summary/locale/es.yml +++ b/modules/item/front/summary/locale/es.yml @@ -2,3 +2,4 @@ Barcode: Códigos de barras Other data: Otros datos Go to the item: Ir al artículo WarehouseFk: Calculado sobre el almacén de {{ warehouseName }} +Minimum sales quantity: Cantidad mínima de venta diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 4f9edd11c..693ae122f 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -215,7 +215,7 @@ module.exports = Self => { LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); if (args.orderFk) { diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js index 0d83f9f4a..722f3e096 100644 --- a/modules/order/back/methods/order/catalogFilter.js +++ b/modules/order/back/methods/order/catalogFilter.js @@ -100,31 +100,32 @@ module.exports = Self => { )); stmt = new ParameterizedSQL(` - SELECT - i.id, - i.name, - i.subName, - i.image, - i.tag5, - i.value5, - i.tag6, - i.value6, - i.tag7, - i.value7, - i.tag8, - i.value8, - i.stars, - tci.price, - tci.available, - w.lastName AS lastName, - w.firstName, - tci.priceKg, - ink.hex + SELECT i.id, + i.name, + i.subName, + i.image, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.tag8, + i.value8, + i.stars, + tci.price, + tci.available, + w.lastName, + w.firstName, + tci.priceKg, + ink.hex, + i.minQuantity FROM tmp.ticketCalculateItem tci JOIN vn.item i ON i.id = tci.itemFk JOIN vn.itemType it ON it.id = i.typeFk JOIN vn.worker w on w.id = it.workerFk - LEFT JOIN vn.ink ON ink.id = i.inkFk`); + LEFT JOIN vn.ink ON ink.id = i.inkFk + `); // Apply order by tag if (orderBy.isTag) { diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 10185af7e..44d8ccb10 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -169,7 +169,7 @@ module.exports = Self => { LEFT JOIN agencyMode am ON am.id = o.agency_id LEFT JOIN client c ON c.id = o.customer_id LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN company co ON co.id = o.company_id LEFT JOIN orderTicket ot ON ot.orderFk = o.id LEFT JOIN ticket t ON t.id = ot.ticketFk diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index fca728855..5d60211ed 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -8,12 +8,12 @@
- @@ -37,13 +37,28 @@ value="{{::item.value7}}">
- - + + + + + + + + + + {{::item.minQuantity}} + + @@ -69,4 +84,4 @@ - \ No newline at end of file + diff --git a/modules/order/front/catalog-view/locale/es.yml b/modules/order/front/catalog-view/locale/es.yml index 82fe5e9e8..8fb3c7896 100644 --- a/modules/order/front/catalog-view/locale/es.yml +++ b/modules/order/front/catalog-view/locale/es.yml @@ -1 +1,2 @@ Order created: Orden creada +Minimal quantity: Cantidad mínima \ No newline at end of file diff --git a/modules/order/front/catalog-view/style.scss b/modules/order/front/catalog-view/style.scss index 87f70cde5..1e48745ca 100644 --- a/modules/order/front/catalog-view/style.scss +++ b/modules/order/front/catalog-view/style.scss @@ -44,4 +44,7 @@ vn-order-catalog { height: 30px; position: relative; } -} \ No newline at end of file + .alert { + color: $color-alert; + } +} diff --git a/modules/order/front/summary/index.html b/modules/order/front/summary/index.html index 3622ae932..218359992 100644 --- a/modules/order/front/summary/index.html +++ b/modules/order/front/summary/index.html @@ -48,8 +48,10 @@ - + + diff --git a/modules/route/back/methods/route/downloadCmrsZip.js b/modules/route/back/methods/route/downloadCmrsZip.js new file mode 100644 index 000000000..532e019b6 --- /dev/null +++ b/modules/route/back/methods/route/downloadCmrsZip.js @@ -0,0 +1,71 @@ +const JSZip = require('jszip'); +const axios = require('axios'); +const UserError = require('vn-loopback/util/user-error'); + +module.exports = Self => { + Self.remoteMethodCtx('downloadCmrsZip', { + description: 'Download a zip file with multiple cmrs pdfs', + accessType: 'READ', + accepts: [ + { + arg: 'ids', + type: 'string', + description: 'The cmrs ids', + } + ], + 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: '/downloadCmrsZip', + verb: 'GET' + } + }); + + 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') + Object.assign(myOptions, options); + + const zipConfig = await models.ZipConfig.findOne(null, myOptions); + let totalSize = 0; + ids = ids.split(','); + try { + for (let id of ids) { + if (zipConfig && totalSize > zipConfig.maxSize) throw new UserError('Files are too large'); + const response = await axios.get( + `${ctx.req.headers.referer}api/Routes/${id}/cmr?access_token=${token.id}`, { + ...myOptions, + 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; + } + }; +}; diff --git a/modules/route/back/methods/route/filter.js b/modules/route/back/methods/route/filter.js index fdec84d4d..fc35e979f 100644 --- a/modules/route/back/methods/route/filter.js +++ b/modules/route/back/methods/route/filter.js @@ -111,7 +111,7 @@ module.exports = Self => { let stmt; stmt = new ParameterizedSQL( - `SELECT + `SELECT r.id, r.workerFk, r.created, @@ -134,7 +134,7 @@ module.exports = Self => { LEFT JOIN agencyMode am ON am.id = r.agencyModeFk LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk` + LEFT JOIN account.user u ON u.id = w.id` ); stmt.merge(conn.makeSuffix(filter)); diff --git a/modules/route/back/methods/route/getExternalCmrs.js b/modules/route/back/methods/route/getExternalCmrs.js index 7b3772c9e..4750e53a1 100644 --- a/modules/route/back/methods/route/getExternalCmrs.js +++ b/modules/route/back/methods/route/getExternalCmrs.js @@ -22,6 +22,11 @@ module.exports = Self => { type: 'integer', description: 'The worker id', }, + { + arg: 'routeFk', + type: 'integer', + description: 'The route id', + }, { arg: 'country', type: 'string', @@ -57,6 +62,7 @@ module.exports = Self => { filter, cmrFk, ticketFk, + routeFk, country, clientFk, hasCmrDms, @@ -66,6 +72,7 @@ module.exports = Self => { const params = { cmrFk, ticketFk, + routeFk, country, clientFk, hasCmrDms, @@ -89,37 +96,38 @@ module.exports = Self => { let stmts = []; const stmt = new ParameterizedSQL(` - SELECT * - FROM ( - SELECT t.cmrFk, - t.id ticketFk, - co.country, - t.clientFk, - IF(sub.id, TRUE, FALSE) hasCmrDms, - DATE(t.shipped) shipped - FROM ticket t - JOIN ticketState ts ON ts.ticketFk = t.id - JOIN state s ON s.id = ts.stateFk - JOIN alertLevel al ON al.id = s.alertLevel - JOIN client c ON c.id = t.clientFk - JOIN address a ON a.id = t.addressFk - JOIN province p ON p.id = a.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN agencyMode am ON am.id = t.agencyModeFk - JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk - JOIN warehouse w ON w.id = t.warehouseFk - LEFT JOIN ( - SELECT td.ticketFk, d.id - FROM ticketDms td - JOIN dms d ON d.id = td.dmsFk - JOIN dmsType dt ON dt.id = d.dmsTypeFk - WHERE dt.name = 'cmr' - ) sub ON sub.ticketFk = t.id - WHERE co.code <> 'ES' - AND am.name <> 'ABONO' - AND w.code = 'ALG' - AND dm.code = 'DELIVERY' - AND t.cmrFk + SELECT * + FROM ( + SELECT t.cmrFk, + t.id ticketFk, + t.routeFk, + co.country, + t.clientFk, + IF(sub.id, TRUE, FALSE) hasCmrDms, + DATE(t.shipped) shipped + FROM ticket t + JOIN ticketState ts ON ts.ticketFk = t.id + JOIN state s ON s.id = ts.stateFk + JOIN alertLevel al ON al.id = s.alertLevel + JOIN client c ON c.id = t.clientFk + JOIN address a ON a.id = t.addressFk + JOIN province p ON p.id = a.provinceFk + JOIN country co ON co.id = p.countryFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + JOIN warehouse w ON w.id = t.warehouseFk + LEFT JOIN ( + SELECT td.ticketFk, d.id + FROM ticketDms td + JOIN dms d ON d.id = td.dmsFk + JOIN dmsType dt ON dt.id = d.dmsTypeFk + WHERE dt.name = 'cmr' + ) sub ON sub.ticketFk = t.id + WHERE co.code <> 'ES' + AND am.name <> 'ABONO' + AND w.code = 'ALG' + AND dm.code = 'DELIVERY' + AND t.cmrFk ) sub `); diff --git a/modules/route/back/methods/route/summary.js b/modules/route/back/methods/route/summary.js index 10cfe38ee..acd17759d 100644 --- a/modules/route/back/methods/route/summary.js +++ b/modules/route/back/methods/route/summary.js @@ -33,7 +33,7 @@ module.exports = Self => { }, { relation: 'worker', scope: { - fields: ['id', 'userFk'], + fields: ['id'], include: [ { relation: 'user', diff --git a/modules/route/back/models/roadmap.json b/modules/route/back/models/roadmap.json index 7ca8fe0f6..2f6bb8c02 100644 --- a/modules/route/back/models/roadmap.json +++ b/modules/route/back/models/roadmap.json @@ -47,7 +47,7 @@ "worker": { "type": "belongsTo", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" }, "supplier": { "type": "belongsTo", diff --git a/modules/route/back/models/route.js b/modules/route/back/models/route.js index 7e61acf25..65fa43ab5 100644 --- a/modules/route/back/models/route.js +++ b/modules/route/back/models/route.js @@ -16,6 +16,7 @@ module.exports = Self => { require('../methods/route/downloadZip')(Self); require('../methods/route/cmr')(Self); require('../methods/route/getExternalCmrs')(Self); + require('../methods/route/downloadCmrsZip')(Self); Self.validate('kmStart', validateDistance, { message: 'Distance must be lesser than 1000' diff --git a/modules/route/front/card/index.js b/modules/route/front/card/index.js index 6bf233c0a..07b5a547c 100644 --- a/modules/route/front/card/index.js +++ b/modules/route/front/card/index.js @@ -41,7 +41,7 @@ class Controller extends ModuleCard { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/route/front/descriptor/index.html b/modules/route/front/descriptor/index.html index 6d6fb082e..4e7e99f1a 100644 --- a/modules/route/front/descriptor/index.html +++ b/modules/route/front/descriptor/index.html @@ -15,14 +15,14 @@ Update volume Delete route @@ -31,23 +31,23 @@
@@ -72,4 +72,4 @@ - \ No newline at end of file + diff --git a/modules/route/front/descriptor/index.js b/modules/route/front/descriptor/index.js index aa47044b1..4377ac617 100644 --- a/modules/route/front/descriptor/index.js +++ b/modules/route/front/descriptor/index.js @@ -79,7 +79,7 @@ class Controller extends Descriptor { }, { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/route/front/roadmap/summary/index.html b/modules/route/front/roadmap/summary/index.html index e6b50601e..9fab0bf87 100644 --- a/modules/route/front/roadmap/summary/index.html +++ b/modules/route/front/roadmap/summary/index.html @@ -25,7 +25,10 @@ + > + { { relation: 'worker', scope: { - fields: ['id', 'userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/shelving/back/model-config.json b/modules/shelving/back/model-config.json index c26c39d38..89a0832b0 100644 --- a/modules/shelving/back/model-config.json +++ b/modules/shelving/back/model-config.json @@ -10,5 +10,8 @@ }, "Sector": { "dataSource": "vn" + }, + "Train": { + "dataSource": "vn" } } \ No newline at end of file diff --git a/modules/shelving/back/models/shelving.json b/modules/shelving/back/models/shelving.json index 5f60318a5..3103b5a4a 100644 --- a/modules/shelving/back/models/shelving.json +++ b/modules/shelving/back/models/shelving.json @@ -9,12 +9,11 @@ "properties": { "id": { "type": "number", - "id": true, - "description": "Identifier" + "description": "Identifier", + "id": true }, "code": { - "type": "string", - "required": true + "type": "string" }, "parkingFk": { "type": "number" @@ -41,7 +40,7 @@ "worker": { "type": "belongsTo", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" } } } diff --git a/modules/shelving/back/models/train.json b/modules/shelving/back/models/train.json new file mode 100644 index 000000000..cc819664b --- /dev/null +++ b/modules/shelving/back/models/train.json @@ -0,0 +1,19 @@ +{ + "name": "Train", + "options": { + "mysql": { + "table": "train" + } + }, + "properties": { + "id": { + "type": "number", + "id": true + }, + "name": { + "type": "string", + "required": true + } + + } +} diff --git a/modules/shelving/front/card/index.js b/modules/shelving/front/card/index.js index 5e2ea9b12..4f571d876 100644 --- a/modules/shelving/front/card/index.js +++ b/modules/shelving/front/card/index.js @@ -7,7 +7,7 @@ class Controller extends ModuleCard { include: [ {relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/shelving/front/summary/index.js b/modules/shelving/front/summary/index.js index 10a905f1d..91f8e2aa7 100644 --- a/modules/shelving/front/summary/index.js +++ b/modules/shelving/front/summary/index.js @@ -12,7 +12,7 @@ class Controller extends Summary { include: [ {relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/supplier/back/methods/supplier/getSummary.js b/modules/supplier/back/methods/supplier/getSummary.js index bf3fa56f5..bc869725c 100644 --- a/modules/supplier/back/methods/supplier/getSummary.js +++ b/modules/supplier/back/methods/supplier/getSummary.js @@ -91,7 +91,7 @@ module.exports = Self => { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js index c368ec1b8..5fc2ea752 100644 --- a/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js +++ b/modules/supplier/back/methods/supplier/specs/newSupplier.spec.js @@ -32,6 +32,7 @@ describe('Supplier newSupplier()', () => { const result = await models.Supplier.newSupplier(ctx, options); expect(result.name).toEqual('newSupplier'); + await tx.rollback(); } catch (e) { await tx.rollback(); throw e; diff --git a/modules/supplier/back/models/specs/supplier.spec.js b/modules/supplier/back/models/specs/supplier.spec.js index f317f1fb9..fbd3a00db 100644 --- a/modules/supplier/back/models/specs/supplier.spec.js +++ b/modules/supplier/back/models/specs/supplier.spec.js @@ -123,5 +123,21 @@ describe('loopback model Supplier', () => { throw e; } }); + + it('should update the account attribute when a new supplier is created', async() => { + const tx = await models.Supplier.beginTransaction({}); + const options = {transaction: tx}; + + try { + const newSupplier = await models.Supplier.create({name: 'Alfred Pennyworth'}, options); + const fetchedSupplier = await models.Supplier.findById(newSupplier.id, null, options); + + expect(Number(fetchedSupplier.account)).toEqual(4100000000 + newSupplier.id); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); }); diff --git a/modules/supplier/back/models/supplier.js b/modules/supplier/back/models/supplier.js index 96042c9a0..5cf357c13 100644 --- a/modules/supplier/back/models/supplier.js +++ b/modules/supplier/back/models/supplier.js @@ -117,6 +117,16 @@ module.exports = Self => { throw new UserError('You can not modify is pay method checked'); }); + Self.observe('after save', async function(ctx) { + if (ctx.instance && ctx.isNewInstance) { + const {id} = ctx.instance; + const {Supplier} = Self.app.models; + + const supplier = await Supplier.findById(id, null, ctx.options); + await supplier?.updateAttribute('account', Number(supplier.account) + id, ctx.options); + } + }); + Self.validateAsync('name', 'countryFk', hasSupplierSameName, { message: 'A supplier with the same name already exists. Change the country.' }); diff --git a/modules/supplier/front/address/create/index.html b/modules/supplier/front/address/create/index.html index 4d66b70f0..e45539445 100644 --- a/modules/supplier/front/address/create/index.html +++ b/modules/supplier/front/address/create/index.html @@ -42,7 +42,7 @@ show-field="code" rule> - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) @@ -50,12 +50,12 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> - - \ No newline at end of file + diff --git a/modules/supplier/front/address/edit/index.html b/modules/supplier/front/address/edit/index.html index dd4cbb4d2..b6f90134b 100644 --- a/modules/supplier/front/address/edit/index.html +++ b/modules/supplier/front/address/edit/index.html @@ -40,20 +40,20 @@ show-field="code" rule> - {{code}} - {{town.name}} ({{town.province.name}}, + {{code}} - {{town.name}} ({{town.province.name}}, {{town.province.country.country}}) - - - - \ No newline at end of file + diff --git a/modules/supplier/front/create/index.html b/modules/supplier/front/create/index.html index c3efcf6ae..eb6e7261e 100644 --- a/modules/supplier/front/create/index.html +++ b/modules/supplier/front/create/index.html @@ -18,7 +18,6 @@ diff --git a/modules/ticket/back/locale/sale-group/en.yml b/modules/ticket/back/locale/sale-group/en.yml new file mode 100644 index 000000000..d88231647 --- /dev/null +++ b/modules/ticket/back/locale/sale-group/en.yml @@ -0,0 +1,10 @@ +name: saleGroup +columns: + id: id + created: created + userFk: user + parkingFk: parking + sectorFk: sector + ticketFk: ticket + editorFk: editor + diff --git a/modules/ticket/back/locale/sale-group/es.yml b/modules/ticket/back/locale/sale-group/es.yml new file mode 100644 index 000000000..9efbe7148 --- /dev/null +++ b/modules/ticket/back/locale/sale-group/es.yml @@ -0,0 +1,10 @@ +name: saleGroup +columns: + id: id + created: creado + userFk: usuario + parkingFk: parking + sectorFk: sector + ticketFk: ticket + editorFk: editor + diff --git a/modules/ticket/back/methods/expedition-state/addExpeditionState.js b/modules/ticket/back/methods/expedition-state/addExpeditionState.js index f1199f188..8eab1a838 100644 --- a/modules/ticket/back/methods/expedition-state/addExpeditionState.js +++ b/modules/ticket/back/methods/expedition-state/addExpeditionState.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethod('addExpeditionState', { + Self.remoteMethodCtx('addExpeditionState', { description: 'Update an expedition state', accessType: 'WRITE', accepts: [ @@ -12,18 +12,15 @@ module.exports = Self => { description: 'Array of objects containing expeditionFk and stateCode' } ], - returns: { - type: 'boolean', - root: true - }, http: { path: `/addExpeditionState`, verb: 'post' } }); - Self.addExpeditionState = async(expeditions, options) => { + Self.addExpeditionState = async(ctx, expeditions, options) => { const models = Self.app.models; + const userId = ctx.req.accessToken.userId; let tx; const myOptions = {}; if (typeof options == 'object') @@ -51,6 +48,7 @@ module.exports = Self => { await models.ExpeditionState.create({ expeditionFk: expedition.expeditionFk, typeFk, + userFk: userId, }, myOptions); } diff --git a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js index 819a43a60..6c7739006 100644 --- a/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js +++ b/modules/ticket/back/methods/expedition-state/specs/addExpeditionState.spec.js @@ -1,9 +1,9 @@ const models = require('vn-loopback/server/server').models; describe('expeditionState addExpeditionState()', () => { + const ctx = {req: {accessToken: {userId: 9}}}; it('should update the expedition states', async() => { const tx = await models.ExpeditionState.beginTransaction({}); - try { const options = {transaction: tx}; const payload = [ @@ -13,7 +13,7 @@ describe('expeditionState addExpeditionState()', () => { }, ]; - await models.ExpeditionState.addExpeditionState(payload, options); + await models.ExpeditionState.addExpeditionState(ctx, payload, options); const expeditionState = await models.ExpeditionState.findOne({ where: {id: 5} @@ -39,7 +39,7 @@ describe('expeditionState addExpeditionState()', () => { stateCode: 'DUMMY' } ]; - await models.ExpeditionState.addExpeditionState(payload, options); + await models.ExpeditionState.addExpeditionState(ctx, payload, options); await tx.rollback(); } catch (e) { @@ -62,7 +62,7 @@ describe('expeditionState addExpeditionState()', () => { } ]; - await models.ExpeditionState.addExpeditionState(payload, options); + await models.ExpeditionState.addExpeditionState(ctx, payload, options); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js index 98743d8cc..fbc855501 100644 --- a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js +++ b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js @@ -41,7 +41,7 @@ module.exports = Self => { FROM saleTracking st JOIN sale s ON s.id = st.saleFk JOIN worker w ON w.id = st.workerFk - JOIN account.user u ON u.id = w.userFk + JOIN account.user u ON u.id = w.id JOIN state ste ON ste.id = st.stateFk`); stmt.merge(Self.makeSuffix(filter)); diff --git a/modules/ticket/back/methods/sale/clone.js b/modules/ticket/back/methods/sale/clone.js new file mode 100644 index 000000000..a5ccb6de4 --- /dev/null +++ b/modules/ticket/back/methods/sale/clone.js @@ -0,0 +1,122 @@ +module.exports = Self => { + Self.clone = async(ctx, salesIds, servicesIds, withWarehouse, group, negative, options) => { + const models = Self.app.models; + const myOptions = {}; + let tx; + const newTickets = []; + + if (typeof options == 'object') + Object.assign(myOptions, options); + + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + + try { + const salesFilter = { + where: {id: {inq: salesIds}}, + include: { + relation: 'components', + scope: { + fields: ['saleFk', 'componentFk', 'value'] + } + } + }; + const sales = await models.Sale.find(salesFilter, myOptions); + let ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; + + const mappedTickets = new Map(); + + if (group) ticketsIds = [ticketsIds[0]]; + + for (let ticketId of ticketsIds) { + const newTicket = await createTicket( + ctx, + ticketId, + withWarehouse, + negative, + myOptions + ); + newTickets.push(newTicket); + mappedTickets.set(ticketId, newTicket.id); + } + + for (const sale of sales) { + const newTicketId = mappedTickets.get(sale.ticketFk); + + const createdSale = await models.Sale.create({ + ticketFk: newTicketId, + itemFk: sale.itemFk, + quantity: negative ? - sale.quantity : sale.quantity, + concept: sale.concept, + price: sale.price, + discount: sale.discount, + }, myOptions); + + const components = sale.components(); + for (const component of components) + component.saleFk = createdSale.id; + + await models.SaleComponent.create(components, myOptions); + } + + if (servicesIds && servicesIds.length) { + const servicesFilter = { + where: {id: {inq: servicesIds}} + }; + const services = await models.TicketService.find(servicesFilter, myOptions); + + for (const service of services) { + const newTicketId = mappedTickets.get(service.ticketFk); + + await models.TicketService.create({ + description: service.description, + quantity: negative ? - service.quantity : service.quantity, + price: service.price, + taxClassFk: service.taxClassFk, + ticketFk: newTicketId, + ticketServiceTypeFk: service.ticketServiceTypeFk, + }, myOptions); + } + } + + if (tx) await tx.commit(); + + return newTickets; + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + + async function createTicket( + ctx, + ticketId, + withWarehouse, + negative, + myOptions + ) { + const models = Self.app.models; + const now = Date.vnNew(); + + const ticket = await models.Ticket.findById(ticketId, null, myOptions); + ctx.args.clientId = ticket.clientFk; + ctx.args.shipped = now; + ctx.args.landed = now; + ctx.args.warehouseId = withWarehouse ? ticket.warehouseFk : null; + ctx.args.companyId = ticket.companyFk; + ctx.args.addressId = ticket.addressFk; + + const newTicket = await models.Ticket.new(ctx, myOptions); + + if (negative) { + await models.TicketRefund.create({ + originalTicketFk: ticketId, + refundTicketFk: newTicket.id + }, myOptions); + } + + return newTicket; + } + }; +}; diff --git a/modules/ticket/back/methods/sale/deleteSales.js b/modules/ticket/back/methods/sale/deleteSales.js index 5d1463a66..0207815a9 100644 --- a/modules/ticket/back/methods/sale/deleteSales.js +++ b/modules/ticket/back/methods/sale/deleteSales.js @@ -1,5 +1,3 @@ -let UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('deleteSales', { description: 'Deletes the selected sales', @@ -70,11 +68,11 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Deleted sales from ticket', { ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + ticketUrl: `${url}ticket/${ticketId}/sale`, deletions: deletions }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/ticket/back/methods/sale/refund.js b/modules/ticket/back/methods/sale/refund.js index 3c41aab1e..17b70f12b 100644 --- a/modules/ticket/back/methods/sale/refund.js +++ b/modules/ticket/back/methods/sale/refund.js @@ -5,7 +5,8 @@ module.exports = Self => { accepts: [ { arg: 'salesIds', - type: ['number'] + type: ['number'], + required: true }, { arg: 'servicesIds', @@ -40,124 +41,23 @@ module.exports = Self => { myOptions.transaction = tx; } - let refundTicket = null; try { - const refundAgencyMode = await models.AgencyMode.findOne({ - include: { - relation: 'zones', - scope: { - limit: 1, - field: ['id', 'name'] - } - }, - where: {code: 'refund'} - }, myOptions); - - const refoundZoneId = refundAgencyMode.zones()[0].id; - - if (salesIds) { - const salesFilter = { - where: {id: {inq: salesIds}}, - include: { - relation: 'components', - scope: { - fields: ['saleFk', 'componentFk', 'value'] - } - } - }; - const sales = await models.Sale.find(salesFilter, myOptions); - const ticketsIds = [...new Set(sales.map(sale => sale.ticketFk))]; - - const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; - - // eslint-disable-next-line max-len - refundTicket = await createTicketRefund(firstTicketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions); - - for (const sale of sales) { - const createdSale = await models.Sale.create({ - ticketFk: refundTicket.id, - itemFk: sale.itemFk, - quantity: - sale.quantity, - concept: sale.concept, - price: sale.price, - discount: sale.discount, - }, myOptions); - - const components = sale.components(); - for (const component of components) - component.saleFk = createdSale.id; - - await models.SaleComponent.create(components, myOptions); - } - } - - if (!refundTicket) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - const ticketsIds = [...new Set(services.map(service => service.ticketFk))]; - - const now = Date.vnNew(); - const [firstTicketId] = ticketsIds; - - // eslint-disable-next-line max-len - refundTicket = await createTicketRefund(firstTicketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions); - } - - if (servicesIds && servicesIds.length > 0) { - const servicesFilter = { - where: {id: {inq: servicesIds}} - }; - const services = await models.TicketService.find(servicesFilter, myOptions); - for (const service of services) { - await models.TicketService.create({ - description: service.description, - quantity: service.quantity, - price: - service.price, - taxClassFk: service.taxClassFk, - ticketFk: refundTicket.id, - ticketServiceTypeFk: service.ticketServiceTypeFk, - }, myOptions); - } - } - - const query = `CALL vn.ticket_recalc(?, NULL)`; - await Self.rawSql(query, [refundTicket.id], myOptions); + const refundsTicket = await models.Sale.clone( + ctx, + salesIds, + servicesIds, + withWarehouse, + false, + true, + myOptions + ); if (tx) await tx.commit(); - return refundTicket; + return refundsTicket[0]; } catch (e) { if (tx) await tx.rollback(); throw e; } }; - - async function createTicketRefund(ticketId, now, refundAgencyMode, refoundZoneId, withWarehouse, myOptions) { - const models = Self.app.models; - - const filter = {include: {relation: 'address'}}; - const ticket = await models.Ticket.findById(ticketId, filter, myOptions); - - const refundTicket = await models.Ticket.create({ - clientFk: ticket.clientFk, - shipped: now, - addressFk: ticket.address().id, - agencyModeFk: refundAgencyMode.id, - nickname: ticket.address().nickname, - warehouseFk: withWarehouse ? ticket.warehouseFk : null, - companyFk: ticket.companyFk, - landed: now, - zoneFk: refoundZoneId - }, myOptions); - - await models.TicketRefund.create({ - refundTicketFk: refundTicket.id, - originalTicketFk: ticket.id, - }, myOptions); - - return refundTicket; - } }; diff --git a/modules/ticket/back/methods/sale/reserve.js b/modules/ticket/back/methods/sale/reserve.js index 2dc368af6..36db791fc 100644 --- a/modules/ticket/back/methods/sale/reserve.js +++ b/modules/ticket/back/methods/sale/reserve.js @@ -1,6 +1,3 @@ - -let UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('reserve', { description: 'Change the state of a ticket', @@ -65,7 +62,8 @@ module.exports = Self => { promises.push(reservedSale); - changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) ${$t('State')}: ${$t(oldState)} ➔ *${$t(newState)}*`; + changesMade += `\r\n-${sale.itemFk}: ${sale.concept} (${sale.quantity}) + ${$t('State')}: ${$t(oldState)} ➔ *${$t(newState)}*`; } } @@ -87,11 +85,11 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale reserved state', { ticketId: ticketId, - ticketUrl: `${origin}/#!/ticket/${ticketId}/sale`, + ticketUrl: `${url}ticket/${ticketId}/sale`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/ticket/back/methods/sale/specs/refund.spec.js b/modules/ticket/back/methods/sale/specs/refund.spec.js index b81f7f84d..08eb1fabd 100644 --- a/modules/ticket/back/methods/sale/specs/refund.spec.js +++ b/modules/ticket/back/methods/sale/specs/refund.spec.js @@ -3,7 +3,7 @@ const LoopBackContext = require('loopback-context'); describe('Sale refund()', () => { const userId = 5; - const ctx = {req: {accessToken: userId}}; + const ctx = {req: {accessToken: userId}, args: {}}; const activeCtx = { accessToken: {userId}, }; @@ -40,6 +40,7 @@ describe('Sale refund()', () => { try { const options = {transaction: tx}; + const ticketsBefore = await models.Ticket.find({}, options); const ticket = await models.Sale.refund(ctx, salesIds, servicesIds, withWarehouse, options); @@ -61,12 +62,13 @@ describe('Sale refund()', () => { } ] }, options); - + const ticketsAfter = await models.Ticket.find({}, options); const salesLength = refundedTicket.ticketSales().length; const componentsLength = refundedTicket.ticketSales()[0].components().length; expect(refundedTicket).toBeDefined(); - expect(salesLength).toEqual(2); + expect(salesLength).toEqual(1); + expect(ticketsBefore.length).toEqual(ticketsAfter.length - 2); expect(componentsLength).toEqual(4); await tx.rollback(); diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 133be8de3..9d1403df0 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -108,7 +108,7 @@ describe('sale updatePrice()', () => { }}, options); expect(updatedSale.price).toBe(price); - expect(createdSaleComponent.value).toEqual(-2.04); + expect(createdSaleComponent.value).toEqual(-2.34); const updatedSalesPersonMana = await models.WorkerMana.findById(18, null, options); diff --git a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js b/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js deleted file mode 100644 index 8064ea30b..000000000 --- a/modules/ticket/back/methods/sale/specs/updateQuantity.spec.js +++ /dev/null @@ -1,162 +0,0 @@ -const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - -describe('sale updateQuantity()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - - const ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - - it('should throw an error if the quantity is greater than it should be', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - const tx = await models.Sale.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, 17, 99, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).toEqual(new Error('The new quantity should be smaller than the old one')); - }); - - it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { - const tx = await models.Sale.beginTransaction({}); - const saleId = 17; - const buyerId = 35; - const ctx = { - req: { - accessToken: {userId: buyerId}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - - try { - const options = {transaction: tx}; - - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - - expect(isRoleAdvanced).toEqual(true); - - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(originalLine.quantity).toEqual(30); - - const newQuantity = originalLine.quantity + 1; - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should update the quantity of a given sale current line', async() => { - const tx = await models.Sale.beginTransaction({}); - const saleId = 25; - const newQuantity = 4; - - try { - const options = {transaction: tx}; - - const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(originalLine.quantity).toEqual(20); - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); - - it('should throw an error if the quantity is negative and it is not a refund ticket', async() => { - const ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'localhost:5000'}, - __: () => {} - } - }; - const saleId = 17; - const newQuantity = -10; - - const tx = await models.Sale.beginTransaction({}); - - let error; - try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error).toEqual(new Error('You can only add negative amounts in refund tickets')); - }); - - it('should update a negative quantity when is a ticket refund', async() => { - const tx = await models.Sale.beginTransaction({}); - const saleId = 13; - const newQuantity = -10; - - try { - const options = {transaction: tx}; - - await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); - - const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); - - expect(modifiedLine.quantity).toEqual(newQuantity); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } - }); -}); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 62e4ebd42..191fd09e3 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -1,5 +1,3 @@ -let UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('updatePrice', { description: 'Changes the price of a sale', @@ -100,7 +98,7 @@ module.exports = Self => { const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale price', { ticketId: sale.ticket().id, itemId: sale.itemFk, @@ -108,8 +106,8 @@ module.exports = Self => { quantity: sale.quantity, oldPrice: oldPrice, newPrice: newPrice, - ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, - itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, + itemUrl: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); } diff --git a/modules/ticket/back/methods/sale/updateQuantity.js b/modules/ticket/back/methods/sale/updateQuantity.js index edbc34e42..1a497da24 100644 --- a/modules/ticket/back/methods/sale/updateQuantity.js +++ b/modules/ticket/back/methods/sale/updateQuantity.js @@ -1,4 +1,3 @@ -let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('updateQuantity', { @@ -64,32 +63,22 @@ module.exports = Self => { const sale = await models.Sale.findById(id, filter, myOptions); - const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); - if (newQuantity > sale.quantity && !isRoleAdvanced) - throw new UserError('The new quantity should be smaller than the old one'); - - const ticketRefund = await models.TicketRefund.findOne({ - where: {refundTicketFk: sale.ticketFk}, - fields: ['id']} - , myOptions); - if (newQuantity < 0 && !ticketRefund) - throw new UserError('You can only add negative amounts in refund tickets'); - const oldQuantity = sale.quantity; const result = await sale.updateAttributes({quantity: newQuantity}, myOptions); const salesPerson = sale.ticket().client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale quantity', { ticketId: sale.ticket().id, itemId: sale.itemFk, concept: sale.concept, oldQuantity: oldQuantity, newQuantity: newQuantity, - ticketUrl: `${origin}/#!/ticket/${sale.ticket().id}/sale`, - itemUrl: `${origin}/#!/item/${sale.itemFk}/summary` + ticketUrl: `${url}ticket/${sale.ticket().id}/sale`, + itemUrl: `${url}item/${sale.itemFk}/summary` }); + await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); } diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index 9cd7f4d68..00310f33c 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -84,7 +84,7 @@ module.exports = Self => { const query = `CALL vn.sale_calculateComponent(?, NULL)`; await Self.rawSql(query, [sale.id], myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const requesterId = request.requesterFk; const message = $t('Bought units from buy request', { @@ -92,8 +92,8 @@ module.exports = Self => { concept: sale.concept, itemId: sale.itemFk, ticketId: sale.ticketFk, - url: `${origin}/#!/ticket/${sale.ticketFk}/summary`, - urlItem: `${origin}/#!/item/${sale.itemFk}/summary` + url: `${url}ticket/${sale.ticketFk}/summary`, + urlItem: `${url}item/${sale.itemFk}/summary` }); await models.Chat.sendCheckingPresence(ctx, requesterId, message, myOptions); diff --git a/modules/ticket/back/methods/ticket-request/deny.js b/modules/ticket/back/methods/ticket-request/deny.js index 35de765d7..44f1e48a1 100644 --- a/modules/ticket/back/methods/ticket-request/deny.js +++ b/modules/ticket/back/methods/ticket-request/deny.js @@ -39,7 +39,7 @@ module.exports = Self => { try { const userId = ctx.req.accessToken.userId; - const worker = await Self.app.models.Worker.findOne({where: {userFk: userId}}, myOptions); + const worker = await Self.app.models.Worker.findOne({where: {id: userId}}, myOptions); const params = { isOk: false, @@ -50,12 +50,12 @@ module.exports = Self => { const request = await Self.app.models.TicketRequest.findById(ctx.args.id, null, myOptions); await request.updateAttributes(params, myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const requesterId = request.requesterFk; const message = $t('Deny buy request', { ticketId: request.ticketFk, - url: `${origin}/#!/ticket/${request.ticketFk}/request/index`, + url: `${url}ticket/${request.ticketFk}/request/index`, observation: params.response }); diff --git a/modules/ticket/back/methods/ticket-request/filter.js b/modules/ticket/back/methods/ticket-request/filter.js index 921598b57..10aaf02e5 100644 --- a/modules/ticket/back/methods/ticket-request/filter.js +++ b/modules/ticket/back/methods/ticket-request/filter.js @@ -99,6 +99,8 @@ module.exports = Self => { switch (value) { case 'pending': return {'tr.isOk': null}; + case 'accepted': + return {'tr.isOk': 1}; default: return {'tr.isOk': value}; } @@ -122,8 +124,7 @@ module.exports = Self => { filter = mergeFilters(filter, {where}); const stmt = new ParameterizedSQL( - `SELECT - tr.id, + `SELECT tr.id, tr.ticketFk, tr.quantity, tr.price, @@ -133,18 +134,19 @@ module.exports = Self => { tr.saleFk, tr.requesterFk, tr.isOk, - s.quantity AS saleQuantity, + s.quantity saleQuantity, s.itemFk, - i.name AS itemDescription, + i.name itemDescription, t.shipped, - DATE(t.shipped) AS shippedDate, + DATE(t.shipped) shippedDate, t.nickname, t.warehouseFk, t.clientFk, - w.name AS warehouse, - u.nickname AS salesPersonNickname, - ua.name AS attenderName, - c.salesPersonFk + w.name warehouse, + u.nickname salesPersonNickname, + ua.name attenderName, + c.salesPersonFk, + ua2.name requesterName FROM ticketRequest tr LEFT JOIN ticketWeekly tw on tw.ticketFk = tr.ticketFk LEFT JOIN ticket t ON t.id = tr.ticketFk @@ -153,9 +155,10 @@ module.exports = Self => { LEFT JOIN item i ON i.id = tr.itemFk LEFT JOIN sale s ON s.id = tr.saleFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN worker wka ON wka.id = tr.attenderFk - LEFT JOIN account.user ua ON ua.id = wka.userFk`); + LEFT JOIN account.user ua ON ua.id = wka.id + LEFT JOIN account.user ua2 ON ua2.id = tr.requesterFk`); stmt.merge(conn.makeSuffix(filter)); return conn.executeStmt(stmt, myOptions); diff --git a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js index ae004a024..9ab89f009 100644 --- a/modules/ticket/back/methods/ticket-request/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/filter.spec.js @@ -14,7 +14,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); - expect(result.length).toEqual(3); + expect(result.length).toEqual(5); await tx.rollback(); } catch (e) { @@ -93,7 +93,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { @@ -113,7 +113,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { @@ -153,7 +153,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, {order: 'id'}, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { @@ -173,7 +173,7 @@ describe('ticket-request filter()', () => { const result = await models.TicketRequest.filter(ctx, options); const requestId = result[0].id; - expect(requestId).toEqual(3); + expect(requestId).toEqual(1); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket-tracking/setDelivered.js b/modules/ticket/back/methods/ticket-tracking/setDelivered.js index bd6e32dcf..d3cdb192f 100644 --- a/modules/ticket/back/methods/ticket-tracking/setDelivered.js +++ b/modules/ticket/back/methods/ticket-tracking/setDelivered.js @@ -43,11 +43,11 @@ module.exports = Self => { fields: ['id', 'name', 'alertLevel', 'code'] }, myOptions); - const worker = await models.Worker.findOne({where: {userFk: userId}}, myOptions); + const worker = await models.Worker.findOne({where: {id: userId}}, myOptions); const promises = []; for (const id of ticketIds) { - const promise = models.TicketTracking.changeState(ctx, { + const promise = await models.Ticket.state(ctx, { stateFk: state.id, workerFk: worker.id, ticketFk: id diff --git a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js index 2587b6657..453b7924f 100644 --- a/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket-weekly/specs/filter.spec.js @@ -16,8 +16,8 @@ describe('ticket-weekly filter()', () => { const firstRow = result[0]; - expect(firstRow.ticketFk).toEqual(1); - expect(result.length).toEqual(6); + expect(firstRow.ticketFk).toEqual(2); + expect(result.length).toEqual(4); await tx.rollback(); } catch (e) { @@ -52,12 +52,12 @@ describe('ticket-weekly filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 'bruce'}}; + const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 'max'}}; const result = await models.TicketWeekly.filter(ctx, null, options); const firstRow = result[0]; - expect(firstRow.clientName).toEqual('Bruce Wayne'); + expect(firstRow.clientName).toEqual('Max Eisenhardt'); await tx.rollback(); } catch (e) { @@ -72,13 +72,13 @@ describe('ticket-weekly filter()', () => { try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 1101}}; + const ctx = {req: {accessToken: {userId: authUserId}}, args: {search: 1105}}; const result = await models.TicketWeekly.filter(ctx, null, options); const firstRow = result[0]; - expect(firstRow.clientFk).toEqual(1101); - expect(firstRow.clientName).toEqual('Bruce Wayne'); + expect(firstRow.clientFk).toEqual(1105); + expect(firstRow.clientName).toEqual('Max Eisenhardt'); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/addSale.js b/modules/ticket/back/methods/ticket/addSale.js index cbf884273..826de6e12 100644 --- a/modules/ticket/back/methods/ticket/addSale.js +++ b/modules/ticket/back/methods/ticket/addSale.js @@ -1,5 +1,3 @@ -const UserError = require('vn-loopback/util/user-error'); - module.exports = Self => { Self.remoteMethodCtx('addSale', { description: 'Inserts a new sale for the current ticket', @@ -63,17 +61,6 @@ module.exports = Self => { } }, myOptions); - const itemInfo = await models.Item.getVisibleAvailable( - itemId, - ticket.warehouseFk, - ticket.shipped, - myOptions - ); - - const isPackaging = item.family == 'EMB'; - if (!isPackaging && itemInfo.available < quantity) - throw new UserError(`This item is not available`); - const newSale = await models.Sale.create({ ticketFk: id, itemFk: item.id, @@ -94,11 +81,11 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t('Added sale to ticket', { ticketId: id, - ticketUrl: `${origin}/#!/ticket/${id}/sale`, + ticketUrl: `${url}ticket/${id}/sale`, addition: addition }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message); diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 8aad8959b..f7c36f108 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -237,7 +237,7 @@ module.exports = Self => { const salesPersonId = originalTicket.client().salesPersonFk; if (salesPersonId) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); let changesMade = ''; for (let change in newProperties) { @@ -249,7 +249,7 @@ module.exports = Self => { const message = $t('Changed this data from the ticket', { ticketId: args.id, - ticketUrl: `${origin}/#!/ticket/${args.id}/sale`, + ticketUrl: `${url}ticket/${args.id}/sale`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); diff --git a/modules/ticket/back/methods/ticket/filter.js b/modules/ticket/back/methods/ticket/filter.js index eb3da39af..899fe05cd 100644 --- a/modules/ticket/back/methods/ticket/filter.js +++ b/modules/ticket/back/methods/ticket/filter.js @@ -272,7 +272,7 @@ module.exports = Self => { LEFT JOIN state st ON st.id = ts.stateFk LEFT JOIN client c ON c.id = t.clientFk LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN account.user u ON u.id = wk.id LEFT JOIN route r ON r.id = t.routeFk`); if (args.orderFk) { diff --git a/modules/ticket/back/methods/ticket/getTicketsAdvance.js b/modules/ticket/back/methods/ticket/getTicketsAdvance.js index ec9314db2..ab40b9559 100644 --- a/modules/ticket/back/methods/ticket/getTicketsAdvance.js +++ b/modules/ticket/back/methods/ticket/getTicketsAdvance.js @@ -28,32 +28,27 @@ module.exports = Self => { { arg: 'ipt', type: 'string', - description: 'Origin Item Packaging Type', - required: false + description: 'Origin Item Packaging Type' }, { arg: 'futureIpt', type: 'string', - description: 'Destination Item Packaging Type', - required: false + description: 'Destination Item Packaging Type' }, { arg: 'id', type: 'number', - description: 'Origin id', - required: false + description: 'Origin id' }, { arg: 'futureId', type: 'number', - description: 'Destination id', - required: false + description: 'Destination id' }, { arg: 'isFullMovable', type: 'boolean', - description: 'True when lines and stock of origin are equal', - required: false + description: 'True when lines and stock of origin are equal' }, { arg: 'filter', diff --git a/modules/ticket/back/methods/ticket/invoiceTickets.js b/modules/ticket/back/methods/ticket/invoiceTickets.js index ca1bf15fb..fa3ee93af 100644 --- a/modules/ticket/back/methods/ticket/invoiceTickets.js +++ b/modules/ticket/back/methods/ticket/invoiceTickets.js @@ -77,9 +77,10 @@ module.exports = function(Self) { if (tx) await tx.rollback(); throw e; } - - for (const invoiceId of invoicesIds) - await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + if (tx) { + for (const invoiceId of invoicesIds) + await models.InvoiceOut.makePdfAndNotify(ctx, invoiceId, null); + } return invoicesIds; }; diff --git a/modules/ticket/back/methods/ticket/isEditableOrThrow.js b/modules/ticket/back/methods/ticket/isEditableOrThrow.js index 6a8bafa2c..f8285cecd 100644 --- a/modules/ticket/back/methods/ticket/isEditableOrThrow.js +++ b/modules/ticket/back/methods/ticket/isEditableOrThrow.js @@ -40,7 +40,7 @@ module.exports = Self => { if (!isEditable && !isRoleAdvanced) throw new ForbiddenError(`This ticket is not editable.`); - if (isLocked) + if (isLocked && !isWeekly) throw new ForbiddenError(`This ticket is locked.`); if (isWeekly && !canEditWeeklyTicket) diff --git a/modules/ticket/back/methods/ticket/merge.js b/modules/ticket/back/methods/ticket/merge.js index 3c0da077f..1106cef06 100644 --- a/modules/ticket/back/methods/ticket/merge.js +++ b/modules/ticket/back/methods/ticket/merge.js @@ -25,7 +25,7 @@ module.exports = Self => { Self.merge = async(ctx, tickets, options) => { const httpRequest = ctx.req; const $t = httpRequest.__; - const origin = httpRequest.headers.origin; + const url = await Self.app.models.Url.getUrl(); const models = Self.app.models; const myOptions = {}; let tx; @@ -40,8 +40,8 @@ module.exports = Self => { try { for (let ticket of tickets) { - const originFullPath = `${origin}/#!/ticket/${ticket.originId}/summary`; - const destinationFullPath = `${origin}/#!/ticket/${ticket.destinationId}/summary`; + const originFullPath = `${url}ticket/${ticket.originId}/summary`; + const destinationFullPath = `${url}ticket/${ticket.destinationId}/summary`; const message = $t('Ticket merged', { originDated: dateUtil.toString(new Date(ticket.originShipped)), destinationDated: dateUtil.toString(new Date(ticket.destinationShipped)), diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index b461fb26d..288d38d77 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -48,7 +48,7 @@ module.exports = Self => { description: `The route id filter` }], returns: { - type: 'number', + type: 'object', root: true }, http: { @@ -96,7 +96,7 @@ module.exports = Self => { if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { const canCreateTicket = await models.Client.canCreateTicket(args.clientId, myOptions); if (!canCreateTicket) - throw new UserError(`You can't create a ticket for a inactive client`); + throw new UserError(`You can't create a ticket for an inactive client`); } if (!args.shipped && args.landed) { diff --git a/modules/ticket/back/methods/ticket/refund.js b/modules/ticket/back/methods/ticket/refund.js index c99b6aa83..758384ae2 100644 --- a/modules/ticket/back/methods/ticket/refund.js +++ b/modules/ticket/back/methods/ticket/refund.js @@ -39,7 +39,6 @@ module.exports = Self => { try { const filter = {where: {ticketFk: {inq: ticketsIds}}}; - const sales = await models.Sale.find(filter, myOptions); const salesIds = sales.map(sale => sale.id); diff --git a/modules/ticket/back/methods/ticket/restore.js b/modules/ticket/back/methods/ticket/restore.js index 722c3294e..e268c3891 100644 --- a/modules/ticket/back/methods/ticket/restore.js +++ b/modules/ticket/back/methods/ticket/restore.js @@ -48,10 +48,10 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonId = ticket.client().salesPersonFk; if (salesPersonId) { - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const message = $t(`I have restored the ticket id`, { id: id, - url: `${origin}/#!/ticket/${id}/summary` + url: `${url}ticket/${id}/summary` }); await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); } diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 2f8c402da..9a9fd9056 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -118,11 +118,11 @@ module.exports = Self => { // Send notification to salesPerson const salesPersonUser = ticket.client().salesPersonUser(); - if (salesPersonUser) { - const origin = ctx.req.headers.origin; + if (salesPersonUser && sales.length) { + const url = await Self.app.models.Url.getUrl(); const message = $t(`I have deleted the ticket id`, { id: id, - url: `${origin}/#!/ticket/${id}/summary` + url: `${url}ticket/${id}/summary` }); await models.Chat.send(ctx, `@${salesPersonUser.name}`, message); } @@ -146,7 +146,8 @@ module.exports = Self => { JOIN vn.sectorCollection sc ON sc.id = scsg.sectorCollectionFk JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = sg.id JOIN vn.sale s ON s.id = sgd.saleFk - WHERE s.ticketFk = ?;`, [ticket.id], myOptions); + WHERE s.ticketFk = ?;`, [ticket.id], myOptions + ); if (tx) await tx.commit(); diff --git a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js index 301745ed3..9dd1f8544 100644 --- a/modules/ticket/back/methods/ticket/specs/isEditable.spec.js +++ b/modules/ticket/back/methods/ticket/specs/isEditable.spec.js @@ -8,7 +8,7 @@ describe('isEditable()', () => { try { const options = {transaction: tx}; const ctx = {req: {accessToken: {userId: 35}}}; - result = await models.Ticket.isEditable(ctx, 5, options); + result = await models.Ticket.isEditable(ctx, 19, options); await tx.rollback(); } catch (error) { await tx.rollback(); diff --git a/modules/ticket/back/methods/ticket/specs/merge.spec.js b/modules/ticket/back/methods/ticket/specs/merge.spec.js index 3be6b8bac..646b9739f 100644 --- a/modules/ticket/back/methods/ticket/specs/merge.spec.js +++ b/modules/ticket/back/methods/ticket/specs/merge.spec.js @@ -49,7 +49,7 @@ describe('ticket merge()', () => { expect(deletedTicket.isDeleted).toEqual(true); expect(salesTicketFuture.length).toEqual(2); - expect(chatNotificationBeforeMerge.length).toEqual(chatNotificationAfterMerge.length - 2); + expect(chatNotificationBeforeMerge.length).toEqual(chatNotificationAfterMerge.length - 1); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js index 0a2f93bc4..9aa073a7b 100644 --- a/modules/ticket/back/methods/ticket/specs/new.spec.js +++ b/modules/ticket/back/methods/ticket/specs/new.spec.js @@ -30,7 +30,7 @@ describe('ticket new()', () => { await tx.rollback(); } - expect(error).toEqual(new UserError(`You can't create a ticket for a inactive client`)); + expect(error).toEqual(new UserError(`You can't create a ticket for an inactive client`)); }); it('should throw an error if the address doesnt exist', async() => { diff --git a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js b/modules/ticket/back/methods/ticket/specs/state.spec.js similarity index 87% rename from modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js rename to modules/ticket/back/methods/ticket/specs/state.spec.js index 175bc4e4b..9b5e80165 100644 --- a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js +++ b/modules/ticket/back/methods/ticket/specs/state.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); -describe('ticket changeState()', () => { +describe('ticket state()', () => { const salesPersonId = 18; const employeeId = 1; const productionId = 49; @@ -47,7 +47,7 @@ describe('ticket changeState()', () => { activeCtx.accessToken.userId = salesPersonId; const params = {ticketFk: 2, stateFk: 3}; - await models.TicketTracking.changeState(ctx, params, options); + await models.Ticket.state(ctx, params, options); await tx.rollback(); } catch (e) { @@ -69,7 +69,7 @@ describe('ticket changeState()', () => { activeCtx.accessToken.userId = employeeId; const params = {ticketFk: 11, stateFk: 13}; - await models.TicketTracking.changeState(ctx, params, options); + await models.Ticket.state(ctx, params, options); await tx.rollback(); } catch (e) { @@ -80,7 +80,8 @@ describe('ticket changeState()', () => { expect(error.code).toBe('ACCESS_DENIED'); }); - it('should be able to create a ticket tracking line for a not editable ticket if the user has the production role', async() => { + it('should be able to create a ticket tracking line for a not' + + ' editable ticket if the user has the production role', async() => { const tx = await models.TicketTracking.beginTransaction({}); try { @@ -91,7 +92,7 @@ describe('ticket changeState()', () => { activeCtx.accessToken.userId = productionId; const params = {ticketFk: ticket.id, stateFk: 3}; - const ticketTracking = await models.TicketTracking.changeState(ctx, params, options); + const ticketTracking = await models.Ticket.state(ctx, params, options); expect(ticketTracking.__data.ticketFk).toBe(params.ticketFk); expect(ticketTracking.__data.stateFk).toBe(params.stateFk); @@ -105,7 +106,8 @@ describe('ticket changeState()', () => { } }); - it('should update the ticket tracking line when the user is salesperson, uses the state assigned and a valid worker id', async() => { + it('should update the ticket tracking line when the user is salesperson,' + + ' uses the state assigned and a valid worker id', async() => { const tx = await models.TicketTracking.beginTransaction({}); try { @@ -115,7 +117,7 @@ describe('ticket changeState()', () => { const ctx = {req: {accessToken: {userId: 18}}}; const assignedState = await models.State.findOne({where: {code: 'PICKER_DESIGNED'}}, options); const params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; - const res = await models.TicketTracking.changeState(ctx, params, options); + const res = await models.Ticket.state(ctx, params, options); expect(res.__data.ticketFk).toBe(params.ticketFk); expect(res.__data.stateFk).toBe(params.stateFk); diff --git a/modules/ticket/back/methods/ticket-tracking/changeState.js b/modules/ticket/back/methods/ticket/state.js similarity index 93% rename from modules/ticket/back/methods/ticket-tracking/changeState.js rename to modules/ticket/back/methods/ticket/state.js index 4ae9ab40c..01bfbba20 100644 --- a/modules/ticket/back/methods/ticket-tracking/changeState.js +++ b/modules/ticket/back/methods/ticket/state.js @@ -1,7 +1,7 @@ const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { - Self.remoteMethodCtx('changeState', { + Self.remoteMethodCtx('state', { description: 'Change the state of a ticket', accessType: 'WRITE', accepts: [ @@ -18,12 +18,12 @@ module.exports = Self => { root: true }, http: { - path: `/changeState`, + path: `/state`, verb: 'POST' } }); - Self.changeState = async(ctx, params, options) => { + Self.state = async(ctx, params, options) => { const models = Self.app.models; const myOptions = {}; let tx; @@ -53,7 +53,7 @@ module.exports = Self => { if (!params.workerFk) { const worker = await models.Worker.findOne({ - where: {userFk: userId} + where: {id: userId} }, myOptions); params.workerFk = worker.id; diff --git a/modules/ticket/back/methods/ticket/transferSales.js b/modules/ticket/back/methods/ticket/transferSales.js index 1124f7ec7..54306510c 100644 --- a/modules/ticket/back/methods/ticket/transferSales.js +++ b/modules/ticket/back/methods/ticket/transferSales.js @@ -66,7 +66,7 @@ module.exports = Self => { const ticket = await models.Ticket.findById(id); const canCreateTicket = await models.Client.canCreateTicket(ticket.clientFk); if (!canCreateTicket) - throw new UserError(`You can't create a ticket for a inactive client`); + throw new UserError(`You can't create a ticket for an inactive client`); ticketId = await cloneTicket(originalTicket, myOptions); } @@ -138,14 +138,15 @@ module.exports = Self => { // Update original sale const rest = originalSale.quantity - sale.quantity; query = `UPDATE sale - SET quantity = ? + SET quantity = ?, + originalQuantity = ? WHERE id = ?`; - await Self.rawSql(query, [rest, sale.id], options); + await Self.rawSql(query, [rest, rest, sale.id], options); // Clone sale with new quantity - query = `INSERT INTO sale (itemFk, ticketFk, concept, quantity, originalQuantity, price, discount, priceFixed, + query = `INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, discount, priceFixed, reserved, isPicked, isPriceFixed, isAdded) - SELECT itemFk, ?, concept, ?, originalQuantity, price, discount, priceFixed, + SELECT itemFk, ?, concept, ?, price, discount, priceFixed, reserved, isPicked, isPriceFixed, isAdded FROM sale WHERE id = ?`; diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index e092ee4ed..2e8bec27a 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -165,11 +165,10 @@ module.exports = Self => { const salesPerson = ticket.client().salesPersonUser(); if (salesPerson) { - const origin = ctx.req.headers.origin; - + const url = await Self.app.models.Url.getUrl(); const message = $t('Changed sale discount', { ticketId: id, - ticketUrl: `${origin}/#!/ticket/${id}/sale`, + ticketUrl: `${url}ticket/${id}/sale`, changes: changesMade }); await models.Chat.sendCheckingPresence(ctx, salesPerson.id, message, myOptions); diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 83d7303b7..76a289cc3 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -17,6 +17,12 @@ "Expedition": { "dataSource": "vn" }, + "ExpeditionPallet": { + "dataSource": "vn" + }, + "ExpeditionScan": { + "dataSource": "vn" + }, "ExpeditionState": { "dataSource": "vn" }, @@ -32,6 +38,9 @@ "ExpeditionMistake": { "dataSource": "vn" }, + "ExpeditionMistakeType": { + "dataSource": "vn" + }, "PrintServerQueue": { "dataSource": "vn" }, @@ -47,6 +56,9 @@ "SaleGroup": { "dataSource": "vn" }, + "SaleMistake": { + "dataSource": "vn" + }, "SaleGroupDetail": { "dataSource": "vn" }, diff --git a/modules/ticket/back/models/expeditionMistake.json b/modules/ticket/back/models/expeditionMistake.json index 43033194a..aeed2aa3a 100644 --- a/modules/ticket/back/models/expeditionMistake.json +++ b/modules/ticket/back/models/expeditionMistake.json @@ -24,7 +24,7 @@ }, "type": { "type": "belongsTo", - "model": "MistakeType", + "model": "ExpeditionMistakeType", "foreignKey": "typeFk" } } diff --git a/modules/ticket/back/models/expeditionMistakeType.json b/modules/ticket/back/models/expeditionMistakeType.json new file mode 100644 index 000000000..c7eaa3cac --- /dev/null +++ b/modules/ticket/back/models/expeditionMistakeType.json @@ -0,0 +1,19 @@ +{ + "name": "ExpeditionMistakeType", + "base": "VnModel", + "options": { + "mysql": { + "table": "expeditionMistakeType" + } + }, + "properties": { + "code": { + "id":true, + "type": "string" + }, + "description": { + "type": "string" + } + } + } + \ No newline at end of file diff --git a/modules/ticket/back/models/expeditionPallet.json b/modules/ticket/back/models/expeditionPallet.json new file mode 100644 index 000000000..c5a38df75 --- /dev/null +++ b/modules/ticket/back/models/expeditionPallet.json @@ -0,0 +1,22 @@ +{ + "name": "ExpeditionPallet", + "options": { + "mysql": { + "table": "expeditionPallet" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + } + }, + "acls": [{ + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "production", + "permission": "ALLOW" + }] +} + diff --git a/modules/ticket/back/models/expeditionScan.json b/modules/ticket/back/models/expeditionScan.json new file mode 100644 index 000000000..7b95eff1e --- /dev/null +++ b/modules/ticket/back/models/expeditionScan.json @@ -0,0 +1,46 @@ +{ + "name": "ExpeditionScan", + "options": { + "mysql": { + "table": "expeditionScan" + } + }, + "properties": { + "id": { + "type": "number", + "description": "Identifier", + "id": true + }, + "expeditionFk": { + "type": "number", + "description": "Identifier" + }, + "palletFk": { + "type": "number", + "description": "Identifier" + }, + "scanned": { + "type": "date", + "default": "$now" + } + }, + "relations": { + "expedition": { + "type": "belongsTo", + "model": "Expedition", + "foreignKey": "expeditionFk" + }, + "pallet": { + "type": "belongsTo", + "model": "expeditionPallet", + "foreignKey": "palletFk" + } + }, + "acls": [{ + "accessType": "WRITE", + "principalType": "ROLE", + "principalId": "production", + "permission": "ALLOW" + }] +} + diff --git a/modules/ticket/back/models/sale-mistake.json b/modules/ticket/back/models/sale-mistake.json new file mode 100644 index 000000000..b1cd989e0 --- /dev/null +++ b/modules/ticket/back/models/sale-mistake.json @@ -0,0 +1,49 @@ +{ + "name": "SaleMistake", + "base": "VnModel", + "options": { + "mysql": { + "table": "saleMistake" + } + }, + "properties": { + "id": { + "id": true, + "type": "number", + "description": "Identifier" + }, + "created": { + "type": "date" + }, + "saleFk": { + "type": "number", + "required": true + }, + "userFk": { + "type": "number", + "required": true + }, + "typeFk": { + "type": "number", + "required": true + } + }, + "relations": { + "sale": { + "type": "belongsTo", + "model": "Sale", + "foreignKey": "saleFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "userFk" + }, + "mistakeType": { + "type": "belongsTo", + "model": "MistakeType", + "foreignKey": "typeFk" + } + + } +} \ No newline at end of file diff --git a/modules/ticket/back/models/sale.js b/modules/ticket/back/models/sale.js index ae247fc24..3589eac4b 100644 --- a/modules/ticket/back/models/sale.js +++ b/modules/ticket/back/models/sale.js @@ -1,3 +1,6 @@ +const UserError = require('vn-loopback/util/user-error'); +const LoopBackContext = require('loopback-context'); + module.exports = Self => { require('../methods/sale/getClaimableFromTicket')(Self); require('../methods/sale/reserve')(Self); @@ -9,8 +12,107 @@ module.exports = Self => { require('../methods/sale/refund')(Self); require('../methods/sale/canEdit')(Self); require('../methods/sale/usesMana')(Self); + require('../methods/sale/clone')(Self); Self.validatesPresenceOf('concept', { message: `Concept cannot be blank` }); + + Self.observe('before save', async ctx => { + const models = Self.app.models; + const changes = ctx.data || ctx.instance; + const instance = ctx.currentInstance; + + const newQuantity = changes?.quantity; + if (newQuantity == null) return; + + const loopBackContext = LoopBackContext.getCurrentContext(); + ctx.req = loopBackContext.active; + if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'canForceQuantity', 'WRITE')) return; + + const ticketId = changes?.ticketFk || instance?.ticketFk; + const itemId = changes?.itemFk || instance?.itemFk; + const oldQuantity = instance?.quantity ?? null; + const quantityAdded = newQuantity - oldQuantity; + const isReduction = oldQuantity && newQuantity <= oldQuantity; + + const ticket = await models.Ticket.findById( + ticketId, + { + fields: ['id', 'clientFk', 'warehouseFk', 'addressFk', 'agencyModeFk', 'shipped', 'landed'], + include: { + relation: 'client', + scope: { + fields: ['id', 'clientTypeFk'], + include: { + relation: 'type', + scope: { + fields: ['code', 'description'] + } + } + } + } + }, + ctx.options); + if (ticket?.client()?.type()?.code === 'loses') return; + + const isRefund = await models.TicketRefund.findOne({ + fields: ['id'], + where: {refundTicketFk: ticketId} + }, ctx.options); + if (isRefund) return; + + if (newQuantity < 0) + throw new UserError('You can only add negative amounts in refund tickets'); + + const item = await models.Item.findOne({ + fields: ['family', 'minQuantity'], + where: {id: itemId}, + }, ctx.options); + if (item.family == 'EMB') return; + + if (await models.ACL.checkAccessAcl(ctx, 'Sale', 'isInPreparing', '*')) return; + + await models.Sale.rawSql(`CALL catalog_calcFromItem(?,?,?,?)`, [ + ticket.landed, + ticket.addressFk, + ticket.agencyModeFk, + itemId + ], + ctx.options); + + const [itemInfo] = await models.Sale.rawSql(`SELECT available FROM tmp.ticketCalculateItem`, null, ctx.options); + const available = itemInfo?.available; + + if ((!isReduction && !available) || available < quantityAdded) + throw new UserError(`This item is not available`); + + if (await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*')) return; + + if (newQuantity < item.minQuantity && newQuantity != available) + throw new UserError('The amount cannot be less than the minimum'); + + if (ctx.isNewInstance || isReduction) return; + + const [saleGrouping] = await models.Sale.rawSql(` + SELECT t.price newPrice + FROM tmp.ticketComponentPrice t + ORDER BY (t.grouping <= ?) DESC, t.grouping ASC + LIMIT 1`, + [quantityAdded], + ctx.options); + + await models.Sale.rawSql(` + DROP TEMPORARY TABLE IF EXISTS + tmp.ticketCalculateItem, + tmp.ticketComponentPrice, + tmp.ticketComponent, + tmp.ticketLot, + tmp.zoneGetShipped; + `, null, ctx.options); + + if (!saleGrouping?.newPrice || saleGrouping.newPrice > instance.price) + throw new UserError('The price of the item changed'); + }); }; + diff --git a/modules/ticket/back/models/specs/sale.spec.js b/modules/ticket/back/models/specs/sale.spec.js new file mode 100644 index 000000000..4af44c991 --- /dev/null +++ b/modules/ticket/back/models/specs/sale.spec.js @@ -0,0 +1,361 @@ +/* eslint max-len: ["error", { "code": 150 }]*/ + +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('sale model ', () => { + const ctx = { + req: { + accessToken: {userId: 9}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + function getActiveCtx(userId) { + return { + active: { + accessToken: {userId}, + http: { + req: { + headers: {origin: 'http://localhost'} + } + } + } + }; + } + + describe('quantity field ', () => { + it('should add quantity if the quantity is greater than it should be and is role advanced', async() => { + const saleId = 17; + const buyerId = 35; + const ctx = { + req: { + accessToken: {userId: buyerId}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + const tx = await models.Sale.beginTransaction({}); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(buyerId)); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + try { + const options = {transaction: tx}; + + const isRoleAdvanced = await models.ACL.checkAccessAcl(ctx, 'Ticket', 'isRoleAdvanced', '*'); + + expect(isRoleAdvanced).toEqual(true); + + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(originalLine.quantity).toEqual(30); + + const newQuantity = originalLine.quantity + 1; + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(modifiedLine.quantity).toEqual(newQuantity); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should update the quantity of a given sale current line', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + + const tx = await models.Sale.beginTransaction({}); + const saleId = 25; + const newQuantity = 4; + + try { + const options = {transaction: tx}; + + const originalLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(originalLine.quantity).toEqual(20); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(modifiedLine.quantity).toEqual(newQuantity); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error if the quantity is negative and it is not a refund ticket', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const saleId = 17; + const newQuantity = -10; + + const tx = await models.Sale.beginTransaction({}); + + let error; + try { + const options = {transaction: tx}; + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('You can only add negative amounts in refund tickets')); + }); + + it('should update a negative quantity when is a ticket refund', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(9)); + + const tx = await models.Sale.beginTransaction({}); + const saleId = 13; + const newQuantity = -10; + + try { + const options = {transaction: tx}; + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + const modifiedLine = await models.Sale.findOne({where: {id: saleId}, fields: ['quantity']}, options); + + expect(modifiedLine.quantity).toEqual(newQuantity); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error if the quantity is less than the minimum quantity of the item', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = minQuantity - 1; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT 100 as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The amount cannot be less than the minimum')); + }); + + it('should change quantity if has minimum quantity and new quantity is equal than item available', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = minQuantity - 1; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = `CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY + SELECT ${newQuantity} as available;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + describe('newPrice', () => { + it('should increase quantity if you have enough available and the new price is the same as the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 7.07 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should increase quantity when the new price is lower than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 1 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw error when increase quantity and the new price is higher than the previous one', async() => { + const ctx = { + req: { + accessToken: {userId: 1}, + headers: {origin: 'localhost:5000'}, + __: () => {} + } + }; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue(getActiveCtx(1)); + + const tx = await models.Sale.beginTransaction({}); + const itemId = 2; + const saleId = 17; + const minQuantity = 30; + const newQuantity = 31; + + let error; + try { + const options = {transaction: tx}; + + const item = await models.Item.findById(itemId, null, options); + await item.updateAttribute('minQuantity', minQuantity, options); + spyOn(models.Sale, 'rawSql').and.callFake((sqlStatement, params, options) => { + if (sqlStatement.includes('catalog_calcFromItem')) { + sqlStatement = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem ENGINE = MEMORY SELECT ${newQuantity} as available; + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY SELECT 1 as grouping, 100000 as price;`; + params = null; + } + return models.Ticket.rawSql(sqlStatement, params, options); + }); + + await models.Sale.updateQuantity(ctx, saleId, newQuantity, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).toEqual(new Error('The price of the item changed')); + }); + }); + }); +}); diff --git a/modules/ticket/back/models/ticket-collection.json b/modules/ticket/back/models/ticket-collection.json index e941ac2ce..4bd34f08e 100644 --- a/modules/ticket/back/models/ticket-collection.json +++ b/modules/ticket/back/models/ticket-collection.json @@ -10,6 +10,9 @@ "id": { "id": true, "type": "number" + }, + "usedShelves": { + "type": "number" } }, "relations": { diff --git a/modules/ticket/back/models/ticket-request.js b/modules/ticket/back/models/ticket-request.js index 4125126dc..d133f85d5 100644 --- a/modules/ticket/back/models/ticket-request.js +++ b/modules/ticket/back/models/ticket-request.js @@ -10,7 +10,7 @@ module.exports = function(Self) { Self.observe('before save', async function(ctx) { if (ctx.isNewInstance) { const loopBackContext = LoopBackContext.getCurrentContext(); - const filter = {where: {userFk: loopBackContext.active.accessToken.userId}}; + const filter = {where: {id: loopBackContext.active.accessToken.userId}}; const models = Self.app.models; const worker = await models.Worker.findOne(filter); diff --git a/modules/ticket/back/models/ticket-tracking.js b/modules/ticket/back/models/ticket-tracking.js index 2e6d3403e..92e046d3e 100644 --- a/modules/ticket/back/models/ticket-tracking.js +++ b/modules/ticket/back/models/ticket-tracking.js @@ -1,5 +1,4 @@ module.exports = function(Self) { - require('../methods/ticket-tracking/changeState')(Self); require('../methods/ticket-tracking/setDelivered')(Self); Self.validatesPresenceOf('stateFk', {message: 'State cannot be blank'}); diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index ea068ef8a..1930765fb 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -1,4 +1,4 @@ module.exports = Self => { - // Methods require('./ticket-methods')(Self); + require('../methods/ticket/state')(Self); }; diff --git a/modules/ticket/front/advance-search-panel/index.js b/modules/ticket/front/advance-search-panel/index.js index 8ddbe78d4..218fb14d3 100644 --- a/modules/ticket/front/advance-search-panel/index.js +++ b/modules/ticket/front/advance-search-panel/index.js @@ -16,8 +16,8 @@ class Controller extends SearchPanel { this.$http.get('ItemPackingTypes', {filter}).then(res => { for (let ipt of res.data) { itemPackingTypes.push({ - code: ipt.code, - description: this.$t(ipt.description) + description: this.$t(ipt.description), + code: ipt.code }); } this.itemPackingTypes = itemPackingTypes; diff --git a/modules/ticket/front/advance/index.html b/modules/ticket/front/advance/index.html index e6f16c965..a6cf8face 100644 --- a/modules/ticket/front/advance/index.html +++ b/modules/ticket/front/advance/index.html @@ -81,6 +81,9 @@ Liters + + Zone + Not Movable @@ -155,6 +158,7 @@ {{::ticket.futureLiters | dashIfEmpty}} + {{::ticket.futureZoneName | dashIfEmpty}} {{::ticket.notMovableLines | dashIfEmpty}} {{::ticket.futureLines | dashIfEmpty}} diff --git a/modules/ticket/front/advance/index.js b/modules/ticket/front/advance/index.js index 0cec41227..389bcdf14 100644 --- a/modules/ticket/front/advance/index.js +++ b/modules/ticket/front/advance/index.js @@ -15,28 +15,22 @@ export default class Controller extends Section { { field: 'state', searchable: false - }, - { + }, { field: 'futureState', searchable: false - }, - { + }, { field: 'totalWithVat', searchable: false - }, - { + }, { field: 'futureTotalWithVat', searchable: false - }, - { + }, { field: 'shipped', searchable: false - }, - { + }, { field: 'futureShipped', searchable: false - }, - { + }, { field: 'ipt', autocomplete: { url: 'ItemPackingTypes', @@ -44,8 +38,7 @@ export default class Controller extends Section { showField: 'description', valueField: 'code' } - }, - { + }, { field: 'futureIpt', autocomplete: { url: 'ItemPackingTypes', @@ -53,6 +46,11 @@ export default class Controller extends Section { showField: 'description', valueField: 'code' } + }, { + field: 'futureZoneFk', + autocomplete: { + url: 'Zones', + } }, ] }; @@ -158,37 +156,21 @@ export default class Controller extends Section { exprBuilder(param, value) { switch (param) { case 'id': - return {'id': value}; case 'futureId': - return {'futureId': value}; case 'liters': - return {'liters': value}; - case 'lines': - return {'lines': value}; case 'futureLiters': - return {'futureLiters': value}; + case 'lines': case 'futureLines': - return {'futureLines': value}; - case 'ipt': - return {or: - [ - {'ipt': {like: `%${value}%`}}, - {'ipt': null} - ] - }; - case 'futureIpt': - return {or: - [ - {'futureIpt': {like: `%${value}%`}}, - {'futureIpt': null} - ] - }; case 'totalWithVat': - return {'totalWithVat': value}; case 'futureTotalWithVat': - return {'futureTotalWithVat': value}; + case 'futureZone': case 'notMovableLines': - return {'notMovableLines': value}; + case 'futureZoneFk': + return {[param]: value}; + case 'ipt': + return {'ipt': {like: `%${value}%`}}; + case 'futureIpt': + return {'futureIpt': {like: `%${value}%`}}; } } } diff --git a/modules/ticket/front/descriptor-menu/index.js b/modules/ticket/front/descriptor-menu/index.js index d1f39fd19..18db8c147 100644 --- a/modules/ticket/front/descriptor-menu/index.js +++ b/modules/ticket/front/descriptor-menu/index.js @@ -201,7 +201,7 @@ class Controller extends Section { sendImportSms() { const params = { ticketId: this.id, - created: this.ticket.updated + shipped: this.ticket.shipped }; this.showSMSDialog({ message: this.$t('Minimum is needed', params) diff --git a/modules/ticket/front/descriptor/locale/en.yml b/modules/ticket/front/descriptor/locale/en.yml index 8eed2265d..698d699d7 100644 --- a/modules/ticket/front/descriptor/locale/en.yml +++ b/modules/ticket/front/descriptor/locale/en.yml @@ -1,3 +1,3 @@ Make a payment: "Verdnatura communicates:\rYour order is pending of payment.\rPlease, enter the web page and make the payment with card.\rThank you." -Minimum is needed: "Verdnatura communicates:\rA minimum import of 50€ (Without BAT) is needed for your order {{ticketId}} from date {{created | date: 'dd/MM/yyyy'}} to receive it with no extra fees." +Minimum is needed: "Verdnatura communicates:\rA minimum import of 50€ (Without BAT) is needed for your order {{ticketId}} from date {{shipped | date: 'dd/MM/yyyy'}} to receive it with no extra fees." Send changes: "Verdnatura communicates:\rOrder {{ticketId}} date {{created | date: 'dd/MM/yyyy'}}\r{{changes}}" diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index 86b1a6b57..b809c1b83 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -3,8 +3,8 @@ Are you sure you want to send it?: ¿Seguro que quieres enviarlo? Show pallet report: Ver hoja de pallet Change shipped hour: Cambiar hora de envío Shipped hour: Hora de envío -Make a payment: "Verdnatura le comunica:\rSu pedido está pendiente de pago.\rPor favor, entre en la página web y efectue el pago con tarjeta.\rMuchas gracias." -Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{created | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." +Make a payment: "Verdnatura le comunica:\rSu pedido está pendiente de pago.\rPor favor, entre en la página web y efectúe el pago con tarjeta.\rMuchas gracias." +Minimum is needed: "Verdnatura le recuerda:\rEs necesario un importe mínimo de 50€ (Sin IVA) en su pedido {{ticketId}} del día {{shipped | date: 'dd/MM/yyyy'}} para recibirlo sin portes adicionales." Ticket invoiced: Ticket facturado Make invoice: Crear factura Regenerate invoice PDF: Regenerar PDF factura diff --git a/modules/ticket/front/dms/index/index.js b/modules/ticket/front/dms/index/index.js index 2ec7e03c0..676a28db8 100644 --- a/modules/ticket/front/dms/index/index.js +++ b/modules/ticket/front/dms/index/index.js @@ -29,7 +29,7 @@ class Controller extends Section { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/ticket/front/index/locale/es.yml b/modules/ticket/front/index/locale/es.yml index afa3d654e..89828d4d9 100644 --- a/modules/ticket/front/index/locale/es.yml +++ b/modules/ticket/front/index/locale/es.yml @@ -18,3 +18,4 @@ Multiple invoice: Factura múltiple Make invoice...: Crear factura... Invoice selected tickets: Facturar tickets seleccionados Are you sure to invoice tickets: ¿Seguro que quieres facturar {{ticketsAmount}} tickets? +Rounding: Redondeo diff --git a/modules/ticket/front/log/index.html b/modules/ticket/front/log/index.html index 91109d3eb..c36b0aa52 100644 --- a/modules/ticket/front/log/index.html +++ b/modules/ticket/front/log/index.html @@ -1 +1,6 @@ - \ No newline at end of file + + diff --git a/modules/ticket/front/routes.json b/modules/ticket/front/routes.json index e403ab02d..da39fbbf7 100644 --- a/modules/ticket/front/routes.json +++ b/modules/ticket/front/routes.json @@ -187,7 +187,7 @@ } }, { - "url" : "/log", + "url" : "/log?changedModel&changedModelId", "state": "ticket.card.log", "component": "vn-ticket-log", "description": "Log" diff --git a/modules/ticket/front/sale/index.html b/modules/ticket/front/sale/index.html index be9e81964..262395d16 100644 --- a/modules/ticket/front/sale/index.html +++ b/modules/ticket/front/sale/index.html @@ -15,7 +15,7 @@ + on-change="$ctrl.state(value)"> - - @@ -318,7 +311,7 @@ clear-disabled="true" suffix="%"> - + { - this.currentWorkerMana = res.data; - }); } getUsesMana() { @@ -179,9 +171,9 @@ class Controller extends Section { this.card.reload(); } - changeState(value) { + state(value) { const params = {ticketFk: this.$params.id, code: value}; - return this.$http.post('TicketTrackings/changeState', params).then(() => { + return this.$http.post('Tickets/state', params).then(() => { this.vnApp.showSuccess(this.$t('Data saved!')); this.card.reload(); }).finally(() => this.resetChanges()); @@ -558,6 +550,14 @@ class Controller extends Section { cancel() { this.$.editDiscount.hide(); } + + goToLog(saleId) { + this.$state.go('ticket.card.log', { + originId: this.$params.id, + changedModel: 'Sale', + changedModelId: saleId + }); + } } ngModule.vnComponent('vnTicketSale', { diff --git a/modules/ticket/front/sale/index.spec.js b/modules/ticket/front/sale/index.spec.js index 9da8e6e7c..70781eb58 100644 --- a/modules/ticket/front/sale/index.spec.js +++ b/modules/ticket/front/sale/index.spec.js @@ -120,12 +120,10 @@ describe('Ticket', () => { const expectedAmount = 250; $httpBackend.expect('GET', 'Tickets/1/getSalesPersonMana').respond(200, expectedAmount); $httpBackend.expect('GET', 'Sales/usesMana').respond(200); - $httpBackend.expect('GET', 'WorkerManas/getCurrentWorkerMana').respond(200, expectedAmount); controller.getMana(); $httpBackend.flush(); expect(controller.edit.mana).toEqual(expectedAmount); - expect(controller.currentWorkerMana).toEqual(expectedAmount); }); }); @@ -230,15 +228,16 @@ describe('Ticket', () => { }); }); - describe('changeState()', () => { - it('should make an HTTP post query, then call the showSuccess(), reload() and resetChanges() methods', () => { + describe('state()', () => { + it('should make an HTTP post query, then call the showSuccess(),' + + ' reload() and resetChanges() methods', () => { jest.spyOn(controller.card, 'reload').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); const expectedParams = {ticketFk: 1, code: 'OK'}; - $httpBackend.expect('POST', `TicketTrackings/changeState`, expectedParams).respond(200); - controller.changeState('OK'); + $httpBackend.expect('POST', `Tickets/state`, expectedParams).respond(200); + controller.state('OK'); $httpBackend.flush(); expect(controller.card.reload).toHaveBeenCalledWith(); @@ -248,7 +247,8 @@ describe('Ticket', () => { }); describe('removeSales()', () => { - it('should make an HTTP post query, then call the showSuccess(), removeSelectedSales() and resetChanges() methods', () => { + it('should make an HTTP post query, then call the showSuccess(),' + + ' removeSelectedSales() and resetChanges() methods', () => { jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'removeSelectedSales').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); @@ -354,7 +354,8 @@ describe('Ticket', () => { }); describe('updatePrice()', () => { - it('should make an HTTP POST query, update the sale price and then call to the resetChanges() method', () => { + it('should make an HTTP POST query, update the sale price ' + + 'and then call to the resetChanges() method', () => { jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); jest.spyOn(controller, 'resetChanges').mockReturnThis(); @@ -420,7 +421,8 @@ describe('Ticket', () => { expect(controller.$.editDiscount.hide).toHaveBeenCalledWith(); }); - it('should not call to the updateDiscount() method and then to the editDiscountDialog hide() method', () => { + it('should not call to the updateDiscount() method and then' + + ' to the editDiscountDialog hide() method', () => { jest.spyOn(controller, 'updateDiscount').mockReturnThis(); const firstSelectedSale = controller.sales[0]; @@ -446,7 +448,8 @@ describe('Ticket', () => { }); describe('updateDiscount()', () => { - it('should make an HTTP POST query, update the sales discount and then call to the resetChanges() method', () => { + it('should make an HTTP POST query, update the sales discount ' + + 'and then call to the resetChanges() method', () => { jest.spyOn(controller, 'resetChanges').mockReturnThis(); jest.spyOn(controller.vnApp, 'showSuccess').mockReturnThis(); diff --git a/modules/ticket/front/services/index.html b/modules/ticket/front/services/index.html index bc288a8a2..5128873c4 100644 --- a/modules/ticket/front/services/index.html +++ b/modules/ticket/front/services/index.html @@ -29,7 +29,7 @@ disabled="watcher.dataChanged() || !$ctrl.checkeds.length" label="Pay" ng-click="$ctrl.createRefund()" - vn-acl="invoicing, claimManager, salesAssistant" + vn-acl="invoicing, claimManager, salesAssistant, buyer" vn-acl-action="remove"> @@ -37,7 +37,9 @@ + disabled="!service.id" + vn-acl="invoicing, claimManager, salesAssistant, buyer" + vn-acl-action="remove"> + step="0.01" + min="0"> + on-change="$ctrl.state(value)"> + > + + > + + ng-if="$ctrl.summary.client.phone != null"> + + ng-if="$ctrl.summary.client.mobile != null"> + @@ -202,7 +212,7 @@ {{::sale.quantity}}
- {{::sale.item.name}} + {{::sale.concept}}

{{::sale.item.subName}}

diff --git a/modules/ticket/front/summary/index.js b/modules/ticket/front/summary/index.js index 60394b5b3..9d161f63e 100644 --- a/modules/ticket/front/summary/index.js +++ b/modules/ticket/front/summary/index.js @@ -59,13 +59,12 @@ class Controller extends Summary { this.$.invoiceOutDescriptor.show(event.target, this.summary.invoiceOut.id); } - changeState(value) { + state(value) { const params = { ticketFk: 'id' in this.ticket ? this.ticket.id : this.$params.id, code: value }; - - this.$http.post(`TicketTrackings/changeState`, params) + this.$http.post(`Tickets/state`, params) .then(() => { if ('id' in this.$params) this.reload(); }) diff --git a/modules/ticket/front/summary/index.spec.js b/modules/ticket/front/summary/index.spec.js index 599da73ae..6837bfd54 100644 --- a/modules/ticket/front/summary/index.spec.js +++ b/modules/ticket/front/summary/index.spec.js @@ -43,15 +43,15 @@ describe('Ticket', () => { }); }); - describe('changeState()', () => { + describe('state()', () => { it('should change the state', () => { jest.spyOn(controller.vnApp, 'showSuccess'); const value = 'myTicketState'; let res = {id: 1, nickname: 'myNickname'}; $httpBackend.when('GET', `Tickets/1/summary`).respond(200, res); - $httpBackend.expectPOST(`TicketTrackings/changeState`).respond(200, 'ok'); - controller.changeState(value); + $httpBackend.expectPOST(`Tickets/state`).respond(200, 'ok'); + controller.state(value); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); diff --git a/modules/ticket/front/summary/style.scss b/modules/ticket/front/summary/style.scss index e92ff0d42..2f52de65e 100644 --- a/modules/ticket/front/summary/style.scss +++ b/modules/ticket/front/summary/style.scss @@ -47,4 +47,9 @@ vn-ticket-summary .summary { } } } + + vn-icon.tel { + font-size: 1.1em; + vertical-align: bottom; + } } \ No newline at end of file diff --git a/modules/ticket/front/tracking/edit/index.html b/modules/ticket/front/tracking/edit/index.html index bff8e71b1..47f367007 100644 --- a/modules/ticket/front/tracking/edit/index.html +++ b/modules/ticket/front/tracking/edit/index.html @@ -1,4 +1,4 @@ - + { + this.$http.post(`Tickets/state`, this.params).then(() => { this.$.watcher.updateOriginalData(); this.card.reload(); this.vnApp.showSuccess(this.$t('Data saved!')); diff --git a/modules/ticket/front/tracking/edit/index.spec.js b/modules/ticket/front/tracking/edit/index.spec.js index 1ba5912b5..9d9aa7983 100644 --- a/modules/ticket/front/tracking/edit/index.spec.js +++ b/modules/ticket/front/tracking/edit/index.spec.js @@ -61,7 +61,7 @@ describe('Ticket', () => { jest.spyOn(controller.vnApp, 'showSuccess'); jest.spyOn(controller.$state, 'go'); - $httpBackend.expectPOST(`TicketTrackings/changeState`, controller.params).respond({}); + $httpBackend.expectPOST(`Tickets/state`, controller.params).respond({}); controller.onSubmit(); $httpBackend.flush(); diff --git a/modules/ticket/front/tracking/index/index.js b/modules/ticket/front/tracking/index/index.js index 38abcd8ab..95665b071 100644 --- a/modules/ticket/front/tracking/index/index.js +++ b/modules/ticket/front/tracking/index/index.js @@ -9,7 +9,7 @@ class Controller extends Section { { relation: 'worker', scope: { - fields: ['userFk'], + fields: ['id'], include: { relation: 'user', scope: { diff --git a/modules/travel/back/methods/travel/extraCommunityFilter.js b/modules/travel/back/methods/travel/extraCommunityFilter.js index 388ba52a1..488297318 100644 --- a/modules/travel/back/methods/travel/extraCommunityFilter.js +++ b/modules/travel/back/methods/travel/extraCommunityFilter.js @@ -132,12 +132,18 @@ module.exports = Self => { s.nickname AS cargoSupplierNickname, s.name AS supplierName, CAST(SUM(b.weight * b.stickers) as DECIMAL(10,0)) as loadedKg, - CAST(SUM(vc.aerealVolumetricDensity * b.stickers * IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000) as DECIMAL(10,0)) as volumeKg + CAST( + SUM( + vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 + ) as DECIMAL(10,0) + ) as volumeKg FROM travel t LEFT JOIN supplier s ON s.id = t.cargoSupplierFk LEFT JOIN entry e ON e.travelFk = t.id LEFT JOIN buy b ON b.entryFk = e.id - LEFT JOIN packaging pkg ON pkg.id = b.packageFk + LEFT JOIN packaging pkg ON pkg.id = b.packagingFk LEFT JOIN item i ON i.id = b.itemFk LEFT JOIN itemType it ON it.id = i.typeFk JOIN warehouse w ON w.id = t.warehouseInFk @@ -169,11 +175,17 @@ module.exports = Self => { e.evaNotes, e.invoiceAmount, CAST(SUM(b.weight * b.stickers) AS DECIMAL(10,0)) as loadedkg, - CAST(SUM(vc.aerealVolumetricDensity * b.stickers * IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000) AS DECIMAL(10,0)) as volumeKg + CAST( + SUM( + vc.aerealVolumetricDensity * + b.stickers * + IF(pkg.volume, pkg.volume, pkg.width * pkg.depth * pkg.height) / 1000000 + ) AS DECIMAL(10,0) + ) as volumeKg FROM tmp.travel tr JOIN entry e ON e.travelFk = tr.id JOIN buy b ON b.entryFk = e.id - JOIN packaging pkg ON pkg.id = b.packageFk + JOIN packaging pkg ON pkg.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 diff --git a/modules/travel/back/methods/travel/getEntries.js b/modules/travel/back/methods/travel/getEntries.js index 71bb0d8fb..50088ccfa 100644 --- a/modules/travel/back/methods/travel/getEntries.js +++ b/modules/travel/back/methods/travel/getEntries.js @@ -47,7 +47,7 @@ module.exports = Self => { LEFT JOIN vn.buy b ON b.entryFk = e.id LEFT JOIN vn.supplier s ON e.supplierFk = s.id JOIN vn.item i ON i.id = b.itemFk - LEFT JOIN vn.packaging p ON p.id = b.packageFk + LEFT JOIN vn.packaging p ON p.id = b.packagingFk JOIN vn.packaging pcc ON pcc.id = 'cc' JOIN vn.packaging ppallet ON ppallet.id = 'pallet 100' JOIN vn.packagingConfig pconfig diff --git a/modules/worker/back/methods/calendar/specs/absences.spec.js b/modules/worker/back/methods/calendar/specs/absences.spec.js index 365773182..b27c9549c 100644 --- a/modules/worker/back/methods/calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/calendar/specs/absences.spec.js @@ -50,7 +50,7 @@ describe('Worker absences()', () => { } }); - it('should give the same holidays as worked days since the holidays amount matches the amount of days in a year', async() => { + it('Should have an equal number of holidays and workdays, as they both total the days in a year', async() => { const businessId = 1106; const workerId = 1106; diff --git a/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js b/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js deleted file mode 100644 index fa34af475..000000000 --- a/modules/worker/back/methods/worker-mana/getCurrentWorkerMana.js +++ /dev/null @@ -1,26 +0,0 @@ -module.exports = Self => { - Self.remoteMethodCtx('getCurrentWorkerMana', { - description: 'Returns the mana of the logged worker', - accessType: 'READ', - accepts: [], - returns: { - type: 'number', - root: true - }, - http: { - path: `/getCurrentWorkerMana`, - verb: 'GET' - } - }); - - Self.getCurrentWorkerMana = async ctx => { - let userId = ctx.req.accessToken.userId; - - let workerMana = await Self.app.models.WorkerMana.findOne({ - where: {workerFk: userId}, - fields: 'amount' - }); - - return workerMana ? workerMana.amount : 0; - }; -}; diff --git a/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js b/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js deleted file mode 100644 index 8d626e720..000000000 --- a/modules/worker/back/methods/worker-mana/specs/getCurrentWorkerMana.spec.js +++ /dev/null @@ -1,15 +0,0 @@ -const app = require('vn-loopback/server/server'); - -describe('workerMana getCurrentWorkerMana()', () => { - it('should get the mana of the logged worker', async() => { - let mana = await app.models.WorkerMana.getCurrentWorkerMana({req: {accessToken: {userId: 18}}}); - - expect(mana).toEqual(124); - }); - - it('should return 0 if the user doesnt uses mana', async() => { - let mana = await app.models.WorkerMana.getCurrentWorkerMana({req: {accessToken: {userId: 9}}}); - - expect(mana).toEqual(0); - }); -}); diff --git a/modules/worker/back/methods/worker-time-control/sendMail.js b/modules/worker/back/methods/worker-time-control/sendMail.js index 66fb7cc23..6f67bbea3 100644 --- a/modules/worker/back/methods/worker-time-control/sendMail.js +++ b/modules/worker/back/methods/worker-time-control/sendMail.js @@ -66,46 +66,36 @@ module.exports = Self => { stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate'); stmts.push('DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate'); + const destroyAllWhere = { + timed: {between: [started, ended]}, + isSendMail: true + }; + const updateAllWhere = { + year: args.year, + week: args.week + }; + + const tmpUserSQL = ` + CREATE OR REPLACE TEMPORARY TABLE tmp.user + SELECT id as userFk + FROM vn.worker`; + let tmpUser = new ParameterizedSQL(tmpUserSQL); + if (args.workerId) { - await models.WorkerTimeControl.destroyAll({ - userFk: args.workerId, - timed: {between: [started, ended]}, - isSendMail: true - }, myOptions); - - const where = { - workerFk: args.workerId, - year: args.year, - week: args.week - }; - await models.WorkerTimeControlMail.updateAll(where, { - updated: Date.vnNew(), state: 'SENDED' - }, myOptions); - - stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`'); - stmts.push(stmt); - stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE tmp.`user` SELECT id userFk FROM account.user WHERE id = ?', [args.workerId]); - stmts.push(stmt); - } else { - await models.WorkerTimeControl.destroyAll({ - timed: {between: [started, ended]}, - isSendMail: true - }, myOptions); - - const where = { - year: args.year, - week: args.week - }; - await models.WorkerTimeControlMail.updateAll(where, { - updated: Date.vnNew(), state: 'SENDED' - }, myOptions); - - stmt = new ParameterizedSQL('DROP TEMPORARY TABLE IF EXISTS tmp.`user`'); - stmts.push(stmt); - stmt = new ParameterizedSQL('CREATE TEMPORARY TABLE IF NOT EXISTS tmp.`user` SELECT userFk FROM vn.worker w JOIN account.`user` u ON u.id = w.userFk WHERE userFk IS NOT NULL'); - stmts.push(stmt); + destroyAllWhere.userFk = args.workerId; + updateAllWhere.workerFk = args.workerId; + tmpUser = new ParameterizedSQL(tmpUserSQL + ' WHERE id = ?', [args.workerId]); } + await models.WorkerTimeControl.destroyAll(destroyAllWhere, myOptions); + + await models.WorkerTimeControlMail.updateAll(updateAllWhere, { + updated: Date.vnNew(), + state: 'SENDED' + }, myOptions); + + stmts.push(tmpUser); + stmt = new ParameterizedSQL( `CALL vn.timeControl_calculate(?, ?) `, [started, ended]); diff --git a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js index e90c849b7..42ec6290a 100644 --- a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js @@ -14,7 +14,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { const tuesday = 2; const thursday = 4; const friday = 5; - const saturday = 6; const sunday = 7; const activeCtx = { accessToken: {userId: 50}, @@ -200,15 +199,15 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); describe('WorkerTimeControl_clockIn calls', () => { - it('should fail to add a time entry if the target user has an absence that day', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); + let workerId; + beforeEach(() => { activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; + workerId = hankPymId; + }); + it('should fail to add a time entry if the target user has an absence that day', async() => { const date = Date.vnNew(); - date.setDate(date.getDate() - 16); date.setHours(8, 0, 0); - let error; - + date.setDate(date.getDate() - 16); const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; try { @@ -225,15 +224,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should fail to add a time entry for a worker without an existing contract', async() => { - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; const date = Date.vnNew(); date.setFullYear(date.getFullYear() - 2); - let error; const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; try { - const options = {transaction: tx}; ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); @@ -246,19 +242,39 @@ describe('workerTimeControl add/delete timeEntry()', () => { expect(error.message).toBe(`No hay un contrato en vigor`); }); + it('should fail to add a time entry for a worker without an existing contract', async() => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 2); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + date.setHours(0, 0, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + try { + date.setHours(20,0, 1); + ctx.args = {timed: date, direction: 'out'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toBe(`Superado el tiempo máximo entre entrada y salida`); + }); + describe('direction errors', () => { + let date = Date.vnNew(); + date.setDate(date.getDate() - 1); + let error; it('should throw an error when trying "in" direction twice', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; + date.setHours(8, 0, 0); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); @@ -278,21 +294,13 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should throw an error when trying "in" direction after insert "in" and "middle"', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; date.setHours(8, 0, 0); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + date.setHours(9, 0, 0); ctx.args = {timed: date, direction: 'middle'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); @@ -312,15 +320,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('Should throw an error when trying "out" before closing a "middle" couple', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; @@ -346,15 +345,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should throw an error when trying "middle" after "out"', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; @@ -380,15 +370,6 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); it('should throw an error when trying "out" direction twice', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); - date = weekDay(date, monday); - let error; - const tx = await models.WorkerTimeControl.beginTransaction({}); const options = {transaction: tx}; @@ -415,14 +396,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); describe('12h rest', () => { + activeCtx.accessToken.userId = salesBossId; + const workerId = hankPymId; it('should throw an error when the 12h rest is not fulfilled yet', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -448,16 +427,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { error = e; } - expect(error.message).toBe(`Descanso diario 12h.`); + expect(error.message).toBe(`Descanso diario`); }); it('should not fail as the 12h rest is fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -488,13 +463,12 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); describe('for 3500kg drivers with enforced 9h rest', () => { + activeCtx.accessToken.userId = salesBossId; + const workerId = jessicaJonesId; it('should throw an error when the 9h enforced rest is not fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = jessicaJonesId; let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -520,16 +494,13 @@ describe('workerTimeControl add/delete timeEntry()', () => { error = e; } - expect(error.message).toBe(`Descanso diario 9h.`); + expect(error.message).toBe(`Descanso diario`); }); it('should not fail when the 9h enforced rest is fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = jessicaJonesId; - + let date = Date.vnNew(); - date.setDate(date.getDate() - 21); + date.setDate(date.getDate() - 2); date = weekDay(date, monday); let error; @@ -559,14 +530,11 @@ describe('workerTimeControl add/delete timeEntry()', () => { }); }); - describe('for 36h weekly rest', () => { - it('should throw an error when the 36h weekly rest is not fulfilled', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - + describe('for 72h weekly rest', () => { + + it('should throw an error when work 11 consecutive days', async() => { let date = Date.vnNew(); - date.setMonth(date.getMonth() - 2); + date.setMonth(date.getMonth() - 1); date.setDate(1); let error; @@ -576,66 +544,24 @@ describe('workerTimeControl add/delete timeEntry()', () => { await populateWeek(date, monday, sunday, ctx, workerId, options); date = nextWeek(date); await populateWeek(date, monday, thursday, ctx, workerId, options); - date = weekDay(date, friday); - date.setHours(7, 59, 0); - ctx.args = {timed: date, direction: 'in'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - try { - date.setHours(8, 1, 0); - ctx.args = {timed: date, direction: 'out'}; - await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - - await tx.rollback(); - } catch (e) { - await tx.rollback(); - error = e; - } - - expect(error.message).toBe(`Descanso semanal 36h. / 72h.`); - }); - - it('should throw an error when the 36h weekly rest is not fulfilled again', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; - - let date = Date.vnNew(); - date.setMonth(date.getMonth() - 2); - date.setDate(1); - let error; - - const tx = await models.WorkerTimeControl.beginTransaction({}); - const options = {transaction: tx}; - - await populateWeek(date, monday, sunday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, thursday, ctx, workerId, options); - - try { - date = weekDay(date, saturday); - date.setHours(3, 59, 0); + date = weekDay(date, friday); + date.setHours(10, 0, 1); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); } catch (e) { await tx.rollback(); error = e; } - expect(error.message).toBe(`Descanso semanal 36h. / 72h.`); + expect(error.message).toBe(`Descanso semanal`); }); - }); - describe('for 72h weekly rest', () => { - it('should throw when the 72h weekly rest is not fulfilled yet', async() => { - pending('https://redmine.verdnatura.es/issues/4707'); - activeCtx.accessToken.userId = salesBossId; - const workerId = hankPymId; + it('should throw an error when the 72h weekly rest is not fulfilled', async() => { let date = Date.vnNew(); - date.setMonth(date.getMonth() - 2); + date.setMonth(date.getMonth() - 1); date.setDate(1); let error; @@ -645,32 +571,263 @@ describe('workerTimeControl add/delete timeEntry()', () => { await populateWeek(date, monday, sunday, ctx, workerId, options); date = nextWeek(date); await populateWeek(date, monday, thursday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, friday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, saturday, ctx, workerId, options); - date = nextWeek(date); - await populateWeek(date, monday, saturday, ctx, workerId, options); - date = lastWeek(date); try { date = weekDay(date, sunday); - date.setHours(8, 0, 0); + date.setHours(17, 59, 0); ctx.args = {timed: date, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - await tx.rollback(); } catch (e) { await tx.rollback(); error = e; } - expect(error.message).toBe(`Descanso semanal 36h. / 72h.`); + expect(error.message).toBe(`Descanso semanal`); + }); + + it('should throw an error when the 72h weekly rest is fulfilled', async() => { + + let date = Date.vnNew(); + date.setMonth(date.getMonth() - 1); + date.setDate(1); + let error; + + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + await populateWeek(date, monday, sunday, ctx, workerId, options); + date = nextWeek(date); + await populateWeek(date, monday, thursday, ctx, workerId, options); + + try { + date = weekDay(date, sunday); + date.setHours(18, 00, 0); + ctx.args = {timed: date, direction: 'in'}; + await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error).not.toBeDefined; + }); + }); + + describe('WorkerTimeControl_calculate calls', () => { + let dated = Date.vnNew(); + dated.setDate(dated.getDate() - 7); + dated = new Date(weekDay(dated, monday)); + const end = new Date(dated); + end.setDate(end.getDate() + 1); + + it(`should return today's worked 8 hours without break`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28800); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 15min break and work time consecutive less than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(14, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 14, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28800); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 15min break and work time consecutive greater than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(15, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 15, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28800); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 25min break and work time consecutive less than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(14, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 24, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28500); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 25min break and work time consecutive greater than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(15, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 25, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(28500); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 60min break and work time consecutive less than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(14, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(15, 59, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(25200); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it(`should return today's worked hours with 60min break and work time consecutive greater than 5h`, async() => { + const tx = await models.WorkerTimeControl.beginTransaction({}); + const options = {transaction: tx}; + + try { + await populateWeek(dated, monday, monday, ctx, hankPymId, options); + dated.setHours(15, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + dated.setHours(16, 0, 0); + await addTimeEntry(ctx, dated, 'middle', hankPymId, options); + + const start = new Date(dated - 1); + start.setHours(0, 0, 0); + await models.WorkerTimeControl.rawSql('CALL vn.timeControl_calculateByUser(?, ?, ?)', [ + hankPymId, + start, + end + ], options); + + let [timeControlCalculateTable] = await models.WorkerTimeControl.rawSql('SELECT * FROM tmp.timeControlCalculate', null, options); + + expect(timeControlCalculateTable.timeWorkSeconds).toEqual(26400); + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } }); }); }); }); +async function addTimeEntry(ctx, dated, direction, userId, option) { + ctx.args = {timed: dated, direction}; + await models.WorkerTimeControl.addTimeEntry(ctx, userId, option); +} + function weekDay(date, dayToSet) { const currentDay = date.getDay(); const distance = dayToSet - currentDay; @@ -704,10 +861,10 @@ async function populateWeek(date, dayStart, dayEnd, ctx, workerId, options) { dateEnd.setDate(dateStart.getDate() + dayEnd); for (let i = dayStart; i <= dayEnd; i++) { - dateStart.setHours(8, 0, 0); + dateStart.setHours(10, 0, 0); ctx.args = {timed: dateStart, direction: 'in'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); - dateStart.setHours(16, 0, 0); + dateStart.setHours(18, 0, 0); ctx.args = {timed: dateStart, direction: 'out'}; await models.WorkerTimeControl.addTimeEntry(ctx, workerId, options); dateStart.setDate(dateStart.getDate() + 1); diff --git a/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js b/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js new file mode 100644 index 000000000..3b5b2b73f --- /dev/null +++ b/modules/worker/back/methods/worker-time-control/specs/updateWorkerTimeControlMail.spec.js @@ -0,0 +1,103 @@ +const models = require('vn-loopback/server/server').models; + +describe('updateWorkerTimeControlMail()', () => { + it('should update WorkerTimeControlMail if exist record', async() => { + const tx = await models.WorkerTimeControlMail.beginTransaction({}); + const args = { + workerId: 9, + week: 50, + year: 2000, + state: 'CONFIRMED' + }; + const ctx = {args}; + + try { + const options = {transaction: tx}; + const beforeMail = await models.WorkerTimeControlMail.findOne({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + const afterMail = await models.WorkerTimeControlMail.findOne({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + + expect(beforeMail.state).toEqual('SENDED'); + expect(afterMail.state).toEqual(args.state); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should insert WorkerTimeControlMail if exist record', async() => { + const tx = await models.WorkerTimeControlMail.beginTransaction({}); + const args = { + workerId: 1, + week: 51, + year: 2000, + state: 'SENDED' + }; + const ctx = {args}; + + try { + const options = {transaction: tx}; + const beforeMail = await models.WorkerTimeControlMail.find({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + const afterMail = await models.WorkerTimeControlMail.find({ + where: { + workerFk: args.workerId, + year: args.year, + week: args.week, + } + }, options); + + expect(beforeMail).toEqual([]); + expect(afterMail.length).toEqual(1); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw error if not exist any record in this week', async() => { + const tx = await models.WorkerTimeControlMail.beginTransaction({}); + const ctx = {args: { + workerId: 1, + week: 1, + year: 0, + state: 'SENDED' + }}; + + let error; + try { + const options = {transaction: tx}; + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + error = e; + } + + expect(error.message).toEqual(`There aren't records for this week`); + }); +}); + diff --git a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js index 6fe30de91..3594f05fe 100644 --- a/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js +++ b/modules/worker/back/methods/worker-time-control/updateWorkerTimeControlMail.js @@ -40,30 +40,39 @@ module.exports = Self => { Self.updateWorkerTimeControlMail = async(ctx, options) => { const models = Self.app.models; const args = ctx.args; - const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); - const workerTimeControlMail = await models.WorkerTimeControlMail.findOne({ + const [sent] = await models.WorkerTimeControlMail.find({ where: { - workerFk: args.workerId, year: args.year, - week: args.week - } + week: args.week, + }, + limit: 1 }, myOptions); - if (!workerTimeControlMail) throw new UserError(`There aren't records for this week`); + if (!sent) throw new UserError(`There aren't records for this week`); - await workerTimeControlMail.updateAttributes({ - state: args.state, - reason: args.reason || null - }, myOptions); + const workerTimeControlMail = await models.WorkerTimeControlMail.upsertWithWhere( + { + year: args.year, + week: args.week, + workerFk: args.workerId + }, + { + state: args.state, + reason: args.workerId, + year: args.year, + week: args.week, + workerFk: args.workerId + }, + myOptions); if (args.state == 'SENDED') { await workerTimeControlMail.updateAttributes({ - sendedCounter: workerTimeControlMail.sendedCounter + 1 + sendedCounter: workerTimeControlMail.sendedCounter ? workerTimeControlMail.sendedCounter + 1 : 1 }, myOptions); } }; diff --git a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js index 3203dea82..816a1d22b 100644 --- a/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js +++ b/modules/worker/back/methods/worker-time-control/weeklyHourRecordEmail.js @@ -61,9 +61,8 @@ module.exports = Self => { const url = `${salix.url}worker/${args.workerId}/time-control?timestamp=${timestamp}`; ctx.args.url = url; - await Self.sendTemplate(ctx, 'weekly-hour-record'); - - return models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, myOptions); + await models.WorkerTimeControl.updateWorkerTimeControlMail(ctx, myOptions); + return Self.sendTemplate(ctx, 'weekly-hour-record'); }; function getMondayDateFromYearWeek(yearNumber, weekNumber) { diff --git a/modules/worker/back/methods/worker/activeWithInheritedRole.js b/modules/worker/back/methods/worker/activeWithInheritedRole.js index 19038405b..9bd02fec8 100644 --- a/modules/worker/back/methods/worker/activeWithInheritedRole.js +++ b/modules/worker/back/methods/worker/activeWithInheritedRole.js @@ -23,7 +23,7 @@ module.exports = Self => { const query = `SELECT DISTINCT w.id, w.firstName, w.lastName, u.name, u.nickname FROM worker w - JOIN account.user u ON u.id = w.userFk + JOIN account.user u ON u.id = w.id JOIN account.roleRole i ON i.role = u.role JOIN account.role r ON r.id = i.inheritsFrom`; diff --git a/modules/worker/back/methods/worker/createAbsence.js b/modules/worker/back/methods/worker/createAbsence.js index cb2cf8330..d628d0a2b 100644 --- a/modules/worker/back/methods/worker/createAbsence.js +++ b/modules/worker/back/methods/worker/createAbsence.js @@ -109,13 +109,13 @@ module.exports = Self => { const absenceType = await models.AbsenceType.findById(args.absenceTypeId, null, myOptions); const account = await models.VnUser.findById(userId, null, myOptions); const subordinated = await models.VnUser.findById(id, null, myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const body = $t('Created absence', { author: account.nickname, employee: subordinated.nickname, absenceType: absenceType.name, dated: formatDate(args.dated), - workerUrl: `${origin}/#!/worker/${id}/calendar` + workerUrl: `${url}worker/${id}/calendar` }); await models.Mail.create({ subject: $t('Absence change notification on the labour calendar'), diff --git a/modules/worker/back/methods/worker/deleteAbsence.js b/modules/worker/back/methods/worker/deleteAbsence.js index c315f5178..b71d077a4 100644 --- a/modules/worker/back/methods/worker/deleteAbsence.js +++ b/modules/worker/back/methods/worker/deleteAbsence.js @@ -60,13 +60,13 @@ module.exports = Self => { const absenceType = await models.AbsenceType.findById(absence.dayOffTypeFk, null, myOptions); const account = await models.VnUser.findById(userId, null, myOptions); const subordinated = await models.VnUser.findById(labour.workerFk, null, myOptions); - const origin = ctx.req.headers.origin; + const url = await Self.app.models.Url.getUrl(); const body = $t('Deleted absence', { author: account.nickname, employee: subordinated.nickname, absenceType: absenceType.name, dated: formatDate(absence.dated), - workerUrl: `${origin}/#!/worker/${id}/calendar` + workerUrl: `${url}worker/${id}/calendar` }); await models.Mail.create({ subject: $t('Absence change notification on the labour calendar'), diff --git a/modules/worker/back/methods/worker/filter.js b/modules/worker/back/methods/worker/filter.js index 71a8da96f..2f328d28f 100644 --- a/modules/worker/back/methods/worker/filter.js +++ b/modules/worker/back/methods/worker/filter.js @@ -95,8 +95,6 @@ module.exports = Self => { ]}; case 'id': return {'w.id': value}; - case 'userFk': - return {'w.userFk': value}; case 'firstName': return {'w.firstName': {like: `%${value}%`}}; case 'lastName': @@ -123,8 +121,8 @@ module.exports = Self => { FROM worker w LEFT JOIN workerDepartment wd ON wd.workerFk = w.id LEFT JOIN department d ON d.id = wd.departmentFk - LEFT JOIN client c ON c.id = w.userFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN client c ON c.id = w.id + LEFT JOIN account.user u ON u.id = w.id LEFT JOIN pbx.sip p ON p.user_id = u.id LEFT JOIN account.emailUser mu ON mu.userFk = u.id` ); diff --git a/modules/worker/back/methods/worker/getWorkedHours.js b/modules/worker/back/methods/worker/getWorkedHours.js index 44f3eca3a..cac74a416 100644 --- a/modules/worker/back/methods/worker/getWorkedHours.js +++ b/modules/worker/back/methods/worker/getWorkedHours.js @@ -38,12 +38,12 @@ module.exports = Self => { const conn = Self.dataSource.connector; const worker = await models.Worker.findById(id); - const userId = worker.userFk; + const userId = worker.id; const stmts = []; stmts.push(` - DROP TEMPORARY TABLE IF EXISTS + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate, tmp.timeBusinessCalculate `); @@ -54,7 +54,7 @@ module.exports = Self => { const resultIndex = stmts.push(new ParameterizedSQL(` SELECT tcc.dated, tbc.timeWorkSeconds expectedHours, tcc.timeWorkSeconds workedHours - FROM tmp.timeControlCalculate tcc + FROM tmp.timeControlCalculate tcc LEFT JOIN tmp.timeBusinessCalculate tbc ON tcc.dated = tbc.dated WHERE tcc.dated BETWEEN DATE(?) AND DATE(?) `, [started, ended])) - 1; diff --git a/modules/worker/back/methods/worker/new.js b/modules/worker/back/methods/worker/new.js index 199a3be62..5316daf01 100644 --- a/modules/worker/back/methods/worker/new.js +++ b/modules/worker/back/methods/worker/new.js @@ -223,19 +223,16 @@ module.exports = Self => { const user = await models.VnUser.findById(client.id, null, myOptions); await user.updateAttribute('email', args.email, myOptions); - await models.Worker.rawSql( - 'CALL vn.workerCreate(?, ?, ?, ?, ?, ?, ?)', - [ - args.firstName, - args.lastNames, - args.code, - args.bossFk, - client.id, - args.fi, - args.birth, - ], - myOptions - ); + await models.Worker.create({ + id: client.id, + code: args.code, + firstName: args.firstName, + lastName: args.lastNames, + bossFk: args.bossFk, + fi: args.fi, + birth: args.birth, + + }, myOptions); if (tx) await tx.commit(); } catch (error) { diff --git a/modules/worker/back/methods/worker/search.js b/modules/worker/back/methods/worker/search.js index cd0a466ea..7fe9e0666 100644 --- a/modules/worker/back/methods/worker/search.js +++ b/modules/worker/back/methods/worker/search.js @@ -46,7 +46,7 @@ module.exports = Self => { SELECT DISTINCT w.id, w.code, u.name, u.nickname, u.active, b.departmentFk FROM worker w JOIN account.user u ON u.id = w.id - JOIN business b ON b.workerFk = w.id + LEFT JOIN business b ON b.workerFk = w.id ) w`); stmt.merge(conn.makeSuffix(filter)); diff --git a/modules/worker/back/methods/worker/setPassword.js b/modules/worker/back/methods/worker/setPassword.js new file mode 100644 index 000000000..43d3d946f --- /dev/null +++ b/modules/worker/back/methods/worker/setPassword.js @@ -0,0 +1,48 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('setPassword', { + description: 'Set a new password', + accepts: [ + { + arg: 'workerFk', + type: 'number', + required: true, + description: 'The worker id', + }, + { + arg: 'newPass', + type: 'String', + required: true, + description: 'The new worker password' + } + ], + http: { + path: `/:id/setPassword`, + verb: 'PATCH' + } + }); + Self.setPassword = async(ctx, options) => { + const models = Self.app.models; + const myOptions = {}; + const {args} = ctx; + let tx; + if (typeof options == 'object') + Object.assign(myOptions, options); + if (!myOptions.transaction) { + tx = await Self.beginTransaction({}); + myOptions.transaction = tx; + } + try { + const isSubordinate = await models.Worker.isSubordinate(ctx, args.workerFk, myOptions); + if (!isSubordinate) throw new UserError('You don\'t have enough privileges.'); + + await models.VnUser.setPassword(args.workerFk, args.newPass, myOptions); + await models.VnUser.updateAll({id: args.workerFk}, {emailVerified: true}, myOptions); + + if (tx) await tx.commit(); + } catch (e) { + if (tx) await tx.rollback(); + throw e; + } + }; +}; diff --git a/modules/worker/back/methods/worker/specs/setPassword.spec.js b/modules/worker/back/methods/worker/specs/setPassword.spec.js new file mode 100644 index 000000000..fbb403b24 --- /dev/null +++ b/modules/worker/back/methods/worker/specs/setPassword.spec.js @@ -0,0 +1,61 @@ +const UserError = require('vn-loopback/util/user-error'); + +const models = require('vn-loopback/server/server').models; + +describe('worker setPassword()', () => { + let ctx; + beforeAll(() => { + ctx = { + req: { + accessToken: {}, + headers: {origin: 'http://localhost'} + }, + args: {workerFk: 9} + }; + }); + + beforeEach(() => { + ctx.req.accessToken.userId = 20; + ctx.args.newPass = 'H3rn4d3z#'; + }); + + it('should change the password', async() => { + const tx = await models.Worker.beginTransaction({}); + + try { + const options = {transaction: tx}; + await models.Worker.setPassword(ctx, options); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('should throw an error: Password does not meet requirements', async() => { + const tx = await models.Collection.beginTransaction({}); + ctx.args.newPass = 'Hi'; + try { + const options = {transaction: tx}; + await models.Worker.setPassword(ctx, options); + await tx.rollback(); + } catch (e) { + expect(e.sqlMessage).toEqual('Password does not meet requirements'); + await tx.rollback(); + } + }); + + it('should throw an error: You don\'t have enough privileges.', async() => { + ctx.req.accessToken.userId = 5; + const tx = await models.Collection.beginTransaction({}); + try { + const options = {transaction: tx}; + await models.Worker.setPassword(ctx, options); + await tx.rollback(); + } catch (e) { + expect(e).toEqual(new UserError(`You don't have enough privileges.`)); + await tx.rollback(); + } + }); +}); diff --git a/modules/worker/back/model-config.json b/modules/worker/back/model-config.json index b261f895e..8352eb070 100644 --- a/modules/worker/back/model-config.json +++ b/modules/worker/back/model-config.json @@ -43,6 +43,9 @@ }, "EducationLevel": { "dataSource": "vn" + }, + "MistakeType": { + "dataSource": "vn" }, "ProfileType":{ "dataSource": "vn" @@ -83,6 +86,12 @@ "WorkerMana": { "dataSource": "vn" }, + "WorkerMistake": { + "dataSource": "vn" + }, + "WorkerMistakeType": { + "dataSource": "vn" + }, "WorkerMedia": { "dataSource": "vn" }, diff --git a/modules/worker/back/models/device-log.json b/modules/worker/back/models/device-log.json index 9278b9038..2b55e9474 100644 --- a/modules/worker/back/models/device-log.json +++ b/modules/worker/back/models/device-log.json @@ -28,6 +28,9 @@ }, "deviceProductionFk": { "type": "number" + }, + "serialNumber": { + "type": "string" } }, "relations": { diff --git a/modules/worker/back/models/mistakeType.json b/modules/worker/back/models/mistakeType.json new file mode 100644 index 000000000..e999b3e28 --- /dev/null +++ b/modules/worker/back/models/mistakeType.json @@ -0,0 +1,20 @@ +{ + "name": "MistakeType", + "base": "VnModel", + "options": { + "mysql": { + "table": "mistakeType" + } + }, + "properties": { + "id": { + "id":true, + "type": "number" + }, + "description": { + "type": "string" + } + + } + } + \ No newline at end of file diff --git a/modules/worker/back/models/operator.json b/modules/worker/back/models/operator.json index 2417078e1..6da3945fc 100644 --- a/modules/worker/back/models/operator.json +++ b/modules/worker/back/models/operator.json @@ -33,6 +33,16 @@ "type": "belongsTo", "model": "Sector", "foreignKey": "sectorFk" + }, + "train": { + "type": "belongsTo", + "model": "Train", + "foreignKey": "trainFk" + }, + "printer": { + "type": "belongsTo", + "model": "Printer", + "foreignKey": "labelerFk" } } } diff --git a/modules/worker/back/models/worker-mana.js b/modules/worker/back/models/worker-mana.js deleted file mode 100644 index 99a0f7694..000000000 --- a/modules/worker/back/models/worker-mana.js +++ /dev/null @@ -1,3 +0,0 @@ -module.exports = Self => { - require('../methods/worker-mana/getCurrentWorkerMana')(Self); -}; diff --git a/modules/worker/back/models/worker-time-control.json b/modules/worker/back/models/worker-time-control.json index b045946e7..c40989d84 100644 --- a/modules/worker/back/models/worker-time-control.json +++ b/modules/worker/back/models/worker-time-control.json @@ -36,7 +36,7 @@ "worker": { "type": "hasOne", "model": "Worker", - "foreignKey": "userFk" + "foreignKey": "id" }, "warehouse": { "type": "belongsTo", diff --git a/modules/worker/back/models/worker.js b/modules/worker/back/models/worker.js index ccae3a6e6..985d83e9f 100644 --- a/modules/worker/back/models/worker.js +++ b/modules/worker/back/models/worker.js @@ -18,6 +18,7 @@ module.exports = Self => { require('../methods/worker/allocatePDA')(Self); require('../methods/worker/search')(Self); require('../methods/worker/isAuthorized')(Self); + require('../methods/worker/setPassword')(Self); Self.validatesUniquenessOf('locker', { message: 'This locker has already been assigned' diff --git a/modules/worker/back/models/worker.json b/modules/worker/back/models/worker.json index 6e1371055..1a777fffe 100644 --- a/modules/worker/back/models/worker.json +++ b/modules/worker/back/models/worker.json @@ -24,9 +24,6 @@ "phone": { "type" : "string" }, - "userFk": { - "type" : "number" - }, "bossFk": { "type" : "number" }, @@ -50,6 +47,15 @@ }, "locker": { "type" : "number" + }, + "fi": { + "type" : "string" + }, + "birth": { + "type" : "date" + }, + "isF11Allowed": { + "type" : "boolean" } }, "relations": { @@ -66,12 +72,12 @@ "client": { "type": "belongsTo", "model": "Client", - "foreignKey": "userFk" + "foreignKey": "id" }, "sip": { "type": "belongsTo", "model": "Sip", - "foreignKey": "userFk" + "foreignKey": "id" }, "department": { "type": "belongsTo", diff --git a/modules/worker/back/models/workerMistake.json b/modules/worker/back/models/workerMistake.json new file mode 100644 index 000000000..00978761e --- /dev/null +++ b/modules/worker/back/models/workerMistake.json @@ -0,0 +1,25 @@ +{ + "name": "WorkerMistake", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerMistake" + } + }, + "properties": { + "id": { + "id":true, + "type": "number" + }, + "userFk": { + "type": "number" + }, + "workerMistakeTypeFk": { + "type": "string" + }, + "created": { + "type": "date" + } + } + } + \ No newline at end of file diff --git a/modules/worker/back/models/workerMistakeType.json b/modules/worker/back/models/workerMistakeType.json new file mode 100644 index 000000000..c5e6e6383 --- /dev/null +++ b/modules/worker/back/models/workerMistakeType.json @@ -0,0 +1,26 @@ +{ + "name": "WorkerMistakeType", + "base": "VnModel", + "options": { + "mysql": { + "table": "workerMistakeType" + } + }, + "properties": { + "code": { + "id":true, + "type": "string" + }, + "description": { + "type": "string" + } + }, + "relations": { + "type": { + "type": "belongsTo", + "model": "WorkerMistakeType", + "foreignKey": "code" + } + } + } + \ No newline at end of file diff --git a/modules/worker/front/card/index.js b/modules/worker/front/card/index.js index b8b533c5d..9a40e31c2 100644 --- a/modules/worker/front/card/index.js +++ b/modules/worker/front/card/index.js @@ -8,7 +8,7 @@ class Controller extends ModuleCard { { relation: 'user', scope: { - fields: ['name'], + fields: ['name', 'emailVerified'], include: { relation: 'emailUser', scope: { diff --git a/modules/worker/front/create/index.html b/modules/worker/front/create/index.html index dd3e0b4a9..39b2dbf47 100644 --- a/modules/worker/front/create/index.html +++ b/modules/worker/front/create/index.html @@ -72,7 +72,7 @@ icon="add_circle" vn-tooltip="New postcode" ng-click="postcode.open()" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" vn-acl-action="remove"> diff --git a/modules/worker/front/descriptor/index.html b/modules/worker/front/descriptor/index.html index ea005e1a2..aa6b80300 100644 --- a/modules/worker/front/descriptor/index.html +++ b/modules/worker/front/descriptor/index.html @@ -3,16 +3,7 @@ description="$ctrl.worker.firstName +' '+ $ctrl.worker.lastName" summary="$ctrl.$.summary"> -
- - - -
+
@@ -20,6 +11,9 @@ ? 'Click to allow the user to be disabled' : 'Click to exclude the user from getting disabled'}} + + Change password +
@@ -37,11 +31,17 @@ + > + + > +
@@ -75,9 +75,29 @@ - - - - + + + + + + + + + + + + diff --git a/modules/worker/front/descriptor/index.js b/modules/worker/front/descriptor/index.js index a53528ef2..13ffa6f2f 100644 --- a/modules/worker/front/descriptor/index.js +++ b/modules/worker/front/descriptor/index.js @@ -1,6 +1,6 @@ import ngModule from '../module'; import Descriptor from 'salix/components/descriptor'; - +const UserError = require('vn-loopback/util/user-error'); class Controller extends Descriptor { constructor($element, $, $rootScope) { super($element, $); @@ -13,9 +13,11 @@ class Controller extends Descriptor { set worker(value) { this.entity = value; - if (value) this.getIsExcluded(); + + if (this.entity && !this.entity.user.emailVerified) + this.getPassRequirements(); } getIsExcluded() { @@ -39,7 +41,7 @@ class Controller extends Descriptor { { relation: 'user', scope: { - fields: ['name'], + fields: ['name', 'emailVerified'], include: { relation: 'emailUser', scope: { @@ -67,20 +69,28 @@ class Controller extends Descriptor { } ] }; - return this.getData(`Workers/${this.id}`, {filter}) .then(res => this.entity = res.data); } - onUploadResponse() { - const timestamp = Date.vnNew().getTime(); - const src = this.$rootScope.imagePath('user', '520x520', this.worker.id); - const zoomSrc = this.$rootScope.imagePath('user', '1600x1600', this.worker.id); - const newSrc = `${src}&t=${timestamp}`; - const newZoomSrc = `${zoomSrc}&t=${timestamp}`; + getPassRequirements() { + this.$http.get('UserPasswords/findOne') + .then(res => { + this.passRequirements = res.data; + }); + } - this.$.photo.setAttribute('src', newSrc); - this.$.photo.setAttribute('zoom-image', newZoomSrc); + setPassword() { + if (!this.newPassword) + throw new UserError(`You must enter a new password`); + if (this.newPassword != this.repeatPassword) + throw new UserError(`Passwords don't match`); + this.$http.patch( + `Workers/${this.entity.id}/setPassword`, + {workerFk: this.entity.id, newPass: this.newPassword} + ) .then(() => { + this.vnApp.showSuccess(this.$translate.instant('Password changed!')); + }); } } diff --git a/modules/worker/front/descriptor/index.spec.js b/modules/worker/front/descriptor/index.spec.js index dfb800415..d158a9e8e 100644 --- a/modules/worker/front/descriptor/index.spec.js +++ b/modules/worker/front/descriptor/index.spec.js @@ -23,4 +23,24 @@ describe('vnWorkerDescriptor', () => { expect(controller.worker).toEqual(response); }); }); + + describe('setPassword()', () => { + it('should throw an error: You must enter a new password', () => { + try { + controller.setPassword(); + } catch (error) { + expect(error.message).toEqual('You must enter a new password'); + } + }); + + it('should throw an error: Passwords don\'t match', () => { + controller.newPassword = 'aaa'; + controller.repeatPassword = 'bbb'; + try { + controller.setPassword(); + } catch (error) { + expect(error.message).toEqual('Passwords don\'t match'); + } + }); + }); }); diff --git a/modules/worker/front/search-panel/index.html b/modules/worker/front/search-panel/index.html index 2adb56587..c93eef78b 100644 --- a/modules/worker/front/search-panel/index.html +++ b/modules/worker/front/search-panel/index.html @@ -18,7 +18,7 @@ + ng-model="filter.id"> @@ -64,4 +64,4 @@ -
\ No newline at end of file +
diff --git a/modules/worker/front/summary/index.html b/modules/worker/front/summary/index.html index 2607d9b2f..2372634bc 100644 --- a/modules/worker/front/summary/index.html +++ b/modules/worker/front/summary/index.html @@ -42,14 +42,21 @@ {{::worker.boss.name}}
- + + - + + + > + @@ -58,7 +65,7 @@

User data

+ value="{{worker.id}}"> diff --git a/modules/worker/front/summary/index.js b/modules/worker/front/summary/index.js index 2bb1f0853..212609f58 100644 --- a/modules/worker/front/summary/index.js +++ b/modules/worker/front/summary/index.js @@ -1,6 +1,5 @@ import ngModule from '../module'; import Summary from 'salix/components/summary'; - class Controller extends Summary { get worker() { return this._worker; diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index b77acbddc..c34a1e3ca 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -79,30 +79,32 @@ - + +
+ + + + + + +
- - - - - - + vn-tooltip="{{$ctrl.state ? 'Resend' : 'Send'}} email of this week to the user" + ng-if="$ctrl.isHr && $ctrl.state != 'CONFIRMED' && $ctrl.canResend">
diff --git a/modules/worker/front/time-control/index.js b/modules/worker/front/time-control/index.js index 38e6721d6..0a955c586 100644 --- a/modules/worker/front/time-control/index.js +++ b/modules/worker/front/time-control/index.js @@ -52,6 +52,30 @@ class Controller extends Section { set worker(value) { this._worker = value; + this.fetchHours(); + if (this.date) + this.getWeekData(); + } + + /** + * Worker hours data + */ + get hours() { + return this._hours; + } + + set hours(value) { + this._hours = value; + + for (const weekDay of this.weekDays) { + if (value) { + let day = weekDay.dated.getDay(); + weekDay.hours = value + .filter(hour => new Date(hour.timed).getDay() == day) + .sort((a, b) => new Date(a.timed) - new Date(b.timed)); + } else + weekDay.hours = null; + } } /** @@ -87,8 +111,18 @@ class Controller extends Section { dayIndex.setDate(dayIndex.getDate() + 1); } - this.fetchHours(); - this.getWeekData(); + if (this.worker) { + this.fetchHours(); + this.getWeekData(); + } + } + + set weekTotalHours(totalHours) { + this._weekTotalHours = this.formatHours(totalHours); + } + + get weekTotalHours() { + return this._weekTotalHours; } getWeekData() { @@ -97,42 +131,40 @@ class Controller extends Section { workerFk: this.$params.id, year: this._date.getFullYear(), week: this.getWeekNumber(this._date) - } + }, }; this.$http.get('WorkerTimeControlMails', {filter}) .then(res => { - const workerTimeControlMail = res.data; - if (!workerTimeControlMail.length) { + if (!res.data.length) { this.state = null; return; } - this.state = workerTimeControlMail[0].state; - this.reason = workerTimeControlMail[0].reason; + const [mail] = res.data; + this.state = mail.state; + this.reason = mail.reason; + }); + this.canBeResend(); + } + + canBeResend() { + this.canResend = false; + const filter = { + where: { + year: this._date.getFullYear(), + week: this.getWeekNumber(this._date) + }, + limit: 1 + }; + this.$http.get('WorkerTimeControlMails', {filter}) + .then(res => { + if (res.data.length) + this.canResend = true; }); } - /** - * Worker hours data - */ - get hours() { - return this._hours; - } - - set hours(value) { - this._hours = value; - - for (const weekDay of this.weekDays) { - if (value) { - let day = weekDay.dated.getDay(); - weekDay.hours = value - .filter(hour => new Date(hour.timed).getDay() == day) - .sort((a, b) => new Date(a.timed) - new Date(b.timed)); - } else - weekDay.hours = null; - } - } - fetchHours() { + if (!this.worker || !this.date) return; + const params = {workerFk: this.$params.id}; const filter = { where: {and: [ @@ -148,58 +180,6 @@ class Controller extends Section { }); } - hasEvents(day) { - return day >= this.started && day < this.ended; - } - - getAbsences() { - const fullYear = this.started.getFullYear(); - let params = { - workerFk: this.$params.id, - businessFk: null, - year: fullYear - }; - - return this.$http.get(`Calendars/absences`, {params}) - .then(res => this.onData(res.data)); - } - - onData(data) { - const events = {}; - - const addEvent = (day, event) => { - events[new Date(day).getTime()] = event; - }; - - if (data.holidays) { - data.holidays.forEach(holiday => { - const holidayDetail = holiday.detail && holiday.detail.description; - const holidayType = holiday.type && holiday.type.name; - const holidayName = holidayDetail || holidayType; - - addEvent(holiday.dated, { - name: holidayName, - color: '#ff0' - }); - }); - } - if (data.absences) { - data.absences.forEach(absence => { - const type = absence.absenceType; - addEvent(absence.dated, { - name: type.name, - color: type.rgb - }); - }); - } - - this.weekDays.forEach(day => { - const timestamp = day.dated.getTime(); - if (events[timestamp]) - day.event = events[timestamp]; - }); - } - getWorkedHours(from, to) { this.weekTotalHours = null; let weekTotalHours = 0; @@ -239,6 +219,58 @@ class Controller extends Section { }); } + getAbsences() { + const fullYear = this.started.getFullYear(); + let params = { + workerFk: this.$params.id, + businessFk: null, + year: fullYear + }; + + return this.$http.get(`Calendars/absences`, {params}) + .then(res => this.onData(res.data)); + } + + hasEvents(day) { + return day >= this.started && day < this.ended; + } + + onData(data) { + const events = {}; + + const addEvent = (day, event) => { + events[new Date(day).getTime()] = event; + }; + + if (data.holidays) { + data.holidays.forEach(holiday => { + const holidayDetail = holiday.detail && holiday.detail.description; + const holidayType = holiday.type && holiday.type.name; + const holidayName = holidayDetail || holidayType; + + addEvent(holiday.dated, { + name: holidayName, + color: '#ff0' + }); + }); + } + if (data.absences) { + data.absences.forEach(absence => { + const type = absence.absenceType; + addEvent(absence.dated, { + name: type.name, + color: type.rgb + }); + }); + } + + this.weekDays.forEach(day => { + const timestamp = day.dated.getTime(); + if (events[timestamp]) + day.event = events[timestamp]; + }); + } + getFinishTime() { if (!this.weekDays) return; @@ -267,14 +299,6 @@ class Controller extends Section { } } - set weekTotalHours(totalHours) { - this._weekTotalHours = this.formatHours(totalHours); - } - - get weekTotalHours() { - return this._weekTotalHours; - } - formatHours(timestamp = 0) { let hour = Math.floor(timestamp / 3600); let min = Math.floor(timestamp / 60 - 60 * hour); @@ -353,30 +377,25 @@ class Controller extends Section { } isSatisfied() { - const params = { - workerId: this.worker.id, - year: this.date.getFullYear(), - week: this.weekNumber, - state: 'CONFIRMED' - }; - const query = `WorkerTimeControls/updateWorkerTimeControlMail`; - this.$http.post(query, params).then(() => { - this.getMailStates(this.date); - this.getWeekData(); - this.vnApp.showSuccess(this.$t('Data saved!')); - }); + this.updateWorkerTimeControlMail('CONFIRMED'); } isUnsatisfied() { if (!this.reason) throw new UserError(`You must indicate a reason`); + this.updateWorkerTimeControlMail('REVISE', this.reason); + } + updateWorkerTimeControlMail(state, reason) { const params = { workerId: this.worker.id, year: this.date.getFullYear(), week: this.weekNumber, - state: 'REVISE', - reason: this.reason + state }; + + if (reason) + params.reason = reason; + const query = `WorkerTimeControls/updateWorkerTimeControlMail`; this.$http.post(query, params).then(() => { this.getMailStates(this.date); @@ -385,7 +404,7 @@ class Controller extends Section { }); } - changeState(state, reason) { + state(state, reason) { this.state = state; this.reason = reason; this.repaint(); diff --git a/modules/worker/front/time-control/index.spec.js b/modules/worker/front/time-control/index.spec.js index 6d8510ba8..10e8aba0d 100644 --- a/modules/worker/front/time-control/index.spec.js +++ b/modules/worker/front/time-control/index.spec.js @@ -22,7 +22,7 @@ describe('Component vnWorkerTimeControl', () => { })); describe('date() setter', () => { - it(`should set the weekDays, the date in the controller and call fetchHours`, () => { + it(`should set the weekDays and the date in the controller`, () => { let today = Date.vnNew(); jest.spyOn(controller, 'fetchHours').mockReturnThis(); @@ -32,7 +32,6 @@ describe('Component vnWorkerTimeControl', () => { expect(controller.started).toBeDefined(); expect(controller.ended).toBeDefined(); expect(controller.weekDays.length).toEqual(7); - expect(controller.fetchHours).toHaveBeenCalledWith(); }); }); diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index bcfb91e3d..13d45428c 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -54,7 +54,7 @@ module.exports = Self => { const ticketList = await models.Ticket.find(filter, myOptions); const fixingState = await models.State.findOne({where: {code: 'FIXING'}}, myOptions); const worker = await models.Worker.findOne({ - where: {userFk: userId} + where: {id: userId} }, myOptions); await models.Ticket.rawSql('UPDATE ticket SET zoneFk = NULL WHERE zoneFk = ?', [id], myOptions); diff --git a/modules/zone/back/methods/zone/toggleIsIncluded.js b/modules/zone/back/methods/zone/toggleIsIncluded.js index bf8c86f46..98c64c4a0 100644 --- a/modules/zone/back/methods/zone/toggleIsIncluded.js +++ b/modules/zone/back/methods/zone/toggleIsIncluded.js @@ -30,18 +30,21 @@ module.exports = Self => { Self.toggleIsIncluded = async(id, geoId, isIncluded, options) => { const models = Self.app.models; const myOptions = {}; - if (typeof options == 'object') Object.assign(myOptions, options); if (isIncluded === undefined) return models.ZoneIncluded.destroyAll({zoneFk: id, geoFk: geoId}, myOptions); - else { - return models.ZoneIncluded.upsert({ - zoneFk: id, - geoFk: geoId, - isIncluded: isIncluded - }, myOptions); - } + + const zoneIncluded = await models.ZoneIncluded.findOne({where: {zoneFk: id, geoFk: geoId}}, myOptions); + + if (zoneIncluded) + return zoneIncluded.updateAttribute('isIncluded', isIncluded, myOptions); + + return models.ZoneIncluded.create({ + zoneFk: id, + geoFk: geoId, + isIncluded: isIncluded + }, myOptions); }; }; diff --git a/modules/zone/back/models/zone-included.json b/modules/zone/back/models/zone-included.json index 61633a3c7..deba73f34 100644 --- a/modules/zone/back/models/zone-included.json +++ b/modules/zone/back/models/zone-included.json @@ -7,8 +7,8 @@ } }, "properties": { - "zoneFk": { - "id": true, + "id": { + "id": true, "type": "number" }, "isIncluded": { diff --git a/modules/zone/front/basic-data/index.html b/modules/zone/front/basic-data/index.html index 8d8fc6c56..5070a3aea 100644 --- a/modules/zone/front/basic-data/index.html +++ b/modules/zone/front/basic-data/index.html @@ -12,9 +12,9 @@ @@ -26,7 +26,7 @@ show-field="name" value-field="id" label="Agency" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" rule>
@@ -52,13 +52,13 @@ ng-model="$ctrl.zone.travelingDays" min="0" step="1" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" rule> @@ -68,16 +68,16 @@ ng-model="$ctrl.zone.price" min="0" step="0.01" - vn-acl="deliveryBoss" + vn-acl="deliveryAssistant" rule> - + @@ -101,7 +101,7 @@ - diff --git a/modules/zone/front/location/index.html b/modules/zone/front/location/index.html index a9e9261a8..b86c618b7 100644 --- a/modules/zone/front/location/index.html +++ b/modules/zone/front/location/index.html @@ -16,12 +16,12 @@ root-label="Locations" fetch-func="$ctrl.onFetch($item)" sort-func="$ctrl.onSort($a, $b)"> - + label="{{::item.name}}"> diff --git a/package-lock.json b/package-lock.json index 10b5e6b02..b66279ae3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "salix-back", - "version": "23.32.02", + "version": "23.48.01", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "salix-back", - "version": "23.26.01", + "version": "23.48.01", "license": "GPL-3.0", "dependencies": { "axios": "^1.2.2", diff --git a/package.json b/package.json index d250071a6..04fcb008b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "salix-back", - "version": "23.40.01", + "version": "23.48.01", "author": "Verdnatura Levante SL", "description": "Salix backend", "license": "GPL-3.0", diff --git a/print/templates/email/client-welcome/sql/client.sql b/print/templates/email/client-welcome/sql/client.sql index 49e1d4bf6..59bdeae4a 100644 --- a/print/templates/email/client-welcome/sql/client.sql +++ b/print/templates/email/client-welcome/sql/client.sql @@ -7,5 +7,5 @@ SELECT FROM client c JOIN account.user u ON u.id = c.id LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.userFk -WHERE c.id = ? \ No newline at end of file + LEFT JOIN account.user wu ON wu.id = w.id +WHERE c.id = ? diff --git a/print/templates/email/incoterms-authorization/incoterms-authorization.js b/print/templates/email/incoterms-authorization/incoterms-authorization.js index cb3cebc09..9e98f60a9 100755 --- a/print/templates/email/incoterms-authorization/incoterms-authorization.js +++ b/print/templates/email/incoterms-authorization/incoterms-authorization.js @@ -28,6 +28,10 @@ module.exports = { companyId: { type: Number, required: true + }, + addressId: { + type: Number, + required: true } } }; diff --git a/print/templates/email/modified-collection-volumetry/assets/css/import.js b/print/templates/email/modified-collection-volumetry/assets/css/import.js new file mode 100644 index 000000000..fec23d870 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/assets/css/import.js @@ -0,0 +1,12 @@ +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`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/templates/email/modified-collection-volumetry/assets/css/style.css b/print/templates/email/modified-collection-volumetry/assets/css/style.css new file mode 100644 index 000000000..5e006baa2 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/assets/css/style.css @@ -0,0 +1,8 @@ +.jsonSection { + text-align: left; + background-color: #e4e4e4; + padding: 25px; + margin-left: 60px; + margin-right: 60px; + border-radius: 25px; +} \ No newline at end of file diff --git a/print/templates/email/modified-collection-volumetry/locale/en.yml b/print/templates/email/modified-collection-volumetry/locale/en.yml new file mode 100644 index 000000000..d29b5b8de --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/locale/en.yml @@ -0,0 +1,3 @@ +subject: Modified collection volumetry +title: Modified collection volumetry +description: Action performed \ No newline at end of file diff --git a/print/templates/email/modified-collection-volumetry/locale/es.yml b/print/templates/email/modified-collection-volumetry/locale/es.yml new file mode 100644 index 000000000..c271183b5 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/locale/es.yml @@ -0,0 +1,3 @@ +subject: Volumetría de colección modificada +title: Volumetría de colección modificada +description: Acción realizada \ No newline at end of file diff --git a/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html new file mode 100644 index 000000000..32ad19fd4 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.html @@ -0,0 +1,15 @@ + +
+
+
+

{{ $t('title') }}

+

{{ $t('description') }}: {{ data.action }} {{ `(${this.username})` }}

+
+ + {{ `${key}:` }} {{ value }}
+
+
+
+
+
+
diff --git a/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js new file mode 100755 index 000000000..4345ead47 --- /dev/null +++ b/print/templates/email/modified-collection-volumetry/modified-collection-volumetry.js @@ -0,0 +1,25 @@ +const Component = require(`vn-print/core/component`); +const emailBody = new Component('email-body'); +const models = require('vn-loopback/server/server').models; + +module.exports = { + name: 'modified-collection-volumetry', + components: { + 'email-body': emailBody.build(), + }, + async serverPrefetch() { + this.username = (this.data.userFk) ? await this.getUsername(this.data.userFk) : 'system'; + }, + methods: { + async getUsername(id) { + const account = await models.VnUser.findById(id); + return account.name; + } + }, + props: { + data: { + type: Object, + required: true + } + } +}; diff --git a/print/templates/email/printer-setup/sql/client.sql b/print/templates/email/printer-setup/sql/client.sql index 2a8a751e0..31454408f 100644 --- a/print/templates/email/printer-setup/sql/client.sql +++ b/print/templates/email/printer-setup/sql/client.sql @@ -8,5 +8,5 @@ SELECT FROM client c JOIN account.user u ON u.id = c.id LEFT JOIN worker w ON w.id = c.salesPersonFk - LEFT JOIN account.user wu ON wu.id = w.userFk -WHERE c.id = ? \ No newline at end of file + LEFT JOIN account.user wu ON wu.id = w.id +WHERE c.id = ? diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 0be5a30f0..92dd1b126 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -117,7 +117,7 @@ {{service.price | currency('EUR', $i18n.locale)}} {{service.taxDescription}} - {{service.price | currency('EUR', $i18n.locale)}} + {{service.total | currency('EUR', $i18n.locale)}} diff --git a/print/templates/reports/delivery-note/sql/services.sql b/print/templates/reports/delivery-note/sql/services.sql index d64e8dc26..ec8a3e7ac 100644 --- a/print/templates/reports/delivery-note/sql/services.sql +++ b/print/templates/reports/delivery-note/sql/services.sql @@ -1,8 +1,9 @@ SELECT tc.code taxDescription, ts.description, - ts.quantity, - ts.price + ts.quantity, + ts.price, + ts.quantity * ts.price total FROM ticketService ts JOIN taxClass tc ON tc.id = ts.taxClassFk WHERE ts.ticketFk = ? \ No newline at end of file diff --git a/print/templates/reports/driver-route/sql/routes.sql b/print/templates/reports/driver-route/sql/routes.sql index 4b6f6a318..79bede5b2 100644 --- a/print/templates/reports/driver-route/sql/routes.sql +++ b/print/templates/reports/driver-route/sql/routes.sql @@ -1,4 +1,4 @@ -SELECT +SELECT r.id, r.m3, r.created, @@ -11,9 +11,9 @@ SELECT FROM route r LEFT JOIN vehicle v ON v.id = r.vehicleFk LEFT JOIN worker w ON w.id = r.workerFk - LEFT JOIN account.user u ON u.id = w.userFk + LEFT JOIN account.user u ON u.id = w.id LEFT JOIN agencyMode am ON am.id = r.agencyModeFk LEFT JOIN agency a ON a.id = am.agencyFk LEFT JOIN supplierAgencyTerm sa ON sa.agencyFk = a.id LEFT JOIN supplier s ON s.id = sa.supplierFk -WHERE r.id IN(?) \ No newline at end of file +WHERE r.id IN(?) diff --git a/print/templates/reports/incoterms-authorization/incoterms-authorization.html b/print/templates/reports/incoterms-authorization/incoterms-authorization.html index 99a5e9caa..8c0a327ab 100644 --- a/print/templates/reports/incoterms-authorization/incoterms-authorization.html +++ b/print/templates/reports/incoterms-authorization/incoterms-authorization.html @@ -3,16 +3,16 @@

diff --git a/print/templates/reports/incoterms-authorization/incoterms-authorization.js b/print/templates/reports/incoterms-authorization/incoterms-authorization.js index 53425487e..22ae13167 100755 --- a/print/templates/reports/incoterms-authorization/incoterms-authorization.js +++ b/print/templates/reports/incoterms-authorization/incoterms-authorization.js @@ -7,6 +7,7 @@ module.exports = { this.client = await this.findOneFromDef('client', [this.id]); this.checkMainEntity(this.client); this.company = await this.findOneFromDef('company', [this.companyId]); + this.address = await this.findOneFromDef('address', [this.addressId]); }, props: { id: { @@ -17,6 +18,10 @@ module.exports = { companyId: { type: Number, required: true + }, + addressId: { + type: Number, + required: true } } }; diff --git a/print/templates/reports/incoterms-authorization/locale/es.yml b/print/templates/reports/incoterms-authorization/locale/es.yml index 6936ebda9..ef63e9e3c 100644 --- a/print/templates/reports/incoterms-authorization/locale/es.yml +++ b/print/templates/reports/incoterms-authorization/locale/es.yml @@ -1,28 +1,25 @@ reportName: autorizacion-incoterms description: '{socialName} una sociedad debidamente constituida con responsabilidad limitada -y registrada conforme al derecho de sociedades de {country} y aquí representada por -___________________. {socialName}, con domicilio en {address}, +y registrada conforme al derecho de sociedades de {country} y aquí representada por {socialName}, con domicilio en {address}, CIF {fiscalID}. En adelante denominada {name}.' issued: 'En {0}, a {1} de {2} de {3}' client: 'Cliente {0}' declaration: '{socialName} declara por la presente que:' declarations: - - 'Todas las compras realizadas por {socialName} con {companyName} se -entregan, Ex Works (Incoterms), en el almacén de {companyName} situado en -{companyCity}.' - - '{socialName} reconoce que es importante para {companyName} tener -comprobante de la entrega intracomunitaria de la mercancía a {destinationCountry} para + - 'Todas las compras realizadas por {socialName} con {companyName} se entregan según las condiciones definidas en el incoterm.' + - '{socialName} reconoce que es importante para {companyName} tener +comprobante de la entrega intracomunitaria de la mercancía a {destinationCountry} para poder facturar con 0% de IVA.' - - 'Por tanto, al firmar este acuerdo, {socialName} declara que todos los bienes que + - 'Por tanto, al firmar este acuerdo, {socialName} declara que todos los bienes que se compren a {companyName} serán entregados a {destinationCountry}.' - - 'Además, {socialName} deberá, a primera solicitud de {companyName}, -proporcionar una prueba de que todos los productos comprados a {companyName} han + - 'Además, {socialName} deberá, a primera solicitud de {companyName}, +proporcionar una prueba de que todos los productos comprados a {companyName} han sido entregados en {destinationCountry}.' - - 'Además de lo anterior, {companyName} proporcionará a {socialName} -un resumen mensual en el que se incluyen todas las facturas (y las entregas correspondientes). -{socialName} firmará y devolverá el resumen mensual a {companyName}, + - 'Además de lo anterior, {companyName} proporcionará a {socialName} +un resumen mensual en el que se incluyen todas las facturas (y las entregas correspondientes). +{socialName} firmará y devolverá el resumen mensual a {companyName}, S.L. dentro de los 5 días posteriores a la recepción del resumen.' -signer: +signer: representative: Representante representativeRole: Cargo del representante signed: Fecha de firma @@ -39,4 +36,4 @@ months: - 'Septiembre' - 'Octubre' - 'Noviembre' - - 'Diciembre' \ No newline at end of file + - 'Diciembre' diff --git a/print/templates/reports/incoterms-authorization/locale/pt.yml b/print/templates/reports/incoterms-authorization/locale/pt.yml index 2d33e6a1a..996c0961e 100644 --- a/print/templates/reports/incoterms-authorization/locale/pt.yml +++ b/print/templates/reports/incoterms-authorization/locale/pt.yml @@ -1,28 +1,27 @@ reportName: autorizacion-incoterms description: '{socialName} uma sociedade devidamente constituída com responsabilidade limitada e registada -conforme ao direito de sociedades da {country} e aqui representada por -___________________. {socialName}, com domicílio em {address}, +conforme ao direito de sociedades da {country} e aqui representada por {socialName}, com domicílio em {address}, CIF {fiscalID}. Em adiante denominada {name}.' issued: 'Em {0}, em {1} de {2} de {3}' client: 'Cliente {0}' declaration: '{socialName} declara através da presente que:' declarations: - - 'Todas as compras realizadas por {socialName} a {companyName} se entregam, + - 'Todas as compras realizadas por {socialName} a {companyName} se entregam, Ex Works (Incoterms), no armazém da {companyName} situado em {companyCity}.' - - '{socialName} reconhece ser importante para {companyName} - ter o comprovante da entrega intracomunitária da mercadoria a {destinationCountry} + - '{socialName} reconhece ser importante para {companyName} + ter o comprovante da entrega intracomunitária da mercadoria em {destinationCountry} para poder faturar com 0% de IVA.' - - 'Portanto, ao assinar este acordo, {socialName} declara que todos os bens + - 'Portanto, ao assinar este acordo, {socialName} declara que todos os bens que se comprem na {companyName} serão entregues na {destinationCountry}.' - 'Além disto, {socialName} deverá, na primeira solicitude da {companyName}, - proporcionar uma prova de que todos os produtos comprados na {companyName} - foram entregues na {destinationCountry}.' - - 'Além do anterio, {companyName} proporcionará a {socialName} + proporcionar uma prova de que todos os produtos comprados em {companyName} + foram entregues em {destinationCountry}.' + - 'Além do anterior, {companyName} proporcionará a {socialName} um resumo mensal onde se incluem todas as faturas (e as entregas correspondentes). {socialName} assinará e devolverá o resumo mensal à {companyName}, dentro dos 5 dias posteriores à receção do resumo.' -signer: +signer: representative: Representante representativeRole: Cargo de representante signed: Data da assinatura @@ -39,4 +38,4 @@ months: - 'Setembro' - 'Outubro' - 'Novembro' - - 'Dezembro' \ No newline at end of file + - 'Dezembro' diff --git a/print/templates/reports/incoterms-authorization/sql/address.sql b/print/templates/reports/incoterms-authorization/sql/address.sql new file mode 100644 index 000000000..a432c5e53 --- /dev/null +++ b/print/templates/reports/incoterms-authorization/sql/address.sql @@ -0,0 +1,9 @@ +SELECT + a.nickname, + a.street, + a.postalCode, + a.city, + p.name province +FROM address a + LEFT JOIN province p ON p.id = a.provinceFk +WHERE a.id = ? diff --git a/print/templates/reports/incoterms-authorization/sql/company.sql b/print/templates/reports/incoterms-authorization/sql/company.sql index 39c3290d1..8d94859e1 100644 --- a/print/templates/reports/incoterms-authorization/sql/company.sql +++ b/print/templates/reports/incoterms-authorization/sql/company.sql @@ -1,8 +1,8 @@ -SELECT +SELECT s.name, s.city, cl.name AS manager FROM company c JOIN supplier s ON s.id = c.id JOIN client cl ON cl.id = c.workerManagerFk -WHERE c.id = ? \ No newline at end of file +WHERE c.id = ? diff --git a/print/templates/reports/invoice/assets/css/style.css b/print/templates/reports/invoice/assets/css/style.css index d4526ce56..f9f6f220f 100644 --- a/print/templates/reports/invoice/assets/css/style.css +++ b/print/templates/reports/invoice/assets/css/style.css @@ -44,3 +44,7 @@ h2 { .phytosanitary-info { margin-top: 10px } + +.panel { + margin-bottom: 0px; +} diff --git a/print/templates/reports/invoice/invoice.js b/print/templates/reports/invoice/invoice.js index 1c9965d3b..b26472b08 100755 --- a/print/templates/reports/invoice/invoice.js +++ b/print/templates/reports/invoice/invoice.js @@ -7,6 +7,7 @@ module.exports = { mixins: [vnReport], async serverPrefetch() { this.invoice = await this.findOneFromDef('invoice', [this.reference]); + this.checkMainEntity(this.invoice); this.client = await this.findOneFromDef('client', [this.reference]); this.taxes = await this.rawSqlFromDef(`taxes`, [this.reference]);