diff --git a/CHANGELOG.md b/CHANGELOG.md index b322f9f25..f59a3d4c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,83 @@ +# Version 24.28 - 2024-07-09 + +### Added 🆕 + +- feat boxPicking refs #7357 by:sergiodt +- feat boxPicking refs #7357 (origin/7357_dipole_review) by:sergiodt +- feat:concurrency issue refs #6861 by:Carlos Andrés +- feat expeditionPalletPrint refs #5210 by:sergiodt +- feat front-reservas refs #6861 (origin/6861-Reservas-front) by:sergiodt +- feat itemShelving_filterBuyer refs #7023 by:sergiodt +- feat itemShelvingLog refs #7168 by:sergiodt +- feat itemShelvingSale refs #6861 by:sergiodt +- feat: previas con reserva refs #6861 by:Carlos Andrés +- feat: previas con sitema de reservas refs #6861 by:Carlos Andrés +- feat: previas con sitema de reservas refs #6861 (origin/6861-Pasar-modo-trabajo-de-previa-a-reservas) by:Carlos Andrés +- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt +- feat: refs #6238 add travelKgPercentage table and model (origin/6238-addPercentage) by:jorgep +- feat: refs #6286 check if is teamBoss (origin/6286-setRightWorkerTimeControlAcls) by:jorgep +- feat: refs #6701 Fix error by:guillermo +- feat: refs #6861 trigger by:sergiodt +- feat: refs #7027 mailError managed by:jgallego +- feat: refs #7168 Added vRecords param in proc by:guillermo +- feat: refs #7168 Minor change by:guillermo +- feat: refs #7216 logUnpaid (origin/7216-clientUnpaid) by:jgallego +- feat: refs #7216 triggers by:jgallego +- feat: refs #7296 by:robert +- feat: refs #7296 drop column expeditionTruckFk by:robert +- feat: refs #7490 Changes (origin/7490-duaInvoiceInBooking) by:guillermo +- feat: refs #7545 Deleted hasIncoterms client column (origin/7545-hasIncoterms) by:guillermo +- feat: refs #7555 remove account.password__ by:alexm +- feat: return sql check error by:alexm +- feat roadmap refs #7195 by:sergiodt +- #refs 5890 feat:add assignCollection by:sergiodt +- refs#5890 feat: delete trigger and modify getTickets by:sergiodt +- refs #5890 feat:itemShelving_add by:sergiodt +- refs #5890 feat:reserves by:sergiodt +- refs #5890 feat:trigger by:sergiodt +- refs #5890 feat: triggers by:sergiodt +- refs #6861 feat: getLock by:sergiodt +- refs #6861 feat: obsrevation by:sergiodt +- refs #6861 feat: previas a reservas by:sergiodt +- refs #6861 feat:reserve previos by:sergiodt +- refs #6861 feat: reservePrevious by:sergiodt +- refs #6861 feat:reserveWithReservation by:sergiodt +- refs #6861 feat:sectoCollection reserve by:sergiodt +- refs #6861 feat: skipTest by:sergiodt +- refs #6861 feat: trigger by:sergiodt + +### Changed 📦 + +- feat refactor setParking REGEXP refs #7575 (origin/7575_setParking_regExp) by:sergiodt +- refactor: refs #5447 changed models by:Jon +- refactor: refs #6238 drop useless round by:jorgep +- refactor: refs #6286 replace name by:jorgep +- refactor: refs #6701 Refactor claim_ratio_routine by:guillermo +- refactor: refs #7490 Added final update by:guillermo +- refactor: refs #7490 Deleted update duaInvoiceInBooking by:guillermo +- refactor: refs #7490 Minor changes by:guillermo +- refactor: refs #7519 Minor change by:guillermo + +### Fixed 🛠️ + +- acls, fixtures, models by:carlossa +- fix: refs #6238 delete unused SQL script by:jorgep +- fix: refs #6238 insert ignore by:jorgep +- fix: refs #6238 use scheme by:jorgep +- fix: refs #6286 replace id for reason by:jorgep +- fix: refs #6286 update WorkerTimeControl permissions by:jorgep +- fix(WorkerIncome): refs #7409 fix models by:alexm +- refs #5890 fix: dev by:sergiodt +- refs #6897 fix entry Salix by:carlossa +- refs #6897 fix es.yml by:carlossa +- refs #6897 fix redirection by:carlossa +- refs #6897 fix remove by:carlossa +- refs #7406 fix back by:carlossa +- refs #7406 fix pr by:carlossa +- refs #7409 fix acls by:carlossa +- refs #7409 fix back (origin/7409-workerIncome) by:carlossa +- refs #7409 fix pr by:carlossa + # Version 24.24 - 2024-06-11 ### Added 🆕 @@ -22,6 +102,7 @@ - feat: refs #7438 Added volume to item_valuateInventory by:guillermo - feat: refs #7438 Requested changes and little changes by:guillermo - refs #6281 feat:buyFk in itemShelving by:sergiodt +- feat: refs #6449 item ID is displayed in the sale line by:jorgep ### Changed 📦 diff --git a/back/methods/collection/assignCollection.js b/back/methods/collection/assignCollection.js new file mode 100644 index 000000000..2ff37ab59 --- /dev/null +++ b/back/methods/collection/assignCollection.js @@ -0,0 +1,29 @@ +const UserError = require('vn-loopback/util/user-error'); +module.exports = Self => { + Self.remoteMethodCtx('assignCollection', { + description: 'Assign a collection', + accessType: 'WRITE', + http: { + path: `/assignCollection`, + verb: 'POST' + }, + returns: { + type: ['object'], + root: true + }, + }); + + Self.assignCollection = async(ctx, options) => { + const userId = ctx.req.accessToken.userId; + const myOptions = {userId}; + + if (typeof options == 'object') + Object.assign(myOptions, options); + const [info, info2, [{'@vCollectionFk': collectionFk}]] = await Self.rawSql( + 'CALL vn.collection_getAssigned(?, @vCollectionFk);SELECT @vCollectionFk', [userId], myOptions); + if (!collectionFk) throw new UserError('There are not picking tickets'); + await Self.rawSql('CALL vn.collection_printSticker(?, NULL)', [collectionFk], myOptions); + + return collectionFk; + }; +}; diff --git a/back/methods/collection/getSales.js b/back/methods/collection/getSales.js index fd5e3d085..a9e5f2e60 100644 --- a/back/methods/collection/getSales.js +++ b/back/methods/collection/getSales.js @@ -1,6 +1,6 @@ module.exports = Self => { Self.remoteMethodCtx('getSales', { - description: 'Get sales from ticket or collection', + description: 'Get sales from ticket, collection or sectorCollection', accessType: 'READ', accepts: [ { @@ -60,15 +60,17 @@ module.exports = Self => { if (print) await Self.rawSql('CALL vn.collection_printSticker(?,NULL)', [id], myOptions); for (let ticket of tickets) { - let observations = ticket.observaciones.split(' '); + if (ticket.observaciones) { + let observations = ticket.observaciones.split(' '); - for (let observation of observations) { - const salesPerson = ticket.salesPersonFk; - if (observation.startsWith('#') || observation.startsWith('@')) { - await models.Chat.send(ctx, - observation, - $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) - ); + for (let observation of observations) { + const salesPerson = ticket.salesPersonFk; + if (observation.startsWith('#') || observation.startsWith('@')) { + await models.Chat.send(ctx, + observation, + $t('ticketCommercial', {ticket: ticket.ticketFk, salesPerson}) + ); + } } } } diff --git a/back/methods/collection/getTickets.js b/back/methods/collection/getTickets.js index 50117b954..b79dbc93a 100644 --- a/back/methods/collection/getTickets.js +++ b/back/methods/collection/getTickets.js @@ -37,6 +37,7 @@ module.exports = Self => { const promises = []; const [tickets] = await Self.rawSql(`CALL vn.collection_getTickets(?)`, [id], myOptions); + const sales = await Self.rawSql(` SELECT s.ticketFk, sgd.saleGroupFk, @@ -62,13 +63,12 @@ module.exports = Self => { 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 + JOIN sale s ON s.ticketFk = tc.ticketFk 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 + 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 @@ -76,17 +76,55 @@ module.exports = Self => { LEFT JOIN origin o ON o.id = i.originFk WHERE tc.collectionFk = ? GROUP BY s.id, ish.id, p.code, p2.code - ORDER BY pickingOrder;`, [id], myOptions); - + UNION ALL + 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, + iss.quantity, + SUM(iss.quantity) OVER (PARTITION BY s.id ORDER BY ish.id), + ROW_NUMBER () OVER (PARTITION BY s.id ORDER BY p.pickingOrder), + COUNT(*) OVER (PARTITION BY s.id ORDER BY s.id) , + sh.code, + IFNULL(p2.code, p.code), + IFNULL(p2.pickingOrder, p.pickingOrder), + iss.id itemShelvingSaleFk, + iss.isPicked + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN saleGroup sg ON sg.id = ss.saleGroupFk + LEFT JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN sale s ON s.id = sgd.saleFk + LEFT JOIN parking p2 ON p2.id = sg.parkingFk + JOIN item i ON i.id = s.itemFk + 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 sc.id = ? + AND sgd.saleGroupFk + GROUP BY s.id, ish.id, p.code, p2.code`, [id, 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 (ticket.observation) { + for (observation of ticket.observation?.split(' ')) { if (['#', '@'].includes(observation.charAt(0))) { promises.push(Self.app.models.Chat.send(ctx, observation, $t('The ticket is in preparation', { @@ -100,11 +138,11 @@ module.exports = Self => { 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 + FROM sale s + LEFT JOIN itemBarcode b ON b.itemFk = s.itemFk + LEFT JOIN buy c ON c.itemFk = s.itemFk + LEFT JOIN entry e ON e.id = c.entryFk + LEFT JOIN travel tr ON tr.id = e.travelFk WHERE s.ticketFk = ? AND tr.landed >= util.VN_CURDATE() - INTERVAL 1 YEAR`, [ticketId], myOptions); diff --git a/back/methods/collection/spec/assignCollection.spec.js b/back/methods/collection/spec/assignCollection.spec.js new file mode 100644 index 000000000..e8f3882a3 --- /dev/null +++ b/back/methods/collection/spec/assignCollection.spec.js @@ -0,0 +1,38 @@ +const models = require('vn-loopback/server/server').models; +const LoopBackContext = require('loopback-context'); + +describe('ticket assignCollection()', () => { + let ctx; + let options; + let tx; + beforeEach(async() => { + ctx = { + req: { + accessToken: {userId: 1106}, + headers: {origin: 'http://localhost'}, + __: value => value + }, + args: {} + }; + + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: ctx.req + }); + + options = {transaction: tx}; + tx = await models.Sale.beginTransaction({}); + options.transaction = tx; + }); + + afterEach(async() => { + await tx.rollback(); + }); + + it('should throw an error when there is not picking tickets', async() => { + try { + await models.Collection.assignCollection(ctx, options); + } catch (e) { + expect(e.message).toEqual('There are not picking tickets'); + } + }); +}); diff --git a/back/methods/collection/spec/getSales.spec.js b/back/methods/collection/spec/getSales.spec.js index e6205cc79..520657ec1 100644 --- a/back/methods/collection/spec/getSales.spec.js +++ b/back/methods/collection/spec/getSales.spec.js @@ -4,15 +4,7 @@ describe('collection getSales()', () => { const collectionOrTicketFk = 999999; const print = true; const source = 'CHECKER'; - - beforeAll(() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'}, - } - }; - }); + const ctx = beforeAll.getCtx(); it('should return a collection with tickets, placements and barcodes settled correctly', async() => { const tx = await models.Collection.beginTransaction({}); diff --git a/back/methods/collection/spec/getTickets.spec.js b/back/methods/collection/spec/getTickets.spec.js index e6b9e6a17..0e006706d 100644 --- a/back/methods/collection/spec/getTickets.spec.js +++ b/back/methods/collection/spec/getTickets.spec.js @@ -1,15 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('collection getTickets()', () => { - let ctx; - beforeAll(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - }); + const ctx = beforeAll.getCtx(); it('should get tickets, sales and barcodes from collection', async() => { const tx = await models.Collection.beginTransaction({}); @@ -26,8 +18,8 @@ describe('collection getTickets()', () => { 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[1].sales.length).toEqual(0); + expect(collectionTickets.tickets[2].sales.length).toEqual(0); expect(collectionTickets.tickets[0].sales[0].Barcodes.length).toBeTruthy(); await tx.rollback(); diff --git a/back/methods/collection/spec/setSaleQuantity.spec.js b/back/methods/collection/spec/setSaleQuantity.spec.js index b563f5b19..00ddae0fe 100644 --- a/back/methods/collection/spec/setSaleQuantity.spec.js +++ b/back/methods/collection/spec/setSaleQuantity.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('setSaleQuantity()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should change quantity sale', async() => { const tx = await models.Ticket.beginTransaction({}); diff --git a/back/methods/edi/updateData.js b/back/methods/edi/updateData.js index 6bebad1e4..d8395cbc4 100644 --- a/back/methods/edi/updateData.js +++ b/back/methods/edi/updateData.js @@ -24,7 +24,7 @@ module.exports = Self => { try { const options = {transaction: tx, userId: ctx.req.accessToken.userId}; - const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileConfig', null, options); + const files = await Self.rawSql('SELECT name, checksum, keyValue FROM edi.fileMultiConfig', null, options); const updatableFiles = []; for (const file of files) { @@ -54,7 +54,7 @@ module.exports = Self => { const tables = await Self.rawSql(` SELECT fileName, toTable, file - FROM edi.tableConfig + FROM edi.tableMultiConfig WHERE file IN (?)`, [fileNames], options); for (const table of tables) { @@ -85,9 +85,9 @@ module.exports = Self => { for (const file of updatableFiles) { console.log(`Updating file ${file.name} checksum...`); await Self.rawSql(` - UPDATE edi.fileConfig - SET checksum = ? - WHERE name = ?`, + UPDATE edi.fileMultiConfig + SET checksum = ? + WHERE name = ?`, [file.checksum, file.name], options); } @@ -228,7 +228,7 @@ module.exports = Self => { await Self.rawSql(sqlTemplate, [filePath], options); await Self.rawSql(` - UPDATE edi.tableConfig + UPDATE edi.tableMultiConfig SET updated = ? WHERE fileName = ? `, [Date.vnNew(), baseName], options); diff --git a/back/methods/mrw-config/cancelShipment.ejs b/back/methods/mrw-config/cancelShipment.ejs index 9ef401bc8..bc0662981 100644 --- a/back/methods/mrw-config/cancelShipment.ejs +++ b/back/methods/mrw-config/cancelShipment.ejs @@ -2,7 +2,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/cancelShipment.js b/back/methods/mrw-config/cancelShipment.js index 86bbb7410..56d206529 100644 --- a/back/methods/mrw-config/cancelShipment.js +++ b/back/methods/mrw-config/cancelShipment.js @@ -13,7 +13,7 @@ module.exports = Self => { required: true }], returns: { - type: ['object'], + type: 'boolean', root: true }, http: { @@ -27,9 +27,9 @@ module.exports = Self => { const mrw = await models.MrwConfig.findOne(); const {externalId} = await models.Expedition.findById(expeditionFk); - + const clientType = await models.MrwConfig.getClientType(expeditionFk); const template = fs.readFileSync(__dirname + '/cancelShipment.ejs', 'utf-8'); - const renderedXml = ejs.render(template, {mrw, externalId}); + const renderedXml = ejs.render(template, {mrw, externalId, clientType}); const response = await axios.post(mrw.url, renderedXml, { headers: { 'Content-Type': 'application/soap+xml; charset=utf-8' @@ -39,6 +39,7 @@ module.exports = Self => { const xmlString = response.data; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, 'text/xml'); - return xmlDoc.getElementsByTagName('Mensaje')[0].textContent; + const result = xmlDoc.getElementsByTagName('Mensaje')[0].textContent; + return result.toLowerCase().includes('se ha cancelado correctamente'); }; }; diff --git a/back/methods/mrw-config/createShipment.ejs b/back/methods/mrw-config/createShipment.ejs index 7468218f2..65326112b 100644 --- a/back/methods/mrw-config/createShipment.ejs +++ b/back/methods/mrw-config/createShipment.ejs @@ -3,7 +3,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/createShipment.js b/back/methods/mrw-config/createShipment.js index b5bea648d..900e1fc0f 100644 --- a/back/methods/mrw-config/createShipment.js +++ b/back/methods/mrw-config/createShipment.js @@ -1,7 +1,3 @@ -const axios = require('axios'); -const {DOMParser} = require('xmldom'); -const fs = require('fs'); -const ejs = require('ejs'); const UserError = require('vn-loopback/util/user-error'); module.exports = Self => { @@ -23,23 +19,21 @@ module.exports = Self => { } }); - Self.createShipment = async(expeditionFk, options) => { - const myOptions = {}; - let tx; - - if (typeof options == 'object') - Object.assign(myOptions, options); - - if (!myOptions.transaction) { - tx = await Self.beginTransaction({}); - myOptions.transaction = tx; - } - + Self.createShipment = async expeditionFk => { const models = Self.app.models; - const mrw = await models.MrwConfig.findOne(null, myOptions); + const mrw = await Self.getConfig(); + const clientType = await models.MrwConfig.getClientType(expeditionFk); - if (!mrw) - throw new UserError(`Some mrwConfig parameters are not set`); + const today = Date.vnNew(); + const [hours, minutes] = mrw?.expeditionDeadLine ? mrw.expeditionDeadLine.split(':').map(Number) : [0, 0]; + + const deadLine = Date.vnNew(); + deadLine.setHours(hours, minutes, 0); + + if (today > deadLine && (!mrw.notified || mrw.notified.setHours(0, 0, 0, 0) !== today.setHours(0, 0, 0, 0))) { + await models.NotificationQueue.create({notificationFk: 'mrw-deadline'}); + await mrw.updateAttributes({notified: Date.vnNow()}); + } const query = `SELECT @@ -57,63 +51,41 @@ module.exports = Self => { DATE_FORMAT(t.shipped, '%d/%m/%Y') created, t.shipped, CONCAT( e.ticketFk, LPAD(e.counter, mc.counterWidth, '0')) reference, - LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth,'0') serviceType, + LPAD(IF(mw.serviceType IS NULL, ms.serviceType, mw.serviceType), mc.serviceTypeWidth, '0') serviceType, IF(mw.weekdays, 'S', 'N') weekDays, oa.description deliveryObservation FROM expedition e JOIN ticket t ON e.ticketFk = t.id JOIN agencyMode am ON am.id = t.agencyModeFk JOIN mrwService ms ON ms.agencyModeCodeFk = am.code - LEFT JOIN mrwServiceWeekday mw ON mw.weekdays | 1 << WEEKDAY(t.landed) + LEFT JOIN mrwServiceWeekday mw ON mw.agencyModeCodeFk = am.code + AND mw.weekDays & (1 << WEEKDAY(t.landed)) JOIN client c ON t.clientFk = c.id JOIN address a ON t.addressFk = a.id LEFT JOIN addressObservation oa ON oa.addressFk = a.id - LEFT JOIN observationType ot ON ot.id = oa.observationTypeFk - AND ot.code = 'delivery' + AND oa.observationTypeFk IN (SELECT id FROM observationType ot WHERE ot.code = 'delivery') JOIN province p ON a.provinceFk = p.id JOIN country co ON co.id = p.countryFk JOIN mrwConfig mc WHERE e.id = ? LIMIT 1`; - const [expeditionData] = await Self.rawSql(query, [expeditionFk], myOptions); + const [expeditionData] = await Self.rawSql(query, [expeditionFk]); - if (!expeditionData) - throw new UserError(`This expedition is not a MRW shipment`); - - const today = Date.vnNew(); - today.setHours(0, 0, 0, 0); - if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today) + if (expeditionData?.shipped.setHours(0, 0, 0, 0) < today.setHours(0, 0, 0, 0)) throw new UserError(`This ticket has a shipped date earlier than today`); - const shipmentResponse = await sendXmlDoc('createShipment', {mrw, expeditionData}, 'application/soap+xml'); - const shipmentId = getTextByTag(shipmentResponse, 'NumeroEnvio'); + const shipmentResponse = await Self.sendXmlDoc( + __dirname + `/createShipment.ejs`, + {mrw, expeditionData, clientType}, + 'application/soap+xml' + ); + const shipmentId = Self.getTextByTag(shipmentResponse, 'NumeroEnvio'); - if (!shipmentId) - throw new UserError(getTextByTag(shipmentResponse, 'Mensaje')); + if (!shipmentId) throw new UserError(Self.getTextByTag(shipmentResponse, 'Mensaje')); - const getLabelResponse = await sendXmlDoc('getLabel', {mrw, shipmentId}, 'text/xml'); - const file = getTextByTag(getLabelResponse, 'EtiquetaFile'); - - if (tx) await tx.commit(); + const file = await models.MrwConfig.getLabel(shipmentId, clientType); return {shipmentId, file}; }; - - function getTextByTag(xmlDoc, tag) { - return xmlDoc?.getElementsByTagName(tag)[0]?.textContent; - } - - async function sendXmlDoc(xmlDock, params, contentType) { - const parser = new DOMParser(); - - const xmlTemplate = fs.readFileSync(__dirname + `/${xmlDock}.ejs`, 'utf-8'); - const renderedTemplate = ejs.render(xmlTemplate, params); - const data = await axios.post(params.mrw.url, renderedTemplate, { - headers: { - 'Content-Type': `${contentType}; charset=utf-8` - } - }); - return parser.parseFromString(data.data, 'text/xml'); - } }; diff --git a/back/methods/mrw-config/getLabel.ejs b/back/methods/mrw-config/getLabel.ejs index 09bdb3f6c..b0dae17c8 100644 --- a/back/methods/mrw-config/getLabel.ejs +++ b/back/methods/mrw-config/getLabel.ejs @@ -2,7 +2,7 @@ <%= mrw.franchiseCode %> - <%= mrw.subscriberCode %> + <%= clientType %> <%= mrw.user %> <%= mrw.password %> diff --git a/back/methods/mrw-config/getLabel.js b/back/methods/mrw-config/getLabel.js new file mode 100644 index 000000000..4af3276bb --- /dev/null +++ b/back/methods/mrw-config/getLabel.js @@ -0,0 +1,37 @@ +module.exports = Self => { + Self.remoteMethod('getLabel', { + description: 'Return a base64Binary label from de MRW WebService', + accessType: 'READ', + accepts: [{ + arg: 'shipmentId', + type: 'string', + required: true + }, + { + arg: 'clientType', + type: 'string', + required: true + }, + ], + returns: { + type: 'string', + root: true + }, + http: { + path: `/getLabel`, + verb: 'GET' + } + }); + + Self.getLabel = async(shipmentId, clientType) => { + const mrw = await Self.getConfig(); + + const getLabelResponse = await Self.sendXmlDoc( + __dirname + `/getLabel.ejs`, + {mrw, shipmentId, clientType}, + 'text/xml' + ); + + return Self.getTextByTag(getLabelResponse, 'EtiquetaFile'); + }; +}; diff --git a/back/methods/mrw-config/specs/createShipment.spec.js b/back/methods/mrw-config/specs/createShipment.spec.js index f05f9a81d..1ab77f608 100644 --- a/back/methods/mrw-config/specs/createShipment.spec.js +++ b/back/methods/mrw-config/specs/createShipment.spec.js @@ -2,6 +2,7 @@ const models = require('vn-loopback/server/server').models; const axios = require('axios'); const fs = require('fs'); +const filter = {notificationFk: 'mrw-deadline'}; const mockBase64Binary = 'base64BinaryString'; const ticket1 = { 'id': '44', @@ -28,25 +29,49 @@ const expedition1 = { 'editorFk': 100 }; -let tx; -let options; - describe('MRWConfig createShipment()', () => { - beforeEach(async() => { - options = tx = undefined; - tx = await models.MrwConfig.beginTransaction({}); - options = {transaction: tx}; - + beforeAll(async() => { await models.Agency.create( - {'id': 999, 'name': 'mrw'}, - options + {'id': 999, 'name': 'mrw'} ); await models.AgencyMode.create( - {'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'}, - options + {'id': 999, 'name': 'mrw', 'agencyFk': 999, 'code': 'mrw'} + ); + await models.MrwService.create( + {'agencyModeCodeFk': 'mrw', 'clientType': '000001', 'serviceType': 105, 'kg': 10} + ); + + await createMrwConfig(); + + await models.Ticket.create(ticket1); + await models.Expedition.create(expedition1); + }); + + afterAll(async() => { + await cleanFixtures(); + await models.Ticket.destroyAll(ticket1); + await models.Expedition.destroyAll(ticket1); + }); + + beforeEach(async() => { + const mockPostResponses = [ + {data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')}, + {data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')} + ]; + + spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop())); + await cleanFixtures(); + }); + + async function cleanFixtures() { + await models.NotificationQueue.destroyAll(filter); + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: null, notified: null}); + } + + async function createMrwConfig() { await models.MrwConfig.create( { 'id': 1, @@ -54,68 +79,82 @@ describe('MRWConfig createShipment()', () => { 'user': 'user', 'password': 'password', 'franchiseCode': 'franchiseCode', - 'subscriberCode': 'subscriberCode' - }, options + 'subscriberCode': 'subscriberCode', + 'clientTypeWidth': 6 + } ); + } - await models.Application.rawSql( - `INSERT INTO vn.mrwService - SET agencyModeCodeFk = 'mrw', - clientType = 1, - serviceType = 1, - kg = 1`, null, options - ); - await models.Ticket.create(ticket1, options); - await models.Expedition.create(expedition1, options); - }); - - afterEach(async() => { - await tx.rollback(); - }); + async function getLastNotification() { + return models.NotificationQueue.findOne({ + order: 'id DESC', + where: filter + }); + } it('should create a shipment and return a base64Binary label', async() => { - const mockPostResponses = [ - {data: fs.readFileSync(__dirname + '/mockGetLabel.xml', 'utf-8')}, - {data: fs.readFileSync(__dirname + '/mockCreateShipment.xml', 'utf-8')} - ]; - - spyOn(axios, 'post').and.callFake(() => Promise.resolve(mockPostResponses.pop())); - - const {file} = await models.MrwConfig.createShipment(expedition1.id, options); + const {file} = await models.MrwConfig.createShipment(expedition1.id); expect(file).toEqual(mockBase64Binary); }); it('should fail if mrwConfig has no data', async() => { let error; + await models.MrwConfig.destroyAll(); await models.MrwConfig.createShipment(expedition1.id).catch(e => { error = e; }).finally(async() => { - expect(error.message).toEqual(`Some mrwConfig parameters are not set`); + expect(error.message).toEqual(`MRW service is not configured`); }); + await createMrwConfig(); expect(error).toBeDefined(); }); it('should fail if expeditionFk is not a MrwExpedition', async() => { let error; - await models.MrwConfig.createShipment(undefined, options).catch(e => { + await models.MrwConfig.createShipment(15).catch(e => { error = e; }).finally(async() => { - expect(error.message).toEqual(`This expedition is not a MRW shipment`); + expect(error.message).toEqual(`ClientType not available`); }); }); - it(' should fail if the creation date of this ticket is before the current date it', async() => { + it('should fail if the creation date of this ticket is before the current date', async() => { let error; const yesterday = Date.vnNew(); - yesterday.setDate(yesterday.getDate() - 1); - await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}, options); - await models.MrwConfig.createShipment(expedition1.id, options).catch(e => { + + await models.Ticket.updateAll({id: ticket1.id}, {shipped: yesterday}); + await models.MrwConfig.createShipment(expedition1.id).catch(e => { error = e; }).finally(async() => { expect(error.message).toEqual(`This ticket has a shipped date earlier than today`); }); + await models.Ticket.updateAll({id: ticket1.id}, {shipped: Date.vnNew()}); + }); + + it('should send mail if you are past the dead line and is not notified today', async() => { + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: null}); + await models.MrwConfig.createShipment(expedition1.id); + const notification = await getLastNotification(); + + expect(notification.notificationFk).toEqual(filter.notificationFk); + }); + + it('should send mail if you are past the dead line and it is notified from another day', async() => { + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: new Date()}); + await models.MrwConfig.createShipment(expedition1.id); + const notification = await getLastNotification(); + + expect(notification.notificationFk).toEqual(filter.notificationFk); + }); + + it('should not send mail if you are past the dead line and it is notified', async() => { + await models.MrwConfig.updateAll({id: 1}, {expeditionDeadLine: '10:00:00', notified: Date.vnNew()}); + await models.MrwConfig.createShipment(expedition1.id); + const notification = await getLastNotification(); + + expect(notification).toEqual(null); }); }); diff --git a/back/methods/starred-module/specs/getStarredModules.spec.js b/back/methods/starred-module/specs/getStarredModules.spec.js index bf9bd1d73..afe1dd9c2 100644 --- a/back/methods/starred-module/specs/getStarredModules.spec.js +++ b/back/methods/starred-module/specs/getStarredModules.spec.js @@ -1,22 +1,7 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('getStarredModules()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = {req: activeCtx}; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); it(`should return the starred modules for a given user`, async() => { const newStarred = await models.StarredModule.create({workerFk: 9, moduleFk: 'customer', position: 1}); diff --git a/back/methods/starred-module/specs/setPosition.spec.js b/back/methods/starred-module/specs/setPosition.spec.js index a428fcf22..63addeffc 100644 --- a/back/methods/starred-module/specs/setPosition.spec.js +++ b/back/methods/starred-module/specs/setPosition.spec.js @@ -1,24 +1,8 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('setPosition()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = { - req: activeCtx - }; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); + beforeAll.mockLoopBackContext(); it('should increase the orders module position by replacing it with clients and vice versa', async() => { const tx = await models.StarredModule.beginTransaction({}); diff --git a/back/methods/starred-module/specs/toggleStarredModule.spec.js b/back/methods/starred-module/specs/toggleStarredModule.spec.js index 848c1475a..d506abc33 100644 --- a/back/methods/starred-module/specs/toggleStarredModule.spec.js +++ b/back/methods/starred-module/specs/toggleStarredModule.spec.js @@ -1,24 +1,7 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('toggleStarredModule()', () => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - const ctx = { - req: activeCtx - }; - - beforeEach(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); it('should create a new starred module and then remove it by calling the method again with same args', async() => { const starredModule = await models.StarredModule.toggleStarredModule(ctx, 'order'); @@ -26,7 +9,7 @@ describe('toggleStarredModule()', () => { expect(starredModules.length).toEqual(1); expect(starredModule.moduleFk).toEqual('order'); - expect(starredModule.workerFk).toEqual(activeCtx.accessToken.userId); + expect(starredModule.workerFk).toEqual(ctx.req.accessToken.userId); expect(starredModule.position).toEqual(starredModules.length); await models.StarredModule.toggleStarredModule(ctx, 'order'); diff --git a/back/methods/url/getUrl.js b/back/methods/url/getUrl.js index fa3f7fdad..5c6e5655f 100644 --- a/back/methods/url/getUrl.js +++ b/back/methods/url/getUrl.js @@ -22,7 +22,7 @@ module.exports = Self => { const url = await Self.app.models.Url.findOne({ where: { appName, - environment: process.env.NODE_ENV || 'development' + environment: process.env.NODE_ENV || 'dev' } }); return url?.url; diff --git a/back/methods/user-config/specs/getUserConfig.spec.js b/back/methods/user-config/specs/getUserConfig.spec.js index 8b510a706..bbfb98ef7 100644 --- a/back/methods/user-config/specs/getUserConfig.spec.js +++ b/back/methods/user-config/specs/getUserConfig.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('userConfig getUserConfig()', () => { + const ctx = beforeAll.getCtx(); it(`should return the configuration data of a given user`, async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const ctx = {req: {accessToken: {userId: 9}}}; const result = await models.UserConfig.getUserConfig(ctx, options); expect(result.warehouseFk).toEqual(1); diff --git a/back/methods/viaexpress-config/renderer.js b/back/methods/viaexpress-config/renderer.js index c8533ea6b..5d83b5870 100644 --- a/back/methods/viaexpress-config/renderer.js +++ b/back/methods/viaexpress-config/renderer.js @@ -20,7 +20,7 @@ module.exports = Self => { } }); - Self.renderer = async (expeditionFk) => { + Self.renderer = async expeditionFk => { const models = Self.app.models; const viaexpressConfig = await models.ViaexpressConfig.findOne({ @@ -109,7 +109,7 @@ module.exports = Self => { const ticket = expedition.ticket(); const sender = ticket.company().client(); const shipped = ticket.shipped.toISOString(); - const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk) + const isInterdia = (ticket.agencyModeFk === viaexpressConfig.agencyModeFk); const data = { viaexpressConfig, sender, diff --git a/back/methods/vn-user/renew-token.js b/back/methods/vn-user/renew-token.js index 5581d19ac..ae2d36e3e 100644 --- a/back/methods/vn-user/renew-token.js +++ b/back/methods/vn-user/renew-token.js @@ -16,36 +16,51 @@ module.exports = Self => { accessScopes: ['DEFAULT', 'read:multimedia']}); Self.renewToken = async function(ctx) { - const {accessToken: token} = ctx.req; - - const {courtesyTime} = await models.AccessTokenConfig.findOne({ - fields: ['courtesyTime'] - }); - const isNotExceeded = await Self.validateToken(ctx); - if (isNotExceeded) - return token; - - // Schedule to remove current token - setTimeout(async() => { - try { - const exists = await models.AccessToken.findById(token.id); - exists && await Self.logout(token.id); - } catch (err) { - // eslint-disable-next-line no-console - console.error(err); - } - }, courtesyTime * 1000); - - // Get scopes - let createTokenOptions = {}; - const {scopes} = token; - if (scopes) - createTokenOptions = {scopes: [scopes[0]]}; - // Create new accessToken - const user = await Self.findById(token.userId); - const accessToken = await user.accessTokens.create(createTokenOptions); + let token; let isNotExceeded; + try { + token = ctx.req.accessToken; - return {id: accessToken.id, ttl: accessToken.ttl}; + const {courtesyTime} = await models.AccessTokenConfig.findOne({ + fields: ['courtesyTime'] + }); + isNotExceeded = await Self.validateToken(ctx); + if (isNotExceeded) + return token; + + // Schedule to remove current token + setTimeout(async() => { + let exists; + try { + exists = await models.AccessToken.findById(token.id); + exists && await Self.logout(token.id); + } catch (error) { + // eslint-disable-next-line no-console + console.error(error); + const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, exists}; + await handleError(body); + throw new Error(error); + } + }, courtesyTime * 1000); + + // Get scopes + const {scopes} = token; + if (scopes) + createTokenOptions = {scopes: [scopes[0]]}; + // Create new accessToken + const user = await Self.findById(token.userId); + const accessToken = await user.accessTokens.create(createTokenOptions); + + return {id: accessToken.id, ttl: accessToken.ttl}; + } catch (error) { + const body = {error: error.message, now: Date.now(), userId: token?.userId ?? null, createTokenOptions, isNotExceeded}; + await handleError(body); + throw new Error(error); + } }; }; + +async function handleError(body, tag = 'renewToken') { + body = JSON.stringify(body); + await models.Application.rawSql('CALL util.debugAdd(?,?);', [tag, body]); +} diff --git a/back/methods/vn-user/specs/renew-token.spec.js b/back/methods/vn-user/specs/renew-token.spec.js index 70e7473d1..8f1bb54c1 100644 --- a/back/methods/vn-user/specs/renew-token.spec.js +++ b/back/methods/vn-user/specs/renew-token.spec.js @@ -61,4 +61,21 @@ describe('Renew Token', () => { expect(error).toBeUndefined(); expect(response.id).toEqual(ctx.req.accessToken.id); }); + + it('throw error', async() => { + let error; + + try { + await models.VnUser.renewToken({req: {token: null}}); + } catch (e) { + error = e; + } + + expect(error).toBeDefined(); + const query = 'SELECT * FROM util.debug'; + + const debugLog = await models.Application.rawSql(query, null); + + expect(debugLog.length).toEqual(1); + }); }); diff --git a/back/model-config.json b/back/model-config.json index c956e96e5..538765f69 100644 --- a/back/model-config.json +++ b/back/model-config.json @@ -64,6 +64,9 @@ "EmailUser": { "dataSource": "vn" }, + "Expedition_PrintOut": { + "dataSource": "vn" + }, "Image": { "dataSource": "vn" }, @@ -192,5 +195,8 @@ }, "RouteConfig": { "dataSource": "vn" + }, + "MrwService": { + "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/back/models/collection.js b/back/models/collection.js index f2c2f1566..f91ac7afa 100644 --- a/back/models/collection.js +++ b/back/models/collection.js @@ -3,6 +3,7 @@ module.exports = Self => { require('../methods/collection/setSaleQuantity')(Self); require('../methods/collection/previousLabel')(Self); require('../methods/collection/getTickets')(Self); + require('../methods/collection/assignCollection')(Self); require('../methods/collection/assign')(Self); require('../methods/collection/getSales')(Self); }; diff --git a/back/models/country.json b/back/models/country.json index a4c74d330..5b9d842a8 100644 --- a/back/models/country.json +++ b/back/models/country.json @@ -25,6 +25,9 @@ }, "isSocialNameUnique": { "type": "boolean" + }, + "continentFk": { + "type": "number" } }, "relations": { @@ -32,6 +35,11 @@ "type": "belongsTo", "model": "Currency", "foreignKey": "currencyFk" + }, + "continent": { + "type": "belongsTo", + "model": "Continent", + "foreignKey": "continentFk" } }, "acls": [ diff --git a/back/models/default-view-config.json b/back/models/default-view-config.json index 88164692d..e7d856c17 100644 --- a/back/models/default-view-config.json +++ b/back/models/default-view-config.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "salix.defaultViewConfig" + "table": "salix.defaultViewMultiConfig" } }, "properties": { diff --git a/back/models/expedition_PrintOut.json b/back/models/expedition_PrintOut.json new file mode 100644 index 000000000..23a2fdbc4 --- /dev/null +++ b/back/models/expedition_PrintOut.json @@ -0,0 +1,19 @@ +{ + "name": "Expedition_PrintOut", + "base": "VnModel", + "options": { + "mysql": { + "table": "dipole.expedition_PrintOut" + } + }, + "properties": { + "expeditionFk": { + "type": "number", + "id": true, + "description": "id expeditionFk" + }, + "itemFk": { + "type": "number" + } + } +} \ No newline at end of file diff --git a/back/models/mrw-config.js b/back/models/mrw-config.js index f764b91cc..8bb24dbe5 100644 --- a/back/models/mrw-config.js +++ b/back/models/mrw-config.js @@ -1,4 +1,60 @@ module.exports = Self => { require('../methods/mrw-config/createShipment')(Self); + require('../methods/mrw-config/getLabel')(Self); require('../methods/mrw-config/cancelShipment')(Self); + + const fs = require('fs'); + const ejs = require('ejs'); + const UserError = require('vn-loopback/util/user-error'); + const {DOMParser} = require('xmldom'); + const axios = require('axios'); + + Self.getConfig = async function() { + const mrw = await Self.app.models.MrwConfig.findOne(null); + if (!mrw) throw new UserError(`MRW service is not configured`); + return mrw; + }; + + Self.getTextByTag = function(xmlDoc, tag) { + return xmlDoc?.getElementsByTagName(tag)[0]?.textContent; + }; + + Self.sendXmlDoc = async function(path, params, contentType) { + const parser = new DOMParser(); + + const xmlTemplate = fs.readFileSync(path, 'utf-8'); + const renderedTemplate = ejs.render(xmlTemplate, params); + const data = await axios.post(params.mrw.url, renderedTemplate, { + headers: { + 'Content-Type': `${contentType}; charset=utf-8` + } + }); + return parser.parseFromString(data.data, 'text/xml'); + }; + + Self.getClientType = async function(expeditionFk) { + if (!expeditionFk) throw new UserError(`No expeditionFk defined`); + + const {clientTypeWidth} = await Self.getConfig(); + const result = await Self.app.models.Expedition.findById(expeditionFk, + {include: [{ + relation: 'ticket', + scope: { + include: { + relation: 'agencyMode', + scope: { + include: { + relation: 'mrwService', + } + } + } + } + }]} + ); + const clientType = result?.ticket()?.agencyMode()?.mrwService()?.clientType; + if (!clientType || !clientTypeWidth) throw new UserError(`ClientType not available`); + + return clientType.toString().padStart(clientTypeWidth, '0'); + }; }; + diff --git a/back/models/mrw-config.json b/back/models/mrw-config.json index b0e9754bd..60c0ca2a2 100644 --- a/back/models/mrw-config.json +++ b/back/models/mrw-config.json @@ -39,6 +39,15 @@ }, "defaultWeight": { "type": "number" + }, + "expeditionDeadLine": { + "type": "string" + }, + "notified":{ + "type": "date" + }, + "clientTypeWidth": { + "type": "number" } } } diff --git a/back/models/mrw-service.json b/back/models/mrw-service.json new file mode 100644 index 000000000..1ad72d060 --- /dev/null +++ b/back/models/mrw-service.json @@ -0,0 +1,33 @@ +{ + "name": "MrwService", + "base": "VnModel", + "options": { + "mysql": { + "table": "mrwService" + } + }, + "properties": { + "agencyModeCodeFk": { + "id": true, + "type": "string", + "required": true + }, + "clientType": { + "type": "number", + "required": true + }, + "serviceType": { + "type": "number" + }, + "kg": { + "type": "number" + } + }, + "relations": { + "agency": { + "type": "hasOne", + "model": "AgencyMode", + "foreignKey": "code" + } + } +} diff --git a/back/models/specs/mailAliasAccount.spec.js b/back/models/specs/mailAliasAccount.spec.js index 8f0278a50..0f4cbdbb1 100644 --- a/back/models/specs/mailAliasAccount.spec.js +++ b/back/models/specs/mailAliasAccount.spec.js @@ -1,12 +1,13 @@ const models = require('vn-loopback/server/server').models; describe('loopback model MailAliasAccount', () => { + const ctx = beforeAll.getCtx(); it('should add a mail Alias', async() => { const tx = await models.MailAliasAccount.beginTransaction({}); let error; try { - const options = {transaction: tx, accessToken: {userId: 9}}; + const options = {transaction: tx, ctx}; await models.MailAliasAccount.create({mailAlias: 2, account: 5}, options); await tx.rollback(); @@ -23,7 +24,7 @@ describe('loopback model MailAliasAccount', () => { let error; try { - const options = {transaction: tx, accessToken: {userId: 9}}; + const options = {transaction: tx, ctx}; await models.MailAliasAccount.create({mailAlias: 3, account: 5}, options); await tx.rollback(); diff --git a/back/models/user-config.json b/back/models/user-config.json index 5c5df1b9e..f8e563dc3 100644 --- a/back/models/user-config.json +++ b/back/models/user-config.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "userConfig" + "table": "userMultiConfig" } }, "properties": { diff --git a/back/models/warehouse.json b/back/models/warehouse.json index dcbf7f2d2..54006130b 100644 --- a/back/models/warehouse.json +++ b/back/models/warehouse.json @@ -9,21 +9,36 @@ }, "properties": { "id": { - "id": true, - "type": "number", - "forceId": false + "id": true, + "type": "number", + "forceId": false }, "name": { - "type": "string" + "type": "string" }, "code": { - "type": "string" + "type": "string" }, "isInventory": { - "type": "number" + "type": "number" }, - "isManaged":{ - "type": "boolean" + "isManaged": { + "type": "boolean" + }, + "countryFk": { + "type": "number" + } + }, + "relations": { + "country": { + "type": "belongsTo", + "model": "Country", + "foreignKey": "countryFk" + }, + "address": { + "type": "belongsTo", + "model": "Address", + "foreignKey": "addressFk" } }, "acls": [ @@ -34,5 +49,11 @@ "permission": "ALLOW" } ], - "scope" : {"where": {"isForTicket": {"neq": 0}}} + "scope": { + "where": { + "isForTicket": { + "neq": 0 + } + } + } } diff --git a/back/tests-helper.js b/back/tests-helper.js index 6d465bc2a..96f75f064 100644 --- a/back/tests-helper.js +++ b/back/tests-helper.js @@ -10,7 +10,6 @@ async function init() { host: process.env.DB_HOST, port: process.env.DB_PORT }); - const bootOptions = {dataSources}; await new Promise((resolve, reject) => { app.boot(bootOptions, @@ -33,3 +32,4 @@ module.exports = { if (require.main === module) init(); + diff --git a/back/tests.js b/back/tests.js index 50698eb92..2527367c2 100644 --- a/back/tests.js +++ b/back/tests.js @@ -84,7 +84,7 @@ async function test() { 'loopback/**/*[sS]pec.js', 'modules/*/back/**/*.[sS]pec.js' ], - helpers: [] + helpers: [`back/vn-jasmine.js`], }; if (PARALLEL) { @@ -114,7 +114,6 @@ async function test() { if (opts.ci) runner.jasmine.DEFAULT_TIMEOUT_INTERVAL = SPEC_TIMEOUT; - // runner.loadConfigFile('back/jasmine.json'); runner.loadConfig(config); process.env.SPEC_IS_RUNNING = true; await runner.execute(); diff --git a/back/vn-jasmine.js b/back/vn-jasmine.js new file mode 100644 index 000000000..2b981c6d9 --- /dev/null +++ b/back/vn-jasmine.js @@ -0,0 +1,48 @@ + +const LoopBackContext = require('loopback-context'); +const getAccessToken = (userId = 9) => { + return {accessToken: {userId}}; +}; +const DEFAULT_HEADERS = {headers: {origin: 'http://localhost'}}; +const default_before_all = userId => { + return { + req: { + ...getAccessToken(userId), + ...DEFAULT_HEADERS, + ...{__: value => value} + + }, + args: {} + }; +}; +const default_loopback_ctx = userId => { + return { + ...getAccessToken(userId), + ...default_before_all(userId), + http: { + ...default_before_all(userId) + }, + args: {} + }; +}; + +function vnBeforeAll() { + Object.assign(beforeAll, {getCtx: default_before_all, mockLoopBackContext}); +} + +const mockLoopBackContext = userId => { + const activeCtx = default_loopback_ctx(userId); + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + return activeCtx; +}; +module.exports = { + mockLoopBackContext +}; + +(function init() { + vnBeforeAll(); +})(); diff --git a/db/dump/.dump/data.sql b/db/dump/.dump/data.sql index 18e3fd4b5..43f686022 100644 --- a/db/dump/.dump/data.sql +++ b/db/dump/.dump/data.sql @@ -3,7 +3,7 @@ USE `util`; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -INSERT INTO `version` VALUES ('vn-database','11090','7adf4a373d19ce126adbc7b1077f69a74559c09a','2024-06-11 08:32:36','11094'); +INSERT INTO `version` VALUES ('vn-database','11117','5558e69e648c3819d4a1edf86f8df4b94d36e71a','2024-07-09 07:39:39','11141'); INSERT INTO `versionLog` VALUES ('vn-database','10107','00-firstScript.sql','jenkins@10.0.2.69','2022-04-23 10:53:53',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10112','00-firstScript.sql','jenkins@10.0.2.69','2022-05-09 09:14:53',NULL,NULL); @@ -644,6 +644,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10849','15-invoiceInLog.sql','je INSERT INTO `versionLog` VALUES ('vn-database','10849','16-travelLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10849','17-packingSiteDeviceLog.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:45:55',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10851','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-01-30 13:31:15',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10852','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:37',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10853','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:05',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10853','00-secondScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-02-15 09:46:06',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10854','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-01-30 16:20:34',NULL,NULL); @@ -776,6 +777,7 @@ INSERT INTO `versionLog` VALUES ('vn-database','10975','01-expeditionFk.sql','je INSERT INTO `versionLog` VALUES ('vn-database','10976','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10977','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-04-18 07:40:57',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10978','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:33',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','10983','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:37',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10984','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10988','00-pbx_prefix.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-04-11 17:00:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','10990','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-07 07:31:59',NULL,NULL); @@ -834,19 +836,49 @@ INSERT INTO `versionLog` VALUES ('vn-database','11058','00-firstScript.sql','jen INSERT INTO `versionLog` VALUES ('vn-database','11059','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11060','00-createRoleReviewer.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11061','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11063','00-roadmapAddress.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11063','01-roadmapStop.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11063','02-roadmapStopGrants.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11064','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11065','00-modifyInvoiceInPrivileges.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11065','01-modifyInvoiceInAcls.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11068','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11069','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:34',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11070','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11071','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-28 07:32:48',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11073','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11074','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11075','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-05-28 12:54:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11078','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11079','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 08:22:10',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11080','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-05-31 12:01:58',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11081','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11082','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11083','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-03 10:46:36',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11084','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11086','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-27 10:02:02',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11087','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:38:13',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11089','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11090','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 08:32:35',NULL,NULL); INSERT INTO `versionLog` VALUES ('vn-database','11092','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-07 08:21:23',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11093','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:16',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11096','00-addBuyerAcl.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-11 12:48:51',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11099','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11100','00-modifyTimeControlAcls.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11101','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11102','00-createTravelKgPercentage.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11103','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11104','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11105','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-06-20 15:36:07',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11106','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11109','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-18 19:09:56',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11110','00-clientUnpaid.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11111','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11114','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-06-25 08:39:49',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11116','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11117','00-firstScript.sql','jenkins@db-proxy1.servers.dc.verdnatura.es','2024-07-09 07:39:38',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11134','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-05 11:02:07',NULL,NULL); +INSERT INTO `versionLog` VALUES ('vn-database','11139','00-firstScript.sql','jenkins@db-proxy2.servers.dc.verdnatura.es','2024-07-08 10:58:01',NULL,NULL); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; @@ -930,7 +962,7 @@ INSERT INTO `role` VALUES (109,'salesTeamBoss','Jefe de equipo de comerciales',1 INSERT INTO `role` VALUES (110,'palletizer','Paletizadores',1,'2022-12-02 13:56:22','2022-12-02 13:56:30',NULL); INSERT INTO `role` VALUES (111,'entryEditor','Entry editor',1,'2023-01-13 12:21:55','2023-01-13 12:21:55',NULL); INSERT INTO `role` VALUES (112,'maintenance','Personal de mantenimiento',1,'2023-01-19 07:23:35','2023-01-19 07:23:35',NULL); -INSERT INTO `role` VALUES (114,'maintenanceBos','Jefe de mantenimiento',1,'2023-01-19 07:31:16','2023-05-17 13:07:21',NULL); +INSERT INTO `role` VALUES (114,'maintenanceBoss','Jefe de mantenimiento',1,'2023-01-19 07:31:16','2024-06-14 08:56:41',19295); INSERT INTO `role` VALUES (115,'itManagement','TI management',1,'2023-03-29 09:27:55','2023-03-29 09:28:04',NULL); INSERT INTO `role` VALUES (119,'palletizerBoss','Jefe de paletizadores',1,'2023-06-07 13:51:54','2023-06-07 13:51:54',NULL); INSERT INTO `role` VALUES (120,'developerBoss','Jefe de proyecto de desarrollo',1,'2023-06-19 09:07:21','2023-06-19 09:07:21',21709); @@ -943,6 +975,7 @@ INSERT INTO `role` VALUES (126,'greenhouseBoss','Jefe de invernadero',1,'2023-11 INSERT INTO `role` VALUES (127,'timeControl','Tablet para fichar',1,'2024-01-09 16:36:56','2024-01-09 16:36:56',NULL); INSERT INTO `role` VALUES (129,'buyerAssistant','Comprador que tienes mas permisos para ayudar al buyerBoss en algunas tareas',1,'2024-02-06 06:59:12','2024-02-06 06:59:12',783); INSERT INTO `role` VALUES (130,'reviewer','Revisor de producción',1,'2024-06-11 00:00:00','2024-06-11 00:00:00',10578); +INSERT INTO `role` VALUES (131,'supplier','Privilegios básicos de un proveedor',1,'2024-07-05 10:18:58','2024-07-05 10:18:58',19295); INSERT INTO `roleInherit` VALUES (1,1,2,NULL); INSERT INTO `roleInherit` VALUES (2,1,3,NULL); @@ -1212,6 +1245,9 @@ INSERT INTO `roleInherit` VALUES (367,30,73,NULL); INSERT INTO `roleInherit` VALUES (368,130,49,10578); INSERT INTO `roleInherit` VALUES (369,50,130,10578); INSERT INTO `roleInherit` VALUES (370,72,130,10578); +INSERT INTO `roleInherit` VALUES (371,36,35,NULL); +INSERT INTO `roleInherit` VALUES (372,126,13,19295); +INSERT INTO `roleInherit` VALUES (373,131,2,19295); INSERT INTO `userPassword` VALUES (1,7,1,0,2,1); @@ -1535,7 +1571,7 @@ INSERT INTO `ACL` VALUES (383,'Sector','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (384,'Sector','*','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (385,'Route','driverRoutePdf','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (386,'Route','driverRouteEmail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','customer'); +INSERT INTO `ACL` VALUES (387,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','$owner'); INSERT INTO `ACL` VALUES (388,'Supplier','newSupplier','WRITE','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (389,'ClaimRma','*','READ','ALLOW','ROLE','claimManager'); INSERT INTO `ACL` VALUES (390,'ClaimRma','*','WRITE','ALLOW','ROLE','claimManager'); @@ -1791,10 +1827,6 @@ INSERT INTO `ACL` VALUES (686,'MailForward','*','*','ALLOW','ROLE','hr'); INSERT INTO `ACL` VALUES (687,'ClientSms','find','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (688,'ClientSms','create','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (689,'Vehicle','sorted','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (690,'Roadmap','*','*','ALLOW','ROLE','palletizerBoss'); -INSERT INTO `ACL` VALUES (691,'Roadmap','*','*','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (692,'RoadmapStop','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (693,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (695,'ViaexpressConfig','internationalExpedition','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (696,'ViaexpressConfig','renderer','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (697,'Ticket','transferClient','WRITE','ALLOW','ROLE','administrative'); @@ -1863,7 +1895,7 @@ INSERT INTO `ACL` VALUES (761,'Route','downloadZip','READ','ALLOW','ROLE','emplo INSERT INTO `ACL` VALUES (762,'Route','filter','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (763,'Route','getByWorker','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (764,'Route','getDeliveryPoint','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (765,'Route','getExternalCmrs','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (765,'Route','cmrs','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (766,'Route','getSuggestedTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (767,'Route','getTickets','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (768,'Route','guessPriority','WRITE','ALLOW','ROLE','employee'); @@ -1874,12 +1906,12 @@ INSERT INTO `ACL` VALUES (772,'Route','getExpeditionSummary','READ','ALLOW','ROL INSERT INTO `ACL` VALUES (773,'WorkerTimeControl','login','READ','ALLOW','ROLE','timeControl'); INSERT INTO `ACL` VALUES (774,'WorkerTimeControl','getClockIn','READ','ALLOW','ROLE','timeControl'); INSERT INTO `ACL` VALUES (775,'WorkerTimeControl','clockIn','WRITE','ALLOW','ROLE','timeControl'); -INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateWorkerTimeControlMail','WRITE','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (776,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (777,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (778,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','teamBoss'); +INSERT INTO `ACL` VALUES (779,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','developer'); +INSERT INTO `ACL` VALUES (780,'WorkerTimeControl','updateMailState','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (781,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','teamBoss'); INSERT INTO `ACL` VALUES (782,'WorkerTimeControl','getMailStates','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (783,'WorkerTimeControl','resendWeeklyHourEmail','WRITE','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (784,'VnRole','*','READ','ALLOW','ROLE','employee'); @@ -1929,7 +1961,6 @@ INSERT INTO `ACL` VALUES (830,'InvoiceIn','*','READ','ALLOW','ROLE','deliveryBos INSERT INTO `ACL` VALUES (831,'InvoiceIn','exchangeRateUpdate','*','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (832,'AgencyLog','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (833,'AgencyWorkCenter','*','READ','ALLOW','ROLE','employee'); -INSERT INTO `ACL` VALUES (834,'AgencyMode','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (835,'Agency','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (836,'Agency','*','WRITE','ALLOW','ROLE','deliveryAssistant'); INSERT INTO `ACL` VALUES (837,'AgencyWorkCenter','*','WRITE','ALLOW','ROLE','deliveryAssistant'); @@ -1939,8 +1970,6 @@ INSERT INTO `ACL` VALUES (840,'Locker','*','*','ALLOW','ROLE','hr'); INSERT INTO `ACL` VALUES (841,'Locker','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (842,'Worker','__get__locker','READ','ALLOW','ROLE','hr'); INSERT INTO `ACL` VALUES (843,'Worker','__get__locker','READ','ALLOW','ROLE','productionBoss'); -INSERT INTO `ACL` VALUES (844,'RoadmapStop','*','*','ALLOW','ROLE','production'); -INSERT INTO `ACL` VALUES (845,'RoadmapStop','*','*','ALLOW','ROLE','productionBoss'); INSERT INTO `ACL` VALUES (846,'Ticket','refund','WRITE','ALLOW','ROLE','logistic'); INSERT INTO `ACL` VALUES (847,'RouteConfig','*','READ','ALLOW','ROLE','employee'); INSERT INTO `ACL` VALUES (848,'InvoiceIn','updateInvoiceIn','WRITE','ALLOW','ROLE','administrative'); @@ -1960,6 +1989,37 @@ INSERT INTO `ACL` VALUES (861,'InvoiceIn','toBook','WRITE','ALLOW','ROLE','buyer INSERT INTO `ACL` VALUES (862,'InvoiceIn','deleteById','WRITE','ALLOW','ROLE','buyer'); INSERT INTO `ACL` VALUES (863,'InvoiceIn','create','WRITE','ALLOW','ROLE','administrative'); INSERT INTO `ACL` VALUES (864,'InvoiceIn','create','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (865,'Ticket','deliveryNotePdf','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (866,'InvoiceOut','download','READ','ALLOW','ROLE','$owner'); +INSERT INTO `ACL` VALUES (867,'InvoiceIn','*','READ','ALLOW','ROLE','maintenanceBoss'); +INSERT INTO `ACL` VALUES (868,'InvoiceIn','*','READ','ALLOW','ROLE','maintenanceBos'); +INSERT INTO `ACL` VALUES (869,'Ticket','editZone','WRITE','ALLOW','ROLE','buyer'); +INSERT INTO `ACL` VALUES (870,'Entry','find','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (871,'RoadmapAddress','*','WRITE','ALLOW','ROLE','palletizerBoss'); +INSERT INTO `ACL` VALUES (872,'RoadmapAddress','*','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (873,'Roadmap','*','WRITE','ALLOW','ROLE','palletizerBoss'); +INSERT INTO `ACL` VALUES (874,'Roadmap','*','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (875,'RoadmapStop','*','WRITE','ALLOW','ROLE','palletizerBoss'); +INSERT INTO `ACL` VALUES (876,'RoadmapStop','*','READ','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (877,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (878,'MrwConfig','getLabel','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (879,'AgencyMode','*','*','ALLOW','ROLE','deliveryAssistant'); +INSERT INTO `ACL` VALUES (880,'Collection','assignCollection','WRITE','ALLOW','ROLE','production'); +INSERT INTO `ACL` VALUES (881,'TrainingCourse','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (882,'TrainingCourseType','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (883,'TrainingCenter','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (884,'Worker','__get__trainingCourse','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (885,'WorkerTimeControl','addTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (886,'WorkerTimeControl','deleteTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (887,'WorkerTimeControl','updateTimeEntry','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (888,'WorkerTimeControl','weeklyHourRecordEmail','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (889,'WorkerTimeControl','sendMail','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (890,'WorkerTimeControl','updateMailState','WRITE','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (891,'TravelKgPercentage','*','READ','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (892,'WorkerIncome','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (893,'PayrollComponent','*','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (894,'Worker','__get__incomes','*','ALLOW','ROLE','hr'); +INSERT INTO `ACL` VALUES (895,'ItemShelvingLog','*','READ','ALLOW','ROLE','production'); INSERT INTO `fieldAcl` VALUES (1,'Client','name','update','employee'); INSERT INTO `fieldAcl` VALUES (2,'Client','contact','update','employee'); @@ -2280,7 +2340,7 @@ INSERT INTO `continent` VALUES (3,'África','AF'); INSERT INTO `continent` VALUES (4,'Europa','EU'); INSERT INTO `continent` VALUES (5,'Oceanía','OC'); -INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,25,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (1,'VN','VERDNATURA',1,110,763,0,0,0,0,26,NULL,'/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (22,'shopping','COMPRAS',2,3,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (23,'CMA','CAMARA',13,14,NULL,72,1,1,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (31,'it','INFORMATICA',4,5,NULL,72,0,0,1,0,1,'/1/','informatica-cau',1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); @@ -2291,49 +2351,49 @@ INSERT INTO `department` VALUES (37,'PROD','PRODUCCION',12,35,NULL,72,1,1,1,11,1 INSERT INTO `department` VALUES (38,'picking','SACADO',15,16,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (39,'packing','ENCAJADO',17,18,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (41,'administration','ADMINISTRACION',36,37,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (43,'VT','VENTAS',38,71,NULL,0,0,0,1,16,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (44,'management','GERENCIA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (46,'delivery','REPARTO',76,77,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',78,79,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (43,'VT','VENTAS',38,69,NULL,0,0,0,1,15,1,'/1/',NULL,1,'',1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (44,'management','GERENCIA',70,71,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (45,'logistic','LOGISTICA',72,73,NULL,72,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (46,'delivery','REPARTO',74,75,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (48,'storage','ALMACENAJE',76,77,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (49,NULL,'PROPIEDAD',78,79,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (52,NULL,'CARGA AEREA',80,81,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (53,'marketing','MARKETING Y COMUNICACIÓN',39,40,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',84,85,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (54,NULL,'ORNAMENTALES',82,83,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (55,NULL,'TALLER NATURAL',19,20,14548,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1118,NULL,NULL,NULL); INSERT INTO `department` VALUES (56,NULL,'TALLER ARTIFICIAL',21,22,8470,72,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,1927,NULL,NULL,NULL); -INSERT INTO `department` VALUES (58,'CMP','CAMPOS',86,89,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',90,91,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (58,'CMP','CAMPOS',84,87,NULL,72,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (59,'maintenance','MANTENIMIENTO',88,89,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (60,'claims','RECLAMACIONES',41,42,NULL,72,0,0,2,0,43,'/1/43/',NULL,1,NULL,1,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (61,NULL,'VNH',92,95,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',96,97,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (61,NULL,'VNH',90,93,NULL,73,0,0,1,1,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (66,NULL,'VERDNAMADRID',94,95,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (68,NULL,'COMPLEMENTOS',23,24,NULL,72,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',98,99,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (69,NULL,'VERDNABARNA',96,97,NULL,74,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (80,'spainTeam5','EQUIPO ESPAÑA 5',43,44,4250,0,0,0,2,0,43,'/1/43/','es5_equipo',1,'es5@verdnatura.es',0,0,0,0,NULL,NULL,'5300',NULL); -INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',100,101,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (89,NULL,'COORDINACION',102,103,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (90,NULL,'TRAILER',93,94,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (86,NULL,'LIMPIEZA',98,99,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (89,NULL,'COORDINACION',100,101,NULL,0,1,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (90,NULL,'TRAILER',91,92,NULL,0,0,0,2,0,61,'/1/61/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (91,'artificial','ARTIFICIAL',25,26,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (92,NULL,'EQUIPO SILVERIO',45,46,1203,0,0,0,2,0,43,'/1/43/','sdc_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',47,48,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',0,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); -INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',49,50,24065,0,0,0,2,0,43,'/1/43/','es1_equipo',0,'es1@verdnatura.es',0,0,0,0,NULL,NULL,'5000',NULL); +INSERT INTO `department` VALUES (94,'spainTeam2','EQUIPO ESPAÑA 2',47,48,3797,0,0,0,2,0,43,'/1/43/','es2_equipo',1,'es2@verdnatura.es',0,0,0,0,NULL,NULL,'5100',NULL); +INSERT INTO `department` VALUES (95,'spainTeam1','EQUIPO ESPAÑA 1',49,50,24065,0,0,0,2,0,43,'/1/43/','es1_equipo',1,'es1@verdnatura.es',0,0,0,0,NULL,NULL,'5000',NULL); INSERT INTO `department` VALUES (96,NULL,'EQUIPO C LOPEZ',51,52,4661,0,0,0,2,0,43,'/1/43/','cla_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (115,NULL,'EQUIPO CLAUDI',53,54,3810,0,0,0,2,0,43,'/1/43/','csr_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (123,NULL,'EQUIPO ELENA BASCUÑANA',55,56,7102,0,0,0,2,0,43,'/1/43/','ebt_equipo',0,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',57,58,NULL,72,0,0,2,0,43,'/1/43/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',59,60,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',0,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); +INSERT INTO `department` VALUES (124,NULL,'CONTROL INTERNO',102,103,NULL,72,0,0,1,0,1,'/1/',NULL,0,NULL,1,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (125,'spainTeam3','EQUIPO ESPAÑA 3',57,58,1118,0,0,0,2,0,43,'/1/43/','es3_equipo',1,'es3@verdnatura.es',0,0,0,0,NULL,NULL,'5200',NULL); INSERT INTO `department` VALUES (126,NULL,'PRESERVADO',27,28,NULL,0,0,0,2,0,37,'/1/37/',NULL,0,NULL,0,1,1,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (128,NULL,'PALETIZADO',29,30,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (130,NULL,'REVISION',31,32,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',87,88,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',61,62,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',63,64,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); -INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',65,66,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); +INSERT INTO `department` VALUES (131,'greenhouse','INVERNADERO',85,86,NULL,0,0,0,2,0,58,'/1/58/',NULL,0,NULL,0,1,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (132,NULL,'EQUIPO DC',59,60,1731,0,0,0,2,0,43,'/1/43/','dc_equipo',1,'gestioncomercial@verdnatura.es',0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (133,'franceTeam','EQUIPO FRANCIA',61,62,1731,72,0,0,2,0,43,'/1/43/','fr_equipo',1,'gestionfrancia@verdnatura.es',0,0,0,0,NULL,NULL,'3300',NULL); +INSERT INTO `department` VALUES (134,'portugalTeam','EQUIPO PORTUGAL',63,64,6264,0,0,0,2,0,43,'/1/43/','pt_equipo',1,'portugal@verdnatura.es',0,0,0,0,NULL,NULL,'3500',NULL); INSERT INTO `department` VALUES (135,'routers','ENRUTADORES',104,105,NULL,0,0,0,1,0,1,'/1/',NULL,1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (136,'heavyVehicles','VEHICULOS PESADOS',106,107,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (137,'sorter','SORTER',108,109,NULL,0,0,0,1,0,1,'/1/',NULL,0,NULL,0,0,0,0,NULL,NULL,NULL,NULL); -INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',67,68,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); -INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',69,70,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); +INSERT INTO `department` VALUES (139,'spainTeam4','EQUIPO ESPAÑA 4',65,66,3803,0,0,0,2,0,43,'/1/43/','es4_equipo',1,'es4@verdnatura.es',0,0,0,0,NULL,NULL,'5400',NULL); +INSERT INTO `department` VALUES (140,'hollandTeam','EQUIPO HOLANDA',67,68,NULL,0,0,0,2,0,43,'/1/43/','nl_equipo',1,NULL,0,0,0,0,NULL,NULL,NULL,NULL); INSERT INTO `department` VALUES (141,NULL,'PREVIA',33,34,NULL,0,1,0,2,0,37,'/1/37/',NULL,0,NULL,0,0,0,1,NULL,NULL,NULL,NULL); INSERT INTO `docuware` VALUES (1,'deliveryNote','Albaranes cliente','find','find','N__ALBAR_N',NULL); diff --git a/db/dump/.dump/privileges.sql b/db/dump/.dump/privileges.sql index 00ef1018b..c063df7ae 100644 --- a/db/dump/.dump/privileges.sql +++ b/db/dump/.dump/privileges.sql @@ -259,7 +259,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran' INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','salesPerson','inter','alexm@%','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','albaran_state','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Articles','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','awb','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','awb','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_component','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -281,8 +281,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vncontrol','employee','inter','ale INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb_gestdoc','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','awb','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','agency','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buySource','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','buy_edi','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k03','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi_k04','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -313,7 +311,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Cajas',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','cmrConfig','guillermo@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb_recibida','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','awb','juan@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Compres','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buy_edi','alexm@%','0000-00-00 00:00:00','Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','salix','developer','ACL','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -348,7 +345,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','empresa','alex INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','sectorType','guillermo@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Tintas','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','Movimientos','juan@%','0000-00-00 00:00:00','Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Compres','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','ticket_observation','juan@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Entradas_dits','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','sale','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -364,7 +361,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','tickets_ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','hrBoss','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tickets_gestdoc','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Tickets','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@%','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','Entradas','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyerBoss','Tintas','alexm@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','filtros','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_kop','alexm@%','0000-00-00 00:00:00','Select',''); @@ -372,9 +369,9 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','flight','jenki INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','zones','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','claimManager','warehouse_pickup','jenkins@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessReasonEnd','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','businessCalendar','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','alexm@%','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Entradas','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','buy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','budgetNotes','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','specialLabels','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetDms','alexm@%','0000-00-00 00:00:00','Select,Insert',''); @@ -383,7 +380,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','edi','grafana','offerList','juan@d INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','bookingPlanner','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','budgetInvoiceIn','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','beach','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@%','0000-00-00 00:00:00','Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','business','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_revisar','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Movimientos_mark','alexm@%','0000-00-00 00:00:00','Select,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Movimientos_componentes','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -414,7 +411,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','salesPerson','Movimientos INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','handmadeBoss','Reservas','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyerBoss','bankEntity','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','Ordenes','alexm@%','0000-00-00 00:00:00','Select,Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','awb','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','Origen','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pago','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','awb','alexm@%','0000-00-00 00:00:00','Update',''); @@ -485,7 +481,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','absenceType','alexm@%',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','artificialBoss','Entradas_Auto','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','productionAssi','Vehiculos_consumo','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','employee','tblContadores','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buyMark','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendar','juan@10.5.1.2','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','calendarHolidays','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','claim','alexm@%','0000-00-00 00:00:00','Select',''); @@ -638,7 +633,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeGroup','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','floramondoNotOfferDay__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','fuelType','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeDMS','alexm@%','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','manager','genericAllocation','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppeComponent','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppe','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','glsExpedition__','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -647,7 +641,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','pgcMaster',' INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','itemBarcode','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','host','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticket','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete','Update'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceIn','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','invoiceIn','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','inventoryFailure','alexm@%','0000-00-00 00:00:00','Select',''); @@ -744,7 +738,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','mrw','guille INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','mrwService','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','ppePlan','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','accountingConfig','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@%','0000-00-00 00:00:00','Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','buy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logistic','buy','alexm@%','0000-00-00 00:00:00','Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','saleGoal','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','packager','packingSiteLog','alexm@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Insert',''); @@ -759,9 +753,8 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenance','moving','guill INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDetail','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machineDms','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','claimManager','vehicle','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@%','0000-00-00 00:00:00','Insert,Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','awb','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hrBoss','machine','alexm@%','0000-00-00 00:00:00','Select,Insert,Update',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','buy','juan@db-proxy1.static.verdnatura.es','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','logistic','Entradas_dits','alexm@%','0000-00-00 00:00:00','Insert,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bi','coolerBoss','rotacion','alexm@%','0000-00-00 00:00:00','Select',''); @@ -909,7 +902,6 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketService','a INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminBoss','ticketServiceType','alexm@%','0000-00-00 00:00:00','Select,Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketState','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','ticketStateToday','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','bi','employee','claims_ratio','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','greugeType','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','time','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','ticketWeekly','alexm@%','0000-00-00 00:00:00','Select',''); @@ -982,7 +974,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','invoiceCorre INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ink','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','zone','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','XDiario','alexm@%','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','XDiario','alexm@%','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','XDiario','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','salesAssistant','workerTimeControlMail','alexm@%','0000-00-00 00:00:00','Select,Update',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerTimeControl','alexm@%','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','bi','financial','Greuge_Evolution','alexm@%','0000-00-00 00:00:00','Select',''); @@ -1048,7 +1040,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','userSession','j INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','receipt','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','buy','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','calendarHolidays','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parking','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','parking','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','role','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','errorLogApp','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','continent','juan@db-proxy2.static.verdnatura.es','0000-00-00 00:00:00','Select',''); @@ -1300,7 +1292,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','coolerBoss','itemShelving','g INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','negativeOrigin','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','Vehiculos_consumo','carlosap@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','entryOrder','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','project','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','machineDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','ink','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','supplierDms','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); @@ -1350,7 +1342,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryAssistant','warehouse INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','component','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','config','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','componentType','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','machineDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','priceFixed','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','itemShelvingSale','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','logisticAssist','tagAbbreviation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketTracking','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); @@ -1361,7 +1353,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','productionAssi','sale_freight INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','accounting','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','accounting','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBos','machineDetail','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketRequest','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','vehicleState','jgallego@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','srt','grafana','expeditionState','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','specialPrice','jgallego@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); @@ -1384,6 +1376,7 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','professionalCategor INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','ticketObservation','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Insert',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','comparative','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','invoiceOutExpense','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','delivery','carlosap@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','entry','jenkins@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); @@ -1398,23 +1391,46 @@ INSERT IGNORE INTO `tables_priv` VALUES ('','hedera','grafana','visit','root@lo INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','workerActivity','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicy','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyDetail','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyReview','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financial','bankPolicyReview','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','production','roadmapStop','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','agencyWorkCenter','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','roadmapStop','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert,Update,Delete',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','antenna','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','bufferPool','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','enteringLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','expeditionLoading','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','failureLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','movingLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); -INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBos','sorterLog','guillermo@10.5.1.3','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','greenhouseBoss','business','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','teamBoss','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','ticketServiceType','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','employee','business','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','','Select'); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','supplierAgencyTerm','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','grafana','clientRate','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','entryEditor','Entradas','guillermo@10.5.1.3','0000-00-00 00:00:00','Insert','Update'); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientInforma','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','solunionCAP','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn','administrative','clientUnpaid','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','administrative','pay_dem','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','invoiceOut','guillermo@10.5.1.3','0000-00-00 00:00:00','Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','invoiceOut','guillermo@10.5.1.3','0000-00-00 00:00:00','Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','financialBoss','accountDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','adminOfficer','accountDetail','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Update',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','project','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','maintenanceBoss','machineDetail','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','antenna','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','bufferPool','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','enteringLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','expeditionLoading','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','failureLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','movingLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','srt','maintenanceBoss','sorterLog','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','buyer','genericAllocation','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select,Insert,Update,Delete',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','hr','businessReasonEnd','guillermo@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buy_edi','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','buyer','buySource','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','bi','salesPerson','claims_ratio','alexm@db-proxy2.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_gestdoc','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn2008','deliveryBoss','albaran_state','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNote','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNoteDms','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); +INSERT IGNORE INTO `tables_priv` VALUES ('','vn','deliveryBoss','deliveryNoteState','guillermo@db-proxy1.servers.dc.verdnatura.es','0000-00-00 00:00:00','Select',''); /*!40000 ALTER TABLE `tables_priv` ENABLE KEYS */; /*!40000 ALTER TABLE `columns_priv` DISABLE KEYS */; @@ -1474,28 +1490,10 @@ INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','user_id','0 INSERT IGNORE INTO `columns_priv` VALUES ('','pbx','grafana','sip','extension','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','name','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','account','grafana','user','active','0000-00-00 00:00:00','Select'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','editorFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','expenseFkDeductible','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','withholdingSageFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','isVatDeductible','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','bookEntried','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','siiTrascendencyInvoiceInFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusTaxBreakFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusSubjectOpFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','cplusRectificationTypeFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','siiTypeInvoiceInFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','operated','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','booked','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','docFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','companyFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','created','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','currencyFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','supplierRef','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','issued','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','supplierFk','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','serial','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','serialNumber','0000-00-00 00:00:00','Update'); -INSERT IGNORE INTO `columns_priv` VALUES ('','vn','administrative','invoiceIn','id','0000-00-00 00:00:00','Update'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','workerFk','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','id','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','departmentFk','0000-00-00 00:00:00','Select'); +INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','business','companyCodeFk','0000-00-00 00:00:00','Select'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','routeFk','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','name','0000-00-00 00:00:00','Update'); INSERT IGNORE INTO `columns_priv` VALUES ('','vn','employee','routesMonitor','beachFk','0000-00-00 00:00:00','Update'); @@ -1904,7 +1902,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesAssistant','invoiceoutboo INSERT IGNORE INTO `procs_priv` VALUES ('','vn','administrative','ticket_gettax','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','productionAssi','midnight','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','dipole','employee','expedition_add','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','employee','ticketstateupdate','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','coolerBoss','itempacking','FUNCTION','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','salesPerson','ticket_clone','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','cache','employee','available_refresh','PROCEDURE','alexm@%','Execute','0000-00-00 00:00:00'); @@ -2034,7 +2031,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_hasrouti INSERT IGNORE INTO `procs_priv` VALUES ('','account','grafana','user_hasRole','FUNCTION','jgallego@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','guest','time_generate','PROCEDURE','jenkins@db-proxy2.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addbyclaim','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelvingtransfer','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_addlist','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','itemshelving_selfconsumption','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','production','item_getsimilar','PROCEDURE','alexm@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2086,7 +2082,6 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_add',' INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_getsaledate','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_filterbuyer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addbyclaim','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); -INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelvingtransfer','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_addlist','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','itemshelving_selfconsumption','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','delivery','item_getsimilar','PROCEDURE','guillermo@db-proxy1.static.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2151,6 +2146,7 @@ INSERT IGNORE INTO `procs_priv` VALUES ('','vn','artificialBoss','confection_co INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','remittance_calc','PROCEDURE','alexm@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','util','developer','connection_kill','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financial','client_getRisk','PROCEDURE','jenkins@db-proxy1.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); +INSERT IGNORE INTO `procs_priv` VALUES ('','account','developer','user_hasRole','FUNCTION','root@localhost','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','financialBoss','balance_create','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','hrBoss','balance_create','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); INSERT IGNORE INTO `procs_priv` VALUES ('','vn','claimManager','buy_recalcPricesByEntry','PROCEDURE','jenkins@db-proxy2.servers.dc.verdnatura.es','Execute','0000-00-00 00:00:00'); @@ -2200,7 +2196,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','financial','{\"access\": 0, \"vers INSERT IGNORE INTO `global_priv` VALUES ('','financialBoss','{\"access\": 0, \"version_id\": 101106, \"is_role\": true}'); INSERT IGNORE INTO `global_priv` VALUES ('','floranet','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','grafana','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','greenhouseBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','guest','{\"access\": 0, \"max_questions\": 40000, \"max_updates\": 1000, \"max_connections\": 150000, \"max_user_connections\": 200, \"max_statement_time\": 0.000000, \"is_role\": true, \"version_id\": 101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','handmadeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','hedera-web','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); @@ -2215,8 +2211,8 @@ INSERT IGNORE INTO `global_priv` VALUES ('','logisticAssist','{\"access\":0,\"v INSERT IGNORE INTO `global_priv` VALUES ('','logisticBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenance','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBos','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); -INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','maintenanceBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); +INSERT IGNORE INTO `global_priv` VALUES ('','manager','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketing','{\"access\": 0, \"is_role\": true,\"version_id\":101106}'); INSERT IGNORE INTO `global_priv` VALUES ('','marketingBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','officeBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); @@ -2235,6 +2231,7 @@ INSERT IGNORE INTO `global_priv` VALUES ('','salesPerson','{\"access\": 0, \"is INSERT IGNORE INTO `global_priv` VALUES ('','salesTeamBoss','{\"access\":0,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','salix','{\"access\":33555456,\"version_id\":100707,\"is_role\":true}'); INSERT IGNORE INTO `global_priv` VALUES ('','sysadmin','{\"access\": 201326592, \"is_role\": true, \"version_id\": 100707}'); +INSERT IGNORE INTO `global_priv` VALUES ('','teamBoss','{\"access\":0,\"version_id\":101106,\"is_role\":true}'); /*!40000 ALTER TABLE `global_priv` ENABLE KEYS */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; diff --git a/db/dump/.dump/structure.sql b/db/dump/.dump/structure.sql index dd068cdc7..9b5e9e4a7 100644 --- a/db/dump/.dump/structure.sql +++ b/db/dump/.dump/structure.sql @@ -449,7 +449,6 @@ CREATE TABLE `user` ( `created` timestamp NOT NULL DEFAULT current_timestamp(), `updated` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `image` varchar(255) DEFAULT NULL, - `password__` char(64) NOT NULL COMMENT 'Deprecated', `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT 'Deprecated', `sync` tinyint(4) NOT NULL DEFAULT 0 COMMENT 'Deprecated', `hasGrant` tinyint(1) NOT NULL, @@ -3166,185 +3165,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `claim_ratio_routine` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `claim_ratio_routine`() -BEGIN - DECLARE vMonthToRefund INT DEFAULT 4; - - /* - * PAK 2015-11-20 - * Se trata de añadir a la tabla Greuges todos los - * cargos que luego vamos a utilizar para calcular el recobro - */ - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim ', c.id,' : ', s.concept) - ,round( -1 * ((c.responsibility -1)/4) * s.quantity * - s.price * (100 - s.discount) / 100, 2) - , 4 - , s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn.greuge(shipped, clientFk, description, - amount, greugeTypeFk, ticketFk) - SELECT c.ticketCreated - , c.clientFk - , concat('Claim_mana ',c.id,' : ', s.concept) - ,round( ((c.responsibility -1)/4) * s.quantity * s.price * (100 - s.discount) / 100, 2) - ,3 - ,s.ticketFk - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3 - AND c.isChargedToMana; - - -- Marcamos para no repetir - UPDATE vn.claimEnd ce - JOIN vn.claim c ON c.id = ce.claimFk - SET ce.isGreuge = TRUE - WHERE ce.claimDestinationFk NOT IN (1,5) - AND NOT ce.isGreuge - AND c.claimStateFk = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.id Id_Ticket - FROM vn.saleComponent sc - JOIN vn.sale s ON sc.saleFk = s.id - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.ticketLastState ts ON ts.ticketFk = t.id - JOIN vn.ticketTracking tt ON tt.id = ts.ticketTrackingFk - JOIN vn.state st ON st.id = tt.stateFk - WHERE sc.componentFk = 17 - AND sc.isGreuge = 0 - AND t.shipped >= '2016-10-01' - AND t.shipped < util.VN_CURDATE() - AND st.alertLevel >= 3; - - DELETE g.* - FROM vn.greuge g - JOIN tmp.ticket_list t ON g.ticketFk = t.Id_Ticket - WHERE g.greugeTypeFk = 2; - - INSERT INTO vn.greuge(clientFk, description, amount,shipped, - greugeTypeFk, ticketFk) - SELECT t.clientFk - ,concat('recobro ', s.ticketFk), - round(SUM(sc.value*s.quantity),2) - AS dif, - date(t.shipped) - , 2 - ,tt.Id_Ticket - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.id - JOIN vn.saleComponent sc - ON sc.saleFk = s.id AND sc.componentFk = 17 - GROUP BY t.id - HAVING ABS(dif) > 1; - - UPDATE vn.saleComponent sc - JOIN vn.sale s ON s.id = sc.saleFk - JOIN tmp.ticket_list tt ON tt.Id_Ticket = s.ticketFk - SET sc.isGreuge = 1 - WHERE sc.componentFk = 17; - - /* - * Recalculamos la ratio de las reclamaciones, que luego - * se va a utilizar en el recobro - */ - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT id, 0,0,0,0 - FROM vn.client; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4), 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT c.clientFk, round(sum(-1 * ((c.responsibility -1)/4) * - s.quantity * s.price * (100 - s.discount) / 100)) - AS Reclamaciones - FROM vn.sale s - JOIN vn.claimEnd ce ON ce.saleFk = s.id - JOIN vn.claim c ON c.id = ce.claimFk - WHERE ce.claimDestinationFk NOT IN (1,5) - AND c.claimStateFk = 3 - AND c.ticketCreated >= TIMESTAMPADD(YEAR, -1, util.VN_CURDATE()) - GROUP BY c.clientFk - ) claims ON claims.clientFk = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT clientFk Id_Cliente, IFNULL(SUM(amount), 0) AS Greuge - FROM vn.greuge - WHERE shipped <= util.VN_CURDATE() - GROUP BY clientFk - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(IFNULL(Greuge, 0) / - (IFNULL(Consumo, 0) * vMonthToRefund / 12 ) ,3)); - - -- Protección neonatos - UPDATE bi.claims_ratio cr - JOIN vn.firstTicketShipped fts ON fts.clientFk = cr.Id_Cliente - SET recobro = 0, Ratio = 0 - WHERE fts.shipped > TIMESTAMPADD(MONTH,-1,util.VN_CURDATE()); - - -- CLIENTE 7983, JULIAN SUAU - UPDATE bi.claims_ratio SET recobro = LEAST(0.05, recobro) WHERE Id_Cliente = 7983; - - -- CLIENTE 4358 - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 4358; - - -- CLIENTE 5523, VERDECORA - UPDATE bi.claims_ratio SET recobro = GREATEST(0.12, recobro) WHERE Id_Cliente = 5523; - - -- CLIENTE 15979, SERVEIS VETERINARIS - UPDATE bi.claims_ratio SET recobro = GREATEST(0.05, recobro) WHERE Id_Cliente = 15979; - - -- CLIENTE 5189 i 8942, son de CSR i son el mateix client - UPDATE bi.claims_ratio cr - JOIN (SELECT sum(Consumo * recobro)/sum(Consumo) as recobro - FROM bi.claims_ratio - WHERE Id_Cliente IN ( 5189,8942) - ) sub - SET cr.recobro = sub.recobro - WHERE Id_Cliente IN ( 5189,8942); -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `clean` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -8280,7 +8100,7 @@ BEGIN JOIN vn.address a ON a.id = t.addressFk JOIN vn.province p ON p.id = a.provinceFk LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk LEFT JOIN vn.beach b ON b.code = rm.beachFk LEFT JOIN vn.`zone`z ON z.id = t.zoneFk JOIN vn.agencyMode am ON t.agencyModeFk = am.id @@ -11169,38 +10989,6 @@ CREATE TABLE `recipe` ( -- -- Dumping events for database 'floranet' -- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `clean` */; -DELIMITER ;; -/*!50003 SET @saved_cs_client = @@character_set_client */ ;; -/*!50003 SET @saved_cs_results = @@character_set_results */ ;; -/*!50003 SET @saved_col_connection = @@collation_connection */ ;; -/*!50003 SET character_set_client = utf8mb4 */ ;; -/*!50003 SET character_set_results = utf8mb4 */ ;; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `clean` ON SCHEDULE EVERY 1 DAY STARTS '2024-01-01 23:00:00' ON COMPLETION PRESERVE ENABLE DO BEGIN - DELETE - FROM `order` - WHERE created < CURDATE() - AND isPaid = FALSE; - - DELETE c.* - FROM catalogue c - LEFT JOIN `order` o ON o.catalogueFk = c.id - WHERE c.created < CURDATE() - AND o.id IS NULL; -END */ ;; -/*!50003 SET time_zone = @saved_time_zone */ ;; -/*!50003 SET sql_mode = @saved_sql_mode */ ;; -/*!50003 SET character_set_client = @saved_cs_client */ ;; -/*!50003 SET character_set_results = @saved_cs_results */ ;; -/*!50003 SET collation_connection = @saved_col_connection */ ;; -DELIMITER ; -/*!50106 SET TIME_ZONE= @save_time_zone */ ; -- -- Dumping routines for database 'floranet' @@ -11244,11 +11032,12 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `catalogue_get`(vLanded DATE, vPosta READS SQL DATA proc:BEGIN /** - * Returns list, price and all the stuff regarding the floranet items. + * Returns list, price and all the stuff regarding the floranet items, for the designed shop * * @param vLanded Delivery date * @param vPostalCode Delivery address postal code */ + DECLARE vAddressFk INT; DECLARE vLastCatalogueFk INT; DECLARE vLockName VARCHAR(20); DECLARE vLockTime INT; @@ -11259,7 +11048,7 @@ proc:BEGIN RESIGNAL; END; - + SET vLockName = 'catalogue_get'; SET vLockTime = 15; @@ -11270,6 +11059,15 @@ proc:BEGIN SELECT MAX(id) INTO vLastCatalogueFk FROM catalogue; + SELECT addressFk + INTO vAddressFk + FROM addressPostCode apc + WHERE apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + -- Aquí hay que incluir los criterios de selección de tienda + LIMIT 1; + INSERT INTO catalogue( name, price, @@ -11289,17 +11087,14 @@ proc:BEGIN it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), i.description, - apc.addressFk + vAddressFk FROM vn.item i JOIN (SELECT itemFk, SUM(quantity * cost) price FROM recipe GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - JOIN addressPostCode apc - ON apc.dayOfWeek = dayOfWeek(vLanded) - AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR - AND apc.postCode = vPostalCode - JOIN vn.address a ON a.id = apc.addressFk; + JOIN addressPostCode apc ON addressFk = vAddressFk + JOIN vn.address a ON a.id = vAddressFk; SELECT * FROM catalogue @@ -11499,7 +11294,7 @@ proc:BEGIN vNewTicketFk, c.itemFk, CONCAT('Entrega: ',c.name), - - c.price, + - apc.deliveryCost, 1 FROM catalogue c JOIN addressPostCode apc @@ -11517,7 +11312,7 @@ proc:BEGIN vNewTicketFk, r.elementFk, i.longName, - r.cost, + 0, r.quantity FROM catalogue c JOIN recipe r ON r.itemFk = c.itemFk @@ -13105,7 +12900,7 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `item_getVisible`( vType INT, vPrefix VARCHAR(255)) BEGIN - + /** * Gets visible items of the specified type at specified date. * @@ -13114,7 +12909,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 vn.getInventoryDate(); @@ -13123,13 +12918,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; @@ -13174,9 +12969,10 @@ BEGIN FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id + JOIN vn.alertLevel al ON al.code = 'DELIVERED' WHERE t.shipped BETWEEN vDateInv AND util.VN_CURDATE() AND t.warehouseFk = vWarehouse - AND s.alertLevel = 3 + AND s.alertLevel = al.id ) t GROUP BY itemFk HAVING quantity > 0; @@ -13208,7 +13004,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.packagingFk @@ -14618,7 +14414,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 @@ -14677,6 +14473,7 @@ BEGIN ) SELECT t.id INTO vTicket FROM vn.ticket t + JOIN vn.alertLevel al ON al.code = 'FREE' LEFT JOIN tPrevia tp ON tp.ticketFk = t.id LEFT JOIN vn.ticketState tls on tls.ticketFk = t.id JOIN hedera.`order` o @@ -14687,7 +14484,7 @@ BEGIN WHERE o.id = vSelf AND t.refFk IS NULL AND tp.ticketFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 + AND (tls.alertLevel IS NULL OR tls.alertLevel = al.id) LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado @@ -17013,6 +16810,22 @@ SET character_set_client = utf8; 1 AS `companyFk` */; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `clientSupplier` +-- + +DROP TABLE IF EXISTS `clientSupplier`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientSupplier` ( + `companyFk` smallint(6) NOT NULL, + `type` enum('C','P') NOT NULL, + `idClientSupplier` int(11) NOT NULL, + `isSync` tinyint(1) NOT NULL DEFAULT 0, + PRIMARY KEY (`companyFk`,`idClientSupplier`,`type`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_general_ci COMMENT='Clients and suppliers present in Sage and their synchronization status'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `clientesProveedores` -- @@ -17596,7 +17409,8 @@ BEGIN DECLARE vTransactionExportTaxFreeFk INT; DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; DECLARE vInvoiceTypeInformativeCode VARCHAR(1); - DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2) ; + DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); + DECLARE vCompanyCode INT; SELECT SiglaNacion INTO vCountryCanariasCode FROM Naciones @@ -17606,9 +17420,6 @@ BEGIN FROM Naciones WHERE Nacion ='CEUTA Y MELILLA'; - SELECT pendingServiceTransactionTypeFk INTO vDuaTransactionFk - FROM config; - SELECT id INTO vTaxImportFk FROM taxType WHERE code = 'import21'; @@ -17621,10 +17432,14 @@ BEGIN FROM taxType WHERE code = 'import4'; - SELECT definitiveExportTransactionTypeFk INTO vTransactionExportFk - FROM config; - - SELECT shipmentTransactionTypeFk INTO vTransactionExportTaxFreeFk + SELECT shipmentTransactionTypeFk, + definitiveExportTransactionTypeFk, + pendingServiceTransactionTypeFk, + company_getCode(vCompanyFk) + INTO vTransactionExportTaxFreeFk, + vTransactionExportFk, + vDuaTransactionFk, + vCompanyCode FROM config; SELECT codeSage INTO vInvoiceTypeInformativeCode @@ -17639,8 +17454,6 @@ BEGIN WHERE enlazadoSage = FALSE AND Asiento <> 1 ; - CALL clientSupplier_add(vCompanyFk); - CALL pgc_add(vCompanyFk); CALL invoiceOut_manager(vYear, vCompanyFk); CALL invoiceIn_manager(vYear, vCompanyFk); @@ -17733,7 +17546,7 @@ BEGIN ) SELECT 'EN' TipoEntrada, YEAR(x.FECHA) Ejercicio, - company_getCode(vCompanyFk) AS CodigoEmpresa, + vCompanyCode CodigoEmpresa, x.ASIEN Asiento, IF(EURODEBE <> 0 OR (EURODEBE = 0 AND EUROHABER IS NULL), 'D', 'H') CargoAbono, @@ -17866,20 +17679,6 @@ BEGIN WHERE m.CargoAbono = 'D' AND m.enlazadoSage = FALSE; --- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación - DELETE cp - FROM clientesProveedores cp - LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta - AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL; - --- Elimina cuentas contables que no se utilizarán en la importación - DELETE pc - FROM planCuentasPGC pc - LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta - AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL; - -- DUAS UPDATE movConta mci JOIN vn.XDiario x ON x.ASIEN = mci.Asiento @@ -17986,6 +17785,56 @@ BEGIN AND importeDivisa > 0 AND ImporteAsiento < 0; + CREATE OR REPLACE TEMPORARY TABLE tmp.clientSupplier + (INDEX(idClientSupplier, `type`)) + ENGINE = MEMORY + WITH client AS( + SELECT DISTINCT c.id + FROM sage.movConta mc + JOIN vn.client c ON c.accountingAccount = mc.CodigoCuenta + WHERE NOT enlazadoSage + ),supplier AS( + SELECT DISTINCT s.id + FROM sage.movConta mc + JOIN vn.supplier s ON s.account = mc.CodigoCuenta + WHERE NOT enlazadoSage + ),clientSupplierSync AS( + SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE isSync + ) + SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE NOT isSync + UNION + SELECT id, 'C' + FROM client c + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = c.id + AND cs.Type ='C' + WHERE cs.idClientSupplier IS NULL + UNION + SELECT id, 'P' + FROM supplier s + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = s.id + AND cs.Type ='P' + WHERE cs.idClientSupplier IS NULL; + + CALL clientSupplier_add(vCompanyFk); + + INSERT IGNORE INTO sage.clientSupplier (companyFk, `type`, idClientSupplier, isSync) + SELECT vCompanyCode, `type`, idClientSupplier, FALSE + FROM tmp.clientSupplier; + + DROP TEMPORARY TABLE tmp.clientSupplier; + + CALL pgc_add(vCompanyFk); +-- Elimina cuentas contables que no se utilizarán en la importación + DELETE pc + FROM planCuentasPGC pc + LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta + AND mc.enlazadoSage = FALSE + WHERE mc.codigoCuenta IS NULL; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18027,13 +17876,18 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`(vCompanyFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `clientSupplier_add`( + vCompanyFk INT +) BEGIN /** - * Prepara los datos de clientes y proveedores para exportarlos a Sage - * @vCompanyFk Empresa dela que se quiere trasladar datos + * Inserta en la tabla sage.clientesProveedores los datos de clientes y proveedores + * que se actualizaran o se daran de alta en Sage + * @vCompanyFk Id de empresa + * @table tmp.clientSupplier(idClientSupplier, `type`) */ DECLARE vCountryCeutaMelillaFk INT; + DECLARE vCompanyCode INT DEFAULT company_getCode(vCompanyFk); DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); SELECT SiglaNacion INTO vCountryCanariasCode @@ -18073,7 +17927,7 @@ BEGIN Email1, iban) SELECT - company_getCode(vCompanyFk), + vCompanyCode, 'C', c.id, c.socialName, @@ -18081,7 +17935,7 @@ BEGIN IFNULL(c.street, ''), c.accountingAccount, @fi := IF(cu.code = LEFT(TRIM(c.fi), 2) AND c.isVies, MID(TRIM(c.fi), 3, LENGTH(TRIM(c.fi))-1), TRIM(c.fi)), - IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), + IF(c.isVies, CONCAT(IFNULL(cu.viesCode,cu.code), @fi ), TRIM(c.fi)), IFNULL(c.postcode, ''), IFNULL(c.city, ''), IFNULL(pr.CodigoProvincia, ''), @@ -18103,15 +17957,14 @@ BEGIN IFNULL(SUBSTR(c.email, 1, LOCATE(',', CONCAT(c.email, ','))-1), ''), IFNULL(c.iban, '') FROM vn.`client` c - JOIN clientLastTwoMonths clm ON clm.clientFk = c.id + JOIN tmp.clientSupplier cs ON cs.idClientSupplier = c.id LEFT JOIN vn.country cu ON cu.id = c.countryFk LEFT JOIN Naciones n ON n.countryFk = cu.id LEFT JOIN vn.province p ON p.id = c.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id - WHERE c.isRelevant - AND clm.companyFk = vCompanyFk + WHERE cs.type = 'C' UNION ALL - SELECT company_getCode(vCompanyFk), + SELECT vCompanyCode, 'P', s.id, s.name, @@ -18135,19 +17988,17 @@ BEGIN IFNULL(s.transactionTypeSageFk, 0), IFNULL(s.withholdingSageFk, '0'), IFNULL(SUBSTR(sc.email, 1, (COALESCE(NULLIF(LOCATE(',', sc.email), 0), 99) - 1)), ''), - IFNULL(iban, '') + IFNULL(sa.iban, '') FROM vn.supplier s - JOIN supplierLastThreeMonths pl ON pl.supplierFk = s.id + JOIN tmp.clientSupplier cs ON cs.idClientSupplier = s.id LEFT JOIN vn.country co ON co.id = s.countryFk LEFT JOIN Naciones n ON n.countryFk = co.id LEFT JOIN vn.province p ON p.id = s.provinceFk LEFT JOIN Provincias pr ON pr.provinceFk = p.id LEFT JOIN vn.supplierContact sc ON sc.supplierFk = s.id LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id - WHERE pl.companyFk = vCompanyFk AND - s.isActive AND - s.nif <> '' - GROUP BY pl.supplierFk, pl.companyFk; + WHERE cs.type = 'P' + GROUP BY s.id; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20439,7 +20290,7 @@ BEGIN 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 t.routeFk = rm.routeFk - LEFT JOIN vn.roadmapStop rs ON rm.expeditionTruckFk = rs.id + LEFT JOIN vn.roadmapStop rs ON rm.roadmapStopFk = rs.id WHERE e.id = vExpeditionFk; RETURN vDayMinute; @@ -23592,12 +23443,13 @@ BEGIN m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked + m.isPicked OR s.alertLevel > al.id isPicked FROM vn.sale m JOIN vn.ticket t ON t.id = m.ticketFk JOIN vn.ticketState s ON s.ticketFk = t.id JOIN vn.item i ON i.id = m.itemFk JOIN vn.itemType tp ON tp.id = i.typeFk + JOIN vn.alertLevel al ON al.code = 'ON_PREPARATION' WHERE ( vTableId IS NULL OR (vTableName = 'ticket' AND t.id = vTableId) @@ -25637,7 +25489,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `debugAdd`(vVariable VARCHAR(255), vValue VARCHAR(255)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `debugAdd`( + vVariable VARCHAR(255), + vValue TEXT +) MODIFIES SQL DATA BEGIN /** @@ -28029,6 +27884,8 @@ DROP TABLE IF EXISTS `claimConfig`; CREATE TABLE `claimConfig` ( `id` int(10) unsigned NOT NULL, `maxResponsibility` int(11) DEFAULT NULL, + `monthsToRefund` int(11) DEFAULT NULL, + `minShipped` date DEFAULT NULL, PRIMARY KEY (`id`), CONSTRAINT `claimConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -28365,7 +28222,7 @@ CREATE TABLE `client` ( `transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa', `lastSalesPersonFk` int(10) unsigned DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo', `businessTypeFk` varchar(20) NOT NULL DEFAULT 'florist', - `hasIncoterms` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Received incoterms authorization from client', + `hasIncoterms__` tinyint(1) NOT NULL DEFAULT 0 COMMENT '@deprecated 2024-06-12 refs #7545 Received incoterms authorization from client', `rating` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa', `recommendedCredit` int(10) unsigned DEFAULT NULL COMMENT 'información proporcionada por Informa', `editorFk` int(10) unsigned DEFAULT NULL, @@ -28592,7 +28449,7 @@ CREATE TABLE `clientLog` ( `action` set('insert','update','delete') NOT NULL, `creationDate` timestamp NULL DEFAULT current_timestamp(), `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, - `changedModel` enum('Client','Address','ClientContact','ClientDms','ClientObservation','ClientSample','Greuge','Recovery','TpvTransaction','WorkerDms','Sms') NOT NULL DEFAULT 'Client', + `changedModel` enum('Client','Address','ClientContact','ClientDms','ClientObservation','ClientSample','ClientUnpaid','Greuge','Recovery','TpvTransaction','WorkerDms','Sms') NOT NULL DEFAULT 'Client', `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), `changedModelId` int(11) NOT NULL, @@ -28706,6 +28563,24 @@ CREATE TABLE `clientProtected` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Lista de clientes y comerciales que no se van a ver afectados por las desagsignaciones mensuales automaticas'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `clientRate` +-- + +DROP TABLE IF EXISTS `clientRate`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientRate` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `clientFk` int(11) NOT NULL, + `dated` date NOT NULL DEFAULT current_timestamp(), + `value` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `clientRate_unique` (`clientFk`,`dated`), + CONSTRAINT `clientRate_client_FK` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `clientRisk` -- @@ -28801,7 +28676,10 @@ CREATE TABLE `clientUnpaid` ( `clientFk` int(11) NOT NULL, `dated` date NOT NULL, `amount` double DEFAULT 0, + `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`clientFk`), + KEY `ClientUnpaid_editorFk` (`editorFk`), + CONSTRAINT `ClientUnpaid_editorFk` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), CONSTRAINT `clientUnpaid_clientFk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -29567,7 +29445,6 @@ CREATE TABLE `country` ( `continentFk` tinyint(4) DEFAULT NULL, `a3Code` int(11) DEFAULT NULL COMMENT 'Código país para a3', `isSocialNameUnique` tinyint(1) NOT NULL DEFAULT 1, - `country` varchar(25) GENERATED ALWAYS AS (`name`) VIRTUAL, PRIMARY KEY (`id`), UNIQUE KEY `country_unique` (`code`), KEY `Id_Paisreal` (`politicalCountryFk__`), @@ -31063,7 +30940,7 @@ SET character_set_client = utf8; 1 AS `routeFk`, 1 AS `scanFk`, 1 AS `expeditionFk`, - 1 AS `expeditionTruckFk`, + 1 AS `roadmapStopFk`, 1 AS `warehouseFk`, 1 AS `lastPacked`, 1 AS `ticketFk` */; @@ -31233,6 +31110,7 @@ CREATE TABLE `expeditionState` ( `expeditionFk` int(11) NOT NULL, `typeFk` int(11) NOT NULL, `userFk` int(11) DEFAULT NULL, + `isScanned` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`id`), KEY `expeditionState_FK` (`expeditionFk`), KEY `expeditionState_FK_1` (`typeFk`), @@ -31324,7 +31202,6 @@ SET character_set_client = utf8; /*!50001 CREATE VIEW `expeditionTruck` AS SELECT 1 AS `id`, 1 AS `roadmapFk`, - 1 AS `warehouseFk`, 1 AS `eta`, 1 AS `description`, 1 AS `bufferFk`, @@ -31332,68 +31209,6 @@ SET character_set_client = utf8; 1 AS `userFk` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `expeditionTruck_Control` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control` AS SELECT - 1 AS `id`, - 1 AS `ETD`, - 1 AS `description`, - 1 AS `ticketsSinBultos`, - 1 AS `pallets`, - 1 AS `routes`, - 1 AS `scans`, - 1 AS `expeditions`, - 1 AS `fallos`, - 1 AS `lastPacked` */; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control_Detail` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control_Detail`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control_Detail` AS SELECT - 1 AS `id`, - 1 AS `eta`, - 1 AS `destino`, - 1 AS `pallet`, - 1 AS `routes`, - 1 AS `scans`, - 1 AS `destinos`, - 1 AS `fallos`, - 1 AS `lastPacked` */; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control_Detail_Pallet` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control_Detail_Pallet`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control_Detail_Pallet` AS SELECT - 1 AS `id`, - 1 AS `eta`, - 1 AS `destino`, - 1 AS `pallet`, - 1 AS `route`, - 1 AS `scans`, - 1 AS `destinos`, - 1 AS `fallos`, - 1 AS `expeditionTruckFk`, - 1 AS `lastPacked` */; -SET character_set_client = @saved_cs_client; - -- -- Table structure for table `expense` -- @@ -31628,13 +31443,13 @@ CREATE TABLE `floramondoConfig` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `forecastedBalance` +-- Table structure for table `forecastedBalance__` -- -DROP TABLE IF EXISTS `forecastedBalance`; +DROP TABLE IF EXISTS `forecastedBalance__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `forecastedBalance` ( +CREATE TABLE `forecastedBalance__` ( `id` int(11) NOT NULL AUTO_INCREMENT, `description` varchar(45) DEFAULT NULL, `amount` double NOT NULL DEFAULT 0, @@ -31647,7 +31462,7 @@ CREATE TABLE `forecastedBalance` ( KEY `empresa_prevision_idx` (`companyFk`), CONSTRAINT `Saldos_PrevisionCompany_Fk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, CONSTRAINT `banco_prevision` FOREIGN KEY (`accountingFk`) REFERENCES `accounting` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Aqui ponemos los gastos e ingresos pendientes de introducir '; +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='@deprecated 2024-05-21'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -33196,12 +33011,13 @@ CREATE TABLE `itemShelving` ( `isChecked` tinyint(1) DEFAULT NULL COMMENT 'Este valor cambia al escanear un carro. True: Existe. False: Nuevo. Null: No escaneado', `buyFk` int(11) DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, + `available` int(11) DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `itemShelving_UN` (`buyFk`,`shelvingFk`), KEY `itemShelving_fk1_idx` (`itemFk`), KEY `itemShelving_fk2_idx` (`shelvingFk`), KEY `itemShelving_fk3_idx` (`packagingFk`), KEY `itemShelving_fk3_idx1` (`userFk`), + KEY `itemShelvingBuy_FK` (`buyFk`), CONSTRAINT `itemShelvingBuy_FK` FOREIGN KEY (`buyFk`) REFERENCES `buy` (`id`), CONSTRAINT `itemShelving_fk1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `itemShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE, @@ -33365,6 +33181,21 @@ CREATE TABLE `itemShelvingSale` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Detalle del producto que se retira de los carros, relacionando la linea de movimiento correspondiente'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `itemShelvingSaleReserve` +-- + +DROP TABLE IF EXISTS `itemShelvingSaleReserve`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `itemShelvingSaleReserve` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `itemShelvingSaleReserve_ibfk_1` (`saleFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Queue of changed itemShelvingSale to reserve'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `itemShelvingSaleSum` -- @@ -34355,6 +34186,8 @@ CREATE TABLE `mrwConfig` ( `counterWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', `serviceTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', `portugalPostCodeTrim` int(10) unsigned DEFAULT NULL COMMENT 'It will trim the last characters of the postal code', + `notified` timestamp NULL DEFAULT NULL COMMENT 'Date when it was notified that the web service deadline was exceeded', + `clientTypeWidth` int(10) unsigned DEFAULT NULL COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.', PRIMARY KEY (`id`), CONSTRAINT `mrwConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; @@ -34512,6 +34345,7 @@ CREATE TABLE `operator` ( `labelerFk` int(10) unsigned DEFAULT NULL, `linesLimit` int(11) DEFAULT 20 COMMENT 'Límite de lineas en una colección para la asignación de pedidos', `volumeLimit` decimal(10,6) DEFAULT 0.500000 COMMENT 'Límite de volumen en una colección para la asignación de pedidos', + `isOnReservationMode` tinyint(1) NOT NULL DEFAULT 0, PRIMARY KEY (`workerFk`), KEY `operator_FK` (`workerFk`), KEY `operator_FK_1` (`trainFk`), @@ -35003,7 +34837,7 @@ CREATE TABLE `parking` ( UNIQUE KEY `code_UNIQUE` (`code`), KEY `parking_fk1_idx` (`sectorFk`), CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` like '%-%') + CONSTRAINT `chkParkingCodeFormat` CHECK (char_length(`code`) > 4 and `code` regexp '^[^ ]+-[^ ]+$') ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Tabla con los parkings del altillo'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -35791,7 +35625,6 @@ CREATE TABLE `productionConfig` ( `pendingCollectionsAge` tinyint(3) unsigned DEFAULT 6, `maxNotAssignedCollectionLifeTime` time NOT NULL DEFAULT '00:10:00' COMMENT 'Tiempo de vida de las colecciones sin asignar. Cuando se supera son eliminadas', `maxProductionScopeDays` int(11) NOT NULL DEFAULT 1 COMMENT 'maximo numero de dias en F11', - `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', `stockScopeDays` int(11) DEFAULT 1 COMMENT 'Días a futuro al revisar el stock', `shortageAddressFk` int(11) DEFAULT NULL COMMENT 'Consignatario por defecto para añadir un item de alta', `clientSelfConsumptionFk` int(11) DEFAULT NULL COMMENT 'Cliente para crear el ticket de autoconsumo', @@ -35804,13 +35637,21 @@ CREATE TABLE `productionConfig` ( `defaultSectorFk` int(10) unsigned NOT NULL DEFAULT 37 COMMENT 'Default sector', `scannableCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode', `scannablePreviusCodeType` enum('qr','barcode') NOT NULL DEFAULT 'barcode', + `itemOlderReviewHours` int(11) NOT NULL DEFAULT 0 COMMENT 'Horas que se tienen en cuenta para comprobar si un ítem es más viejo.', + `sectorFromCode` varchar(15) DEFAULT NULL COMMENT 'Sector origen que se revisa ítems más nuevos al parkinear', + `sectorToCode` varchar(15) DEFAULT NULL COMMENT 'Sector destino que se revisa ítems más nuevos al parkinear', + `orderMode` enum('Location','Age') NOT NULL DEFAULT 'Location', PRIMARY KEY (`id`), KEY `productionConfig_FK` (`shortageAddressFk`), KEY `productionConfig_FK_1` (`clientSelfConsumptionFk`), KEY `productionConfig_FK_2` (`addressSelfConsumptionFk`), + KEY `productionConfig_sector_FK` (`sectorFromCode`), + KEY `productionConfig_sector_FK_1` (`sectorToCode`), CONSTRAINT `productionConfig_FK` FOREIGN KEY (`shortageAddressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, CONSTRAINT `productionConfig_FK_1` FOREIGN KEY (`clientSelfConsumptionFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `productionConfig_FK_2` FOREIGN KEY (`addressSelfConsumptionFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE, + CONSTRAINT `productionConfig_sector_FK` FOREIGN KEY (`sectorFromCode`) REFERENCES `sector` (`code`) ON UPDATE CASCADE, + CONSTRAINT `productionConfig_sector_FK_1` FOREIGN KEY (`sectorToCode`) REFERENCES `sector` (`code`) ON UPDATE CASCADE, CONSTRAINT `productionConfig_check` CHECK (`id` = 1) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Recoge los parámetros que condicionan la producción'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36465,6 +36306,10 @@ CREATE TABLE `roadmap` ( `userFk` int(10) unsigned DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, `driverName` varchar(45) DEFAULT NULL, + `kmStart` mediumint(9) DEFAULT NULL, + `kmEnd` mediumint(9) DEFAULT NULL, + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, PRIMARY KEY (`id`), KEY `userFk` (`userFk`), KEY `roadmap_supplierFk` (`supplierFk`), @@ -36473,6 +36318,21 @@ CREATE TABLE `roadmap` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Troncales diarios que se contratan'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `roadmapAddress` +-- + +DROP TABLE IF EXISTS `roadmapAddress`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `roadmapAddress` ( + `addressFk` int(11) NOT NULL, + `isActive` tinyint(4) DEFAULT 1, + PRIMARY KEY (`addressFk`), + CONSTRAINT `roadmapAddress_address_FK` FOREIGN KEY (`addressFk`) REFERENCES `address` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Direcciones de los troncales'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `roadmapStop` -- @@ -36483,7 +36343,7 @@ DROP TABLE IF EXISTS `roadmapStop`; CREATE TABLE `roadmapStop` ( `id` int(11) NOT NULL AUTO_INCREMENT, `roadmapFk` int(10) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned DEFAULT NULL, + `addressFk` int(11) DEFAULT NULL, `eta` datetime DEFAULT NULL COMMENT 'Estimated time of arrival', `description` varchar(45) NOT NULL, `bufferFk` int(11) DEFAULT NULL COMMENT 'buffer destino de las cajas', @@ -36492,13 +36352,13 @@ CREATE TABLE `roadmapStop` ( PRIMARY KEY (`id`), KEY `expeditionTruck_idx1` (`eta`), KEY `expeditionTruck_FK` (`bufferFk`), - KEY `expeditionTruck_FK_1` (`warehouseFk`), KEY `expeditionTruck_FK_2` (`roadmapFk`), KEY `expeditionTruck_FK_3` (`userFk`), + KEY `roadmapStop_roadmapAddress_FK` (`addressFk`), CONSTRAINT `expeditionTruck_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, CONSTRAINT `expeditionTruck_FK_2` FOREIGN KEY (`roadmapFk`) REFERENCES `roadmap` (`id`) ON UPDATE CASCADE, - CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE + CONSTRAINT `expeditionTruck_FK_3` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON UPDATE CASCADE, + CONSTRAINT `roadmapStop_roadmapAddress_FK` FOREIGN KEY (`addressFk`) REFERENCES `roadmapAddress` (`addressFk`) ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci COMMENT='Distintas paradas que hacen los trocales'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -36872,7 +36732,7 @@ CREATE TABLE `routesMonitor` ( `m3` decimal(10,1) DEFAULT NULL, `priority` int(11) NOT NULL DEFAULT 0, `etd` time DEFAULT NULL, - `expeditionTruckFk` int(11) DEFAULT NULL, + `roadmapStopFk` int(11) DEFAULT NULL, `m3boxes` decimal(10,1) DEFAULT NULL, `bufferFk` int(11) DEFAULT NULL COMMENT 'Buffer del sorter por el que se quiere sacar esa ruta', `isPickingAllowed` tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Los tickets de esta ruta se pueden preparar', @@ -36881,12 +36741,12 @@ CREATE TABLE `routesMonitor` ( KEY `routesMonitor_FK` (`bufferFk`), KEY `routesMonitor_FK_2` (`beachFk`), KEY `routesMonitor_FK_1` (`dockFk`), - KEY `routesMonitor_FK_3` (`expeditionTruckFk`), + KEY `routesMonitor_FK_3` (`roadmapStopFk`), KEY `routesMonitor_fk_editor` (`editorFk`), CONSTRAINT `routesMonitor_FK` FOREIGN KEY (`bufferFk`) REFERENCES `srt`.`buffer` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `routesMonitor_FK_1` FOREIGN KEY (`dockFk`) REFERENCES `dock` (`code`) ON UPDATE CASCADE, CONSTRAINT `routesMonitor_FK_2` FOREIGN KEY (`beachFk`) REFERENCES `beach` (`code`) ON UPDATE CASCADE, - CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`expeditionTruckFk`) REFERENCES `roadmapStop` (`id`) ON UPDATE CASCADE, + CONSTRAINT `routesMonitor_FK_3` FOREIGN KEY (`roadmapStopFk`) REFERENCES `roadmapStop` (`id`) ON UPDATE CASCADE, CONSTRAINT `routesMonitor_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39128,16 +38988,13 @@ CREATE TABLE `ticketPackaging` ( `quantity` int(10) DEFAULT 0, `created` timestamp NOT NULL DEFAULT current_timestamp(), `pvp` double DEFAULT NULL, - `workerFk` int(10) unsigned DEFAULT NULL, `editorFk` int(10) unsigned DEFAULT NULL, PRIMARY KEY (`id`), KEY `ticketPackaging_fk1_idx` (`ticketFk`), KEY `ticketPackaging_fk2_idx` (`packagingFk`), - KEY `ticketPackaging_fk3_idx` (`workerFk`), KEY `ticketPackaging_fk_editor` (`editorFk`), CONSTRAINT `ticketPackaging_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, - CONSTRAINT `ticketPackaging_fk3` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `ticketPackaging_fk_editor` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39160,7 +39017,7 @@ CREATE TABLE `ticketPackagingStartingStock` ( KEY `ticketPackagingStartingStock_fk2_idx` (`packagingFk`), KEY `ticketPackagingStartingStock_fk3_idx` (`itemFk`), CONSTRAINT `ticketPackagingStartingStock_fk1` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `packaging` (`id`) ON UPDATE CASCADE, CONSTRAINT `ticketPackagingStartingStock_fk3` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -39554,6 +39411,21 @@ CREATE TABLE `tillConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `tillSerial` +-- + +DROP TABLE IF EXISTS `tillSerial`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `tillSerial` ( + `code` varchar(2) NOT NULL, + `description` varchar(30) DEFAULT NULL, + `account` varchar(10) DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `time` -- @@ -39879,6 +39751,20 @@ CREATE TABLE `travelConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `travelKgPercentage` +-- + +DROP TABLE IF EXISTS `travelKgPercentage`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `travelKgPercentage` ( + `value` int(3) NOT NULL, + `className` varchar(50) DEFAULT NULL, + PRIMARY KEY (`value`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `travelLog` -- @@ -41951,6 +41837,24 @@ END */ ;; /*!50003 SET character_set_client = @saved_cs_client */ ;; /*!50003 SET character_set_results = @saved_cs_results */ ;; /*!50003 SET collation_connection = @saved_col_connection */ ;; +/*!50106 DROP EVENT IF EXISTS `itemShelvingSale_doReserve` */;; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`localhost`*/ /*!50106 EVENT `itemShelvingSale_doReserve` ON SCHEDULE EVERY 15 SECOND STARTS '2023-10-16 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.itemShelvingSale_doReserve */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; /*!50106 DROP EVENT IF EXISTS `mysqlConnectionsSorter_kill` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; @@ -45195,6 +45099,44 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP FUNCTION IF EXISTS `sectorCollection_hasSalesReserved` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` FUNCTION `sectorCollection_hasSalesReserved`(vSelf INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Devuelve si sectorCollection tiene reservas + * @param vSelf Id de sectorCollection + * + * returns BOOLEAN + */ + DECLARE vHasSalesReserved BOOLEAN; + + SELECT DISTINCT COUNT(*) INTO vHasSalesReserved + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk + JOIN saleGroup sg ON sg.id = scsg.saleGroupFk + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN sale s ON s.id = sgd.saleFk + JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN saleTracking st ON st.saleFk = s.id + WHERE sc.id = vSelf; + + RETURN vHasSalesReserved; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP FUNCTION IF EXISTS `specie_IsForbidden` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -45766,62 +45708,42 @@ DELIMITER ; 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; +BEGIN +/** + * Devuelve el número de ticket / collection / sectorCollection consultando + * en que tabla se encuantra en la última semana + * + * @param vParamFk Número a validar + * @return vReturn Identificador validado + */ + DECLARE vReturn INT DEFAULT NULL; + DECLARE vDated DATE; - -- 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 - WHERE sg.id = vParamFk - AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) - LIMIT 1; - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SET vDated = util.VN_CURDATE() - INTERVAL 1 WEEK; - -- Tabla vn.collection - SELECT c.id INTO vValidFk - 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; + SELECT COALESCE( + (SELECT s.ticketFk + FROM sale s + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + WHERE sg.id = vParamFk + AND sg.created > vDated + LIMIT 1), + (SELECT c.id + FROM collection c + WHERE c.id = vParamFk + AND c.created > vDated), + (SELECT id + FROM ticket + WHERE id = vParamFk + AND shipped > vDated), + (SELECT id + FROM sectorCollection + WHERE id = vParamFk + AND created > vDated) + ) INTO vReturn; - -- Tabla vn.ticket - SELECT t.id INTO vValidFk - 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; + RETURN vReturn; END ;; DELIMITER ; @@ -48182,7 +48104,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`(vSelf INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `buy_afterUpsert`( + vSelf INT +) BEGIN /** * Triggered actions when a buy is updated or inserted. @@ -48199,7 +48123,7 @@ BEGIN DECLARE vIsFeedStock BOOL; DECLARE vWeight DECIMAL(10,2); DECLARE vPacking INT; - + SELECT b.entryFk, b.itemFk, i.packingOut, @@ -48230,8 +48154,11 @@ BEGIN WHERE e.id = vEntryFk; IF vIsMerchandise THEN + IF vWarehouse IS NULL THEN + CALL util.throw('The entry does not have travel'); + END IF; - REPLACE itemCost SET + REPLACE itemCost SET itemFk = vItemFk, warehouseFk = vWarehouse, cm3 = buy_getUnitVolume(vSelf), @@ -48257,7 +48184,7 @@ BEGIN WHERE b.id = vSelf; END IF; - CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck + CREATE OR REPLACE TEMPORARY TABLE tmp.buysToCheck SELECT vSelf id; CALL buy_checkItem(); END ;; @@ -49560,6 +49487,209 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `claimRatio_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `claimRatio_add`() +BEGIN +/* +* Añade a la tabla greuges todos los cargos necesario y +* que luego lo utilizamos para calcular el recobro. +*/ + DECLARE vMonthToRefund INT + DEFAULT (SELECT monthsToRefund FROM claimConfig); + DECLARE vRecoveryGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'recovery'); + DECLARE vManaGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'mana'); + DECLARE vClaimGreugeType INT + DEFAULT (SELECT id FROM greugeType WHERE code = 'claim'); + DECLARE vDebtComponentType INT + DEFAULT (SELECT id FROM component WHERE code = 'debtCollection'); + + IF vMonthToRefund IS NULL + OR vRecoveryGreugeType IS NULL + OR vManaGreugeType IS NULL + OR vClaimGreugeType IS NULL + OR vDebtComponentType IS NULL THEN + + CALL util.throw('Required variables not found'); + END IF; + + -- Reclamaciones demasiado sensibles + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim ', c.id,' : ', s.concept), + ROUND(-1 * ((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vClaimGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved'; + + -- Reclamaciones que pasan a Maná + INSERT INTO greuge( + shipped, + clientFk, + `description`, + amount, + greugeTypeFk, + ticketFk + ) + SELECT c.ticketCreated, + c.clientFk, + CONCAT('Claim_mana ', c.id,' : ', s.concept), + ROUND(((c.responsibility - 1) / 4) * s.quantity * + s.price * (100 - s.discount) / 100, 2), + vManaGreugeType, + s.ticketFk + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved' + AND c.isChargedToMana; + + -- Marcamos para no repetir + UPDATE claimEnd ce + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + SET ce.isGreuge = TRUE + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND NOT ce.isGreuge + AND cs.code = 'resolved'; + + -- Recobros + CREATE OR REPLACE TEMPORARY TABLE tTicketList + (PRIMARY KEY (ticketFk)) + ENGINE = MEMORY + SELECT DISTINCT s.ticketFk + FROM saleComponent sc + JOIN sale s ON sc.saleFk = s.id + JOIN ticket t ON t.id = s.ticketFk + JOIN ticketLastState ts ON ts.ticketFk = t.id + JOIN ticketTracking tt ON tt.id = ts.ticketTrackingFk + JOIN state st ON st.id = tt.stateFk + JOIN alertLevel al ON al.id = st.alertLevel + WHERE sc.componentFk = vDebtComponentType + AND NOT sc.isGreuge + AND t.shipped >= (SELECT minShipped FROM claimConfig) + AND t.shipped < util.VN_CURDATE() + AND al.code = 'DELIVERED'; + + DELETE g.* + FROM greuge g + JOIN tTicketList t ON t.ticketFk = g.ticketFk + WHERE g.greugeTypeFk = vRecoveryGreugeType; + + INSERT INTO greuge( + clientFk, + `description`, + amount, + shipped, + greugeTypeFk, + ticketFk + ) + SELECT t.clientFk, + 'Recobro', + - ROUND(SUM(sc.value * s.quantity), 2) dif, + DATE(t.shipped), + vRecoveryGreugeType, + tl.ticketFk + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN tTicketList tl ON tl.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + AND sc.componentFk = vDebtComponentType + GROUP BY t.id + HAVING ABS(dif) > 1; + + UPDATE saleComponent sc + JOIN sale s ON s.id = sc.saleFk + JOIN tTicketList tl ON tl.ticketFk = s.ticketFk + SET sc.isGreuge = TRUE + WHERE sc.componentFk = vDebtComponentType; + + REPLACE claimRatio( + clientFk, + yearSale, + claimAmount, + claimingRate, + priceIncreasing + ) + SELECT c.id, + 12 * cac.invoiced, + totalClaims, + ROUND(totalClaims / (12 * cac.invoiced), 4), + 0 + FROM client c + LEFT JOIN bs.clientAnnualConsumption cac ON cac.clientFk = c.id + LEFT JOIN ( + SELECT c.clientFk, + ROUND(SUM(-1 * ((c.responsibility - 1) / 4) * + s.quantity * s.price * (100 - s.discount) + / 100)) totalClaims + FROM sale s + JOIN claimEnd ce ON ce.saleFk = s.id + JOIN claimDestination cd ON cd.id = ce.claimDestinationFk + JOIN claim c ON c.id = ce.claimFk + JOIN claimState cs ON cs.id = c.claimStateFk + WHERE cd.description NOT IN ('Bueno', 'Corregido') + AND cs.code = 'resolved' + AND c.ticketCreated >= util.VN_CURDATE() - INTERVAL 1 YEAR + GROUP BY c.clientFk + ) sub ON sub.clientFk = c.id; + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE claimRatio cr + JOIN ( + SELECT clientFk, IFNULL(SUM(amount), 0) greuge + FROM greuge + WHERE shipped <= util.VN_CURDATE() + GROUP BY clientFk + ) sub ON sub.clientFk = cr.clientFk + SET cr.priceIncreasing = GREATEST(0, ROUND(IFNULL(sub.greuge, 0) / + (IFNULL(cr.yearSale, 0) * vMonthToRefund / 12 ), 3)); + + -- Protección neonatos + UPDATE claimRatio cr + JOIN firstTicketShipped fts ON fts.clientFk = cr.clientFk + SET cr.priceIncreasing = 0, + cr.claimingRate = 0 + WHERE fts.shipped > util.VN_CURDATE() - INTERVAL 1 MONTH; + + DROP TEMPORARY TABLE tTicketList; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `clean` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -50950,6 +51080,7 @@ BEGIN JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk + JOIN bs.clientDiedPeriod cdp ON cdp.countryFk = co.id WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND sp.salesPersonFk IS NULL @@ -51312,6 +51443,108 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_addWithReservation` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT, + vSaleGroupFk INT +) +BEGIN +/** + * En el ámbito de las colecciones se añade una línea de sale a un ticket + * de una colección en caso de tener disponible y se realiza la reserva. + * + * @param vItemFk id of item + * @param vQuantity quantity to be added to the ticket + * @param vTicketFk ticket to which the sales line is added + * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail + */ + + DECLARE vWarehouseFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vAvailable INT; + DECLARE vSaleFk INT; + DECLARE vConcept VARCHAR(50); + DECLARE vItemName VARCHAR(50); + DECLARE vHasThrow BOOLEAN DEFAULT FALSE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT t.warehouseFk INTO vWarehouseFk + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + WHERE t.id = vTicketFk; + + CALL cache.available_refresh( + vCacheAvailableFk, + FALSE, + vWarehouseFk, + util.VN_CURDATE()); + + SELECT available INTO vAvailable + FROM cache.available + WHERE calc_id = vCacheAvailableFk + AND item_id = vItemFk; + + IF vAvailable < vQuantity THEN + SET vHasThrow = TRUE; + ELSE + SELECT `name`, + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + INTO vItemName, vConcept + FROM item + WHERE id = vItemFk; + + START TRANSACTION; + + INSERT INTO sale + SET itemFk = vItemFk, + ticketFk = vTicketFk, + concept = vConcept, + quantity = vQuantity, + isAdded = TRUE; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + CALL sale_calculateComponent(vSaleFk, NULL); + CALL itemShelvingSale_addBySale(vSaleFk); + + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN + SET vHasThrow = TRUE; + END IF; + END IF; + + IF vHasThrow THEN + CALL util.throw("There is no available for the selected item"); + END IF; + + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + END IF; + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `collection_assign` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -51334,21 +51567,63 @@ BEGIN * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + CALL util.debugAdd('collection_assign', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp + END IF; + + RESIGNAL; + END; -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; + LEFT JOIN tmp.collection ON TRUE; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('Hay colecciones pendientes'); END IF; + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + -- Se eliminan las colecciones sin asignar que estan obsoletas INSERT INTO ticketTracking(stateFk, ticketFk) SELECT s.id, tc.ticketFk @@ -51356,7 +51631,7 @@ BEGIN JOIN ticketCollection tc ON tc.collectionFk = c.id JOIN `state` s ON s.code = 'PRINTED_AUTO' JOIN productionConfig pc - WHERE c.workerFk IS NULL + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* @@ -51396,6 +51671,8 @@ BEGIN UPDATE `collection` SET workerFk = vUserFk WHERE id = vCollectionFk; + + DO RELEASE_LOCK(vLockName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51420,28 +51697,150 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tCollection - 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 - 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 - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + 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 + 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 + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `collection_getAssigned` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getAssigned`( + vUserFk INT, + OUT vCollectionFk INT +) +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 y hace la reserva para la colección + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + END IF; + + RESIGNAL; + END; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + pc.collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName + FROM tmp.collection c + JOIN productionConfig pc; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('There are pending collections'); + END IF; + + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN state s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c + FROM collection c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed + SET userFk = vUserFk; + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM collection c + JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk + OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE collection + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + CALL itemShelvingSale_addByCollection(vCollectionFk); + + DO RELEASE_LOCK(vLockName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51461,62 +51860,89 @@ DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `collection_getTickets`(vParamFk INT) BEGIN /** - * Selecciona los tickets de una colección/ticket - * @param vParamFk ticketFk/collectionFk - * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones + * Selecciona los tickets de una colección/ticket/sectorCollection + * @param vParamFk ticketFk/collectionFk/sectorCollection + * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observation */ DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vYesterday DATE; -- Si los sacadores son los de pruebas, pinta los colores - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + SELECT itemPackingTypeFk + INTO vItemPackingTypeFk + FROM collection WHERE id = vParamFk; + + SET vYesterday = util.yesterday(); - SELECT t.id ticketFk, - IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, - am.name agencyName, - t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description,'') observaciones, - cc.rgb - 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` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - 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 - AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk - AND t.shipped >= util.yesterday() - UNION ALL + WITH observation AS ( + SELECT tob.ticketFk, tob.description + FROM vn.ticketObservation tob + JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk + WHERE ot.`code` = 'itemPicker' + AND tc.collectionFk = vParamFk + ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description, '') observaciones, - IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + w.id salesPersonFk, + IFNULL(ob.description,'') observaciones, + cc.rgb 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.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk 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 - AND tob.observationTypeFk = 1 - WHERE tc.collectionFk = vParamFk; - + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE t.id = vParamFk + AND t.shipped >= vYesterday + UNION ALL + SELECT t.id ticketFk, + IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, + am.name agencyName, + t.warehouseFk, + w.id salesPersonFk, + ob.description, + IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + FROM vn.ticket t + JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk + 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 observation ob ON ob.ticketFk = t.id + WHERE tc.collectionFk = vParamFk + UNION ALL + SELECT sg.ticketFk, + NULL `level`, + am.name agencyName, + t.warehouseFk, + c.salesPersonFk, + ob.description, + NULL `rgb` + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk + JOIN vn.ticket t ON t.id = sg.ticketFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + LEFT JOIN vn.client c ON c.id = t.clientFk + WHERE sc.id = vParamFk + AND t.shipped >= vYesterday; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -51672,6 +52098,8 @@ BEGIN DECLARE vLockName VARCHAR(215); DECLARE vLockTime INT DEFAULT 30; DECLARE vFreeWagonFk INT; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; DECLARE c1 CURSOR FOR SELECT ticketFk, `lines`, m3 @@ -51691,12 +52119,19 @@ BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd(JSON_OBJECT( - 'type', 'releaseLock', - 'userFk', vUserFk - ), vLockName); -- Tmp + CALL util.debugAdd('collection_new', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk, + 'ticketFk', vTicketFk + )); -- Tmp END IF; RESIGNAL; @@ -52613,7 +53048,7 @@ BEGIN 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.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk JOIN vn.packagingConfig pc WHERE t.warehouseFk IN (60,1,44) AND e.created BETWEEN vStarted AND vEnded @@ -53461,7 +53896,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `duaInvoiceInBooking`( + vDuaFk INT +) BEGIN /** * Genera el asiento de un DUA y marca las entradas como confirmadas @@ -53491,27 +53928,25 @@ BEGIN SET ii.booked = IFNULL(ii.booked, d.booked), ii.operated = IFNULL(ii.operated, d.operated), ii.issued = IFNULL(ii.issued, d.issued), - ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried), - e.isBooked = TRUE, - e.isConfirmed = TRUE + ii.bookEntried = IFNULL(ii.bookEntried, d.bookEntried) WHERE d.id = vDuaFk; SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - IF vBookEntry IS NULL THEN + IF vBookEntry IS NULL THEN SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear FROM invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id + JOIN `entry` e ON e.invoiceInFk = ii.id JOIN duaEntry de ON de.entryFk = e.id JOIN dua d ON d.id = de.duaFk WHERE d.id = vDuaFk LIMIT 1; CALL ledger_nextTx(vFiscalYear, vBookEntry); - END IF; + END IF; OPEN vInvoicesIn; -l: LOOP + l: LOOP SET vDone = FALSE; FETCH vInvoicesIn INTO vInvoiceFk; @@ -53532,6 +53967,29 @@ l: LOOP JOIN duaInvoiceIn dii ON dii.invoiceInFk = ii.id SET ii.isBooked = TRUE WHERE dii.duaFk = vDuaFk; + + UPDATE `entry` e + JOIN ( + WITH entries AS ( + SELECT e.id, de.duaFk + FROM vn.`entry` e + JOIN vn.duaEntry de ON de.entryFk = e.id + WHERE de.duaFk = vDuaFk + AND (NOT e.isBooked OR NOT e.isConfirmed) + ), + notBookedEntries AS ( + SELECT e.id + FROM vn.duaEntry + WHERE duaFk = vDuaFk + AND NOT customsValue + ) + SELECT e.id + FROM entries e + LEFT JOIN notBookedEntries nbe ON nbe.entryFk = e.id + WHERE nbe.entryFk IS NULL + ) sub ON sub.id = e.id + SET e.isBooked = TRUE, + e.isConfirmed = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -55323,13 +55781,13 @@ BEGIN LIMIT 1; IF vPalletFk IS NULL THEN - SELECT expeditionTruckFk + SELECT roadmapStopFk INTO vTruckFk FROM ( - SELECT rm.expeditionTruckFk, count(*) n + SELECT rm.roadmapStopFk, count(*) n FROM vn.routesMonitor rm JOIN tExpedition e ON e.routeFk = rm.routeFk - GROUP BY expeditionTruckFk + GROUP BY roadmapStopFk ORDER BY n DESC LIMIT 1) sub; @@ -55421,14 +55879,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `expeditionPallet_printLabel` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionPallet_printLabel`(vSelf INT) BEGIN @@ -55440,7 +55898,16 @@ BEGIN */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + DECLARE vIsInExpeditionPallet BOOL; + + SELECT COUNT(id) INTO vIsInExpeditionPallet + FROM expeditionPallet + WHERE id = vSelf; + + IF NOT vIsInExpeditionPallet THEN + CALL util.throw("ExpeditionPallet not exists"); + END IF; + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; @@ -55795,53 +56262,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `expeditionTruck_Add` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_Add`(vHour VARCHAR(5), vDescription VARCHAR(45)) -BEGIN - - INSERT INTO vn.roadmapStop(eta,description) - VALUES(CONCAT(util.VN_CURDATE(), ' ', vHour), vDescription); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `expeditionTruck_List` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `expeditionTruck_List`() -BEGIN - - SELECT id truckFk, - eta, - description Destino - FROM roadmapStop - WHERE eta BETWEEN util.VN_CURDATE() AND util.dayend(util.VN_CURDATE()) - ORDER BY eta; -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `expedition_getFromRoute` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -55866,7 +56286,8 @@ BEGIN t.addressFk, a.nickname, sub2.itemPackingTypeConcat, - est.code + est.code, + es.isScanned FROM expedition e JOIN ticket t ON t.id = e.ticketFk JOIN ticketState ts ON ts.ticketFk = e.ticketFk @@ -55884,6 +56305,10 @@ BEGIN GROUP BY sub.ticketFk ) sub2 ON sub2.ticketFk = t.id LEFT JOIN expeditionStateType est ON est.id = e.stateTypeFk + LEFT JOIN expeditionState es ON es.id = ( + SELECT MAX(id) + FROM expeditionState es + WHERE expeditionFk = e.id) WHERE t.routeFk = vRouteFk AND e.freightItemFk <> FALSE ORDER BY r.created, t.priority DESC; END ;; @@ -55953,7 +56378,7 @@ BEGIN 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.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END ;; @@ -56040,7 +56465,7 @@ BEGIN 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.roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE e.id = vExpeditionFk; END ;; @@ -57121,7 +57546,6 @@ BEGIN */ DECLARE vTaxRowLimit INT; DECLARE vLines INT; - DECLARE vHasDistinctTransactions INT; SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig; @@ -57133,18 +57557,6 @@ BEGIN IF vLines >= vTaxRowLimit THEN CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit)); END IF; - - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vInvoiceInFk - AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; - - IF vHasDistinctTransactions > 1 THEN - CALL util.throw ('This invoice does not allow different types of transactions'); - END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57357,6 +57769,19 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; + DECLARE vHasDistinctTransactions INT; + + SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN invoiceInSerial iis ON iis.code = ii.serial + WHERE ii.id = vSelf + AND iis.taxAreaFk = 'CEE' + AND transactionTypeSageFk; + + IF vHasDistinctTransactions > 1 THEN + CALL util.throw ('This invoice does not allow different types of transactions'); + END IF; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY @@ -58276,8 +58701,8 @@ BEGIN OR t.isDeleted OR c.hasToInvoice = FALSE OR itc.id IS NULL - OR a.id IS NULL - OR (vTaxArea = 'WORLD' + OR a.id IS NULL + OR (vTaxArea = 'WORLD' AND (a.customsAgentFk IS NULL OR a.incotermsFk IS NULL)); SELECT SUM(s.quantity * s.price * (100 - s.discount)/100) <> 0 @@ -58349,7 +58774,9 @@ BEGIN FROM tmp.ticketToInvoice ti LEFT JOIN ticketState ts ON ti.id = ts.ticketFk JOIN state s - WHERE IFNULL(ts.alertLevel, 0) < 3 and s.`code` = getAlert3State(ti.id); + JOIN alertLevel al ON al.code = 'DELIVERED' + WHERE (ts.alertLevel IS NULL OR ts.alertLevel < al.id) + AND s.`code` = getAlert3State(ti.id); INSERT INTO ticketTracking(stateFk, ticketFk, userFk) SELECT * FROM tmp.updateInter; @@ -59438,7 +59865,7 @@ BEGIN ish.isChecked, sub.isAllChecked FROM itemShelvingStock iss - JOIN itemShelving ish ON ish.shelvingFk = iss.shelvingFk + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk LEFT JOIN ( SELECT itemFk, IF( @@ -59758,7 +60185,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserve` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addByCollection` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -59766,302 +60193,53 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserve`() -BEGIN -/** - * Reserva cantidades con ubicaciones para un conjunto de sales del mismo - * almacen. - * - * @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 ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveByCollection` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reserveByCollection`( - vCollectionFk INT(11) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addByCollection`( + 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 ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reserveBySale` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `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 ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `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; +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + WITH sales AS ( + SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + GROUP BY s.id + HAVING quantity <> quantityReserved + ), trackedSales AS ( + SELECT sa.saleFk + FROM sales sa + JOIN vn.saleTracking st ON st.saleFk = sa.saleFk + JOIN vn.`state` s ON s.id = st.stateFk + WHERE st.isChecked + AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') + GROUP BY sa.saleFk + ) SELECT s.saleFk + FROM sales s + LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk + WHERE ts.saleFk IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60070,7 +60248,7 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingTransfer` */; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySale` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -60078,50 +60256,512 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3)) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySale`( + vSaleFk INT +) +proc: BEGIN +/** + * Reserva una línea de venta en la ubicación más óptima + * + * @param vSaleFk Id de sale + * @param vItemShelvingSaleFk Id de reserva + */ + DECLARE vLastPickingOrder INT; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vItemShelvingFk INT; + DECLARE vAvailable INT; + DECLARE vReservedQuantity INT; + DECLARE vOutStanding INT; + DECLARE vUserFk INT; + + DECLARE vItemShelvingAvailable CURSOR FOR + SELECT ish.id itemShelvingFk, + ish.available + FROM sale s + JOIN itemShelving ish ON ish.itemFk = s.itemFk + 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 productionConfig pc + WHERE s.id = vSaleFk + AND NOT sc.isHideForPickers + ORDER BY s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.available >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)) + INTO vLastPickingOrder, vOutStanding + FROM sale s + 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 + WHERE s.id = vSaleFk; + + IF vOutStanding <= 0 THEN + LEAVE proc; + END IF; + + SELECT getUser() INTO vUserFk; + + OPEN vItemShelvingAvailable; + l: LOOP + SET vDone = FALSE; + FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable; + + IF vOutStanding <= 0 OR vDone THEN + LEAVE l; + END IF; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + SELECT LEAST(vOutStanding, vAvailable) INTO vReservedQuantity; + SET vOutStanding = vOutStanding - vReservedQuantity; + + IF vReservedQuantity > 0 THEN + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk; + + UPDATE itemShelving + SET available = available - vReservedQuantity + WHERE id = vItemShelvingFk; + + END IF; + + COMMIT; + END LOOP; + CLOSE vItemShelvingAvailable; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_addBySectorCollection` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_addBySectorCollection`(vSectorCollectionFk INT(11)) BEGIN /** - * Transfiere producto de una ubicación a otra, fusionando si coincide el - * packing y la fecha. + * Reserva cantidades con ubicaciones para el contenido de una preparación previa + * de la cual ya tiene generada la asociación del saleGroup con sectorCollection * - * @param vItemShelvingFk Identificador de itemShelving - * @param vShelvingFk Identificador de shelving + * @param vSectorCollectionFk Identificador de sectorCollection */ - DECLARE vNewItemShelvingFk INT DEFAULT 0; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + SELECT s.id + FROM sectorCollectionSaleGroup sc + JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk + JOIN sale s ON sg.saleFk = s.id + JOIN saleTracking str ON str.saleFk = s.id + JOIN `state` st ON st.id = str.stateFk + AND st.code = 'PREVIOUS_PREPARATION' + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + WHERE sc.sectorCollectionFk = vSectorCollectionFk + AND str.workerFk = account.myUser_getId() + AND iss.id IS NULL; - SELECT MAX(ish.id) - INTO vNewItemShelvingFk - FROM itemShelving ish - JOIN ( - SELECT - itemFk, - packing, - created, - buyFk - FROM itemShelving - WHERE id = vItemShelvingFk - ) ish2 - ON ish2.itemFk = ish.itemFk - AND ish2.packing = ish.packing - AND date(ish2.created) = date(ish.created) - AND ish2.buyFk = ish.buyFk - WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - IF vNewItemShelvingFk THEN - UPDATE itemShelving ish - JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk - SET ish.visible = ish.visible + ish2.visible - WHERE ish.id = vNewItemShelvingFk; + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; - DELETE FROM itemShelving - WHERE id = vItemShelvingFk; - ELSE - UPDATE itemShelving - SET shelvingFk = vShelvingFk - WHERE id = vItemShelvingFk; - END IF; + IF vDone THEN + LEAVE l; + END IF; - SELECT true; + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_doReserve` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_doReserve`() +proc: BEGIN +/** + * Genera reservas de la tabla vn.itemShelvingSaleReserve + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk FROM tSale; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tSale + ENGINE = MEMORY + SELECT id, saleFk FROM itemShelvingSaleReserve; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserve iss JOIN tSale s ON s.id = iss.id; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_reallocate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_reallocate`( + vItemShelvingFk INT(10), + vItemFk INT(10) +) +BEGIN +/** + * Elimina reservas de un itemShelving e intenta reservar en otra ubicación + * + * @param vItemShelvingFk Id itemShelving + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = 0, + available = 0 + WHERE id = vItemShelvingFk + AND itemFk = vItemFk; + + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT DISTINCT iss.saleFk + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + + DELETE iss + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + COMMIT; + + CALL itemShelvingSale_doReserve(); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setPicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setPicked`( + vSaleGroupFk INT(10) +) +BEGIN +/** + * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked + * y cambiando el estado de la vn.sale + * + * @param vSaleGroupFk Id saleGroupFk + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN + CALL util.throw('Sale group not exists'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + JOIN saleGroupDetail sg ON sg.saleFk = s.id + SET iss.isPicked = TRUE + WHERE sg.saleGroupFk = vSaleGroupFk; + + CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); + + COMMIT; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_setQuantity` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en itemShelvingSale y 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 la ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Reservation completed'); + END IF; + + SELECT s.itemFk, iss.saleFk, iss.itemShelvingFk, SUM(IFNULL(iss.quantity,0)) + INTO vItemFk, vSaleFk, vItemShelvingFk, vReservedQuantity + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND + (NOT vIsItemShelvingSaleEmpty OR vIsItemShelvingSaleEmpty IS NULL)) + OR (vIsItemShelvingSaleEmpty IS NOT NULL AND vQuantity = vReservedQuantity) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = GREATEST(0, visible - vQuantity) + WHERE id = vItemShelvingFk; + + SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) + INTO vRemainingQuantity, vTotalQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN + CALL saleTracking_new( + vSaleFk, + TRUE, + vTotalQuantity, + `account`.`myUser_getId`(), + NULL, + 'PREPARED', + TRUE); + + UPDATE sale s + SET s.quantity = vTotalQuantity, + isPicked = TRUE + WHERE s.id = vSaleFk; + END IF; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT vSaleFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelvingSale_unpicked` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelvingSale_unpicked`( + vSelf INT(11) +) +BEGIN +/** + * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vReservedQuantity INT; + DECLARE vIsSaleGroup BOOL; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN + CALL util.throw('Reserva no completada'); + END IF; + + SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) + INTO vSaleFk, vReservedQuantity, vIsSaleGroup + FROM itemShelvingSale ish + LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk + WHERE ish.id = vSelf; + + /*IF vIsSaleGroup THEN + CALL util.throw('Can not unpicked a sale group'); + END IF;*/ + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = FALSE + WHERE id = vSelf; + + UPDATE sale s + JOIN itemShelvingSale ish ON ish.saleFk = s.id + SET s.isPicked = FALSE + WHERE ish.id = vSelf; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.visible = ish.visible + iss.quantity + WHERE iss.id = vSelf; + + CALL saleTracking_new( + vSaleFk, + FALSE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'ON_PREPARATION', + TRUE); + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60138,9 +60778,16 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; 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) +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_add`( + vShelvingFk VARCHAR(8), + vBarcode VARCHAR(22), + vQuantity INT, + vPackagingFk VARCHAR(10), + vGrouping INT, + vPacking INT, + vWarehouseFk INT +) BEGIN - /** * Añade registro o lo actualiza si ya existe. * @@ -60162,12 +60809,7 @@ BEGIN SELECT barcodeToItem(vBarcode) INTO vItemFk; IF vBuyFk IS NULL THEN - CALL cache.last_buy_refresh(FALSE); - - SELECT buy_id INTO vBuyFk - FROM cache.last_buy - WHERE item_id = vItemFk - AND warehouse_id = vWarehouseFk; + CALL util.throw('The buy is required'); END IF; IF vPacking IS NULL @@ -60347,7 +60989,8 @@ proc:BEGIN sub.downstairs, sub.visible, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho, - sub.name itemColour + sub.name itemColour, + CAST(sub2.pendiente AS DECIMAL(10,0)) pendingAmount FROM (SELECT iss.itemFk, CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName, '' size, @@ -60384,7 +61027,8 @@ proc:BEGIN 0, v.visible, v.visible nicho, - ik.name itemColour + ik.name itemColour, + CAST(sub5.pendiente AS DECIMAL(10,0)) pendingAmount FROM cache.visible v JOIN item i ON i.id = v.item_id LEFT JOIN ink ik ON ik.id = i.inkFk @@ -60950,6 +61594,67 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `itemShelving_transfer` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `itemShelving_transfer`( + vItemShelvingFk INT, + vShelvingFk VARCHAR(10) +) +BEGIN +/** + * Transfiere producto de una ubicación a otra, fusionando si coincide el + * packing y la fecha. + * + * @param vItemShelvingFk Identificador de itemShelving + * @param vShelvingFk Identificador de shelving + */ + DECLARE vNewItemShelvingFk INT DEFAULT 0; + + SELECT MAX(ish.id) + INTO vNewItemShelvingFk + FROM itemShelving ish + JOIN ( + SELECT + itemFk, + packing, + created, + buyFk + FROM itemShelving + WHERE id = vItemShelvingFk + ) ish2 ON ish2.itemFk = ish.itemFk + AND ish2.packing = ish.packing + AND date(ish2.created) = date(ish.created) + AND ish2.buyFk = ish.buyFk + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_unicode_ci; + + IF vNewItemShelvingFk THEN + UPDATE itemShelving ish + JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk + SET ish.visible = ish.visible + ish2.visible + WHERE ish.id = vNewItemShelvingFk; + + DELETE FROM itemShelving + WHERE id = vItemShelvingFk; + ELSE + UPDATE itemShelving + SET shelvingFk = vShelvingFk + WHERE id = vItemShelvingFk; + END IF; + SELECT true; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `itemShelving_update` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -62827,6 +63532,7 @@ BEGIN FROM sale s JOIN ticket t ON t.id = s.ticketFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo + AND t.warehouseFk AND s.quantity != 0 AND (vItemFk IS NULL OR s.itemFk = vItemFk) AND (vWarehouseFk IS NULL OR t.warehouseFk = vWarehouseFk) @@ -62837,7 +63543,7 @@ BEGIN t.warehouseInFk FROM buy b JOIN entry e ON e.id = b.entryFk - LEFT JOIN travel t ON t.id = e.travelFk + JOIN travel t ON t.id = e.travelFk WHERE t.landed BETWEEN vDatedFrom AND vDatedTo AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) AND !e.isExcludedFromAvailable @@ -62850,7 +63556,7 @@ BEGIN t.warehouseOutFk FROM buy b JOIN entry e ON e.id = b.entryFk - LEFT JOIN travel t ON t.id = e.travelFk + JOIN travel t ON t.id = e.travelFk WHERE t.shipped BETWEEN vDatedFrom AND vDatedTo AND (vWarehouseFk IS NULL OR t.warehouseOutFk = vWarehouseFk) AND !e.isExcludedFromAvailable @@ -62941,14 +63647,13 @@ BEGIN * @param vDated Fecha * @param vShowType Mostrar tipos */ - DECLARE vCalcFk INT; + DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); - - -- Añadido temporalmente para que no se cuelgue la db - SET vShowType = TRUE; + CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); WITH itemTags AS ( SELECT i.id, @@ -62991,21 +63696,21 @@ BEGIN WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 END AS minQuantity, - iss.visible located, + v.visible located, b.price2 FROM vn.item i JOIN cache.available a ON a.item_id = i.id - AND a.calc_id = vCalcFk + AND a.calc_id = vAvailableCalcFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id - AND iss.warehouseFk = vWarehouseFk JOIN itemTags its WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) @@ -63601,6 +64306,239 @@ BEGIN */ UPDATE item SET itemPackingTypeFk = vItemPackingTypeFk WHERE id = vItem; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_valuateInventory` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb3 */ ; +/*!50003 SET character_set_results = utf8mb3 */ ; +/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `item_valuateInventory`( +vDated DATE +) +BEGIN +DECLARE vInventoried DATE; +DECLARE vHasNotInventory BOOLEAN DEFAULT FALSE; +DECLARE vInventoryClone DATE; +DECLARE vDateDayEnd DATETIME; +DECLARE vInventorySupplierFk INT; + +SELECT inventorySupplierFk INTO vInventorySupplierFk +FROM entryConfig; + +SET vDateDayEnd = util.dayEnd(vDated); + +SELECT tr.landed INTO vInventoried +FROM travel tr +JOIN `entry` e ON e.travelFk = tr.id +WHERE tr.landed <= vDateDayEnd +AND e.supplierFk = vInventorySupplierFk +ORDER BY tr.landed DESC +LIMIT 1; + +SET vHasNotInventory = (vInventoried IS NULL); + +IF vHasNotInventory THEN +SELECT landed INTO vInventoryClone +FROM travel tr +JOIN `entry` e ON e.travelFk = tr.id +WHERE tr.landed >= vDated +AND e.supplierFk = vInventorySupplierFk +ORDER BY landed ASC +LIMIT 1; + +SET vInventoried = vDated + INTERVAL 1 DAY; +SET vDateDayEnd = vInventoryClone; +END IF; + +CREATE OR REPLACE TEMPORARY TABLE tInventory( +warehouseFk SMALLINT, +itemFk BIGINT, +quantity INT, +volume DECIMAL(10,2), +cost DOUBLE DEFAULT 0, +total DOUBLE DEFAULT 0, +warehouseInventory VARCHAR(20), +PRIMARY KEY (warehouseInventory, itemFk) USING HASH +) +ENGINE = MEMORY; + + +IF vHasNotInventory THEN +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +SUM(b.quantity), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseInFk +WHERE tr.landed = vDateDayEnd +AND e.supplierFk = vInventorySupplierFk +AND w.valuatedInventory +AND t.isInventory +GROUP BY tr.warehouseInFk, b.itemFk; +ELSE +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +SUM(b.quantity), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseInFk +WHERE tr.landed = vInventoried +AND e.supplierFk = vInventorySupplierFk +AND w.valuatedInventory +AND t.isInventory +GROUP BY tr.warehouseInFk, b.itemFk; +END IF; + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +b.quantity * IF(vHasNotInventory, -1, 1), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseInFk +WHERE tr.landed BETWEEN vInventoried AND vDateDayEnd +AND IF(tr.landed = util.VN_CURDATE(), tr.isReceived, TRUE) +AND NOT e.isRaid +AND w.valuatedInventory +AND t.isInventory +AND e.supplierFk <> vInventorySupplierFk +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory, -1, 1)); + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseOutFk, +b.itemFk, +b.quantity * IF(vHasNotInventory, 1, -1), +w.name +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse w ON w.id = tr.warehouseOutFk +WHERE tr.shipped BETWEEN vInventoried AND vDateDayEnd +AND NOT e.isRaid +AND w.valuatedInventory +AND t.isInventory +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity * IF(vHasNotInventory,1,-1)); + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT w.id, +s.itemFk, +s.quantity * IF(vHasNotInventory, 1, -1), +w.name +FROM sale s +JOIN ticket t ON t.id = s.ticketFk +JOIN `client` c ON c.id = t.clientFk +JOIN item i ON i.id = s.itemFk +JOIN itemType it ON it.id = i.typeFk +JOIN warehouse w ON w.id = t.warehouseFk +WHERE t.shipped BETWEEN vInventoried AND vDateDayEnd +AND w.valuatedInventory +AND it.isInventory +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 1, -1); + + +IF vDated = util.VN_CURDATE() THEN +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT w.id, +s.itemFk, +s.quantity * IF(vHasNotInventory, 0, 1), +w.name +FROM sale s +JOIN ticket t ON t.id = s.ticketFk +JOIN `client` c ON c.id = t.clientFk +JOIN item i ON i.id = s.itemFk +JOIN itemType it ON it.id = i.typeFk +JOIN warehouse w ON w.id = t.warehouseFk +WHERE t.shipped BETWEEN vDated AND vDateDayEnd +AND NOT (s.isPicked OR t.isLabeled) +AND w.valuatedInventory +AND it.isInventory +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + s.quantity * IF(vHasNotInventory, 0, 1); +END IF; + + +INSERT INTO tInventory(warehouseFk, itemFk, quantity, warehouseInventory) +SELECT tr.warehouseInFk, +b.itemFk, +b.quantity, +CONCAT(wOut.`name`, ' - ', wIn.`name`) +FROM buy b +JOIN item i ON i.id = b.itemFk +JOIN `entry` e ON e.id = b.entryFk +JOIN travel tr ON tr.id = e.travelFk +JOIN itemType t ON t.id = i.typeFk +JOIN warehouse wIn ON wIn.id = tr.warehouseInFk +JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk +WHERE vDated >= tr.shipped AND vDated < tr.landed +AND NOT isRaid +AND wIn.valuatedInventory +AND t.isInventory +AND e.isConfirmed +ON DUPLICATE KEY UPDATE tInventory.quantity = tInventory.quantity + (b.quantity); + +CALL buyUltimate(NULL, vDateDayEnd); + +DELETE FROM tInventory WHERE quantity IS NULL OR NOT quantity; + +UPDATE tInventory i +JOIN tmp.buyUltimate bu ON i.warehouseFk = bu.warehouseFk AND i.itemFk = bu.itemFk +JOIN buy b ON b.id = bu.buyFk +LEFT JOIN itemCost ic ON ic.itemFk = i.itemFk +AND ic.warehouseFk = i.warehouseFk +SET i.total = i.quantity * (IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0)), +i.cost = IFNULL(b.buyingValue, 0) + IFNULL(b.packageValue, 0) + IFNULL(b.freightValue, 0) + IFNULL(b.comissionValue, 0), +i.volume = i.quantity * ic.cm3delivery / 1000000; + +SELECT ti.warehouseFk, +i.id, +i.longName, +i.size, +ti.quantity, +ti.volume, +tp.name itemTypeName, +ic.name itemCategoryName, +ti.cost, +ti.total, +ti.warehouseInventory +FROM tInventory ti +JOIN warehouse w ON w.id = warehouseFk +JOIN item i ON i.id = ti.itemFk +JOIN itemType tp ON tp.id = i.typeFk +JOIN itemCategory ic ON ic.id = tp.categoryFk +WHERE w.valuatedInventory +AND ti.total > 0; + +DROP TEMPORARY TABLE +tmp.buyUltimate, +tInventory; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -64316,9 +65254,11 @@ proc: BEGIN ADD `life` TINYINT NOT NULL DEFAULT '0'; -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal + CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + SUM(quantity) quantity FROM ( SELECT s.itemFk, - s.quantity quantity FROM sale s @@ -64349,56 +65289,61 @@ proc: BEGIN AND w.isComparative AND NOT e.isExcludedFromAvailable AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; + ) sub + GROUP BY itemFk; + + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.quantity, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; -- Cálculo del visible + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, SUM(quantity) visible + FROM ( + SELECT s.itemFk, s.quantity + FROM sale s + JOIN ticket t ON t.id = s.ticketFk + JOIN warehouse w ON w.id = t.warehouseFk + WHERE t.shipped >= vDate + AND t.shipped < vDateTomorrow + AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) + AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, - b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseInFk + WHERE t.landed = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk + AND w.isComparative + UNION ALL + SELECT b.itemFk, b.quantity + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + JOIN warehouse w ON w.id = t.warehouseOutFk + WHERE t.shipped = vDate + AND NOT t.isReceived + AND NOT e.isExcludedFromAvailable + AND NOT e.isRaid + AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk + AND w.isComparative + ) sub2 + GROUP BY itemFk; + UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; + JOIN tItemVisibleCalc ivc ON ivc.itemFk = ai.id + SET ai.visible = ai.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -64469,6 +65414,8 @@ proc: BEGIN DROP TEMPORARY TABLE tmp.itemTravel, tmp.itemCalc, + tItemInventoryCalc, + tItemVisibleCalc, tmp.itemAtp; END ;; DELIMITER ; @@ -65248,14 +66195,16 @@ BEGIN (PRIMARY KEY (ticketFk)) ENGINE = MEMORY SELECT t.id ticketFk, t.clientFk - FROM vn.ticket t - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - JOIN vn.client c ON c.id = t.clientFk + FROM ticket t + JOIN alertLevel al ON al.code = 'DELIVERED' + LEFT JOIN ticketState ts ON ts.ticketFk = t.id + JOIN client c ON c.id = t.clientFk + WHERE c.typeFk IN ('normal','handMaking','internalUse') AND ( t.shipped BETWEEN util.VN_CURDATE() AND vEndingDate OR ( - ts.alertLevel < 3 + ts.alertLevel < al.id AND t.shipped >= vStartingDate AND t.shipped < util.VN_CURDATE() ) @@ -65383,7 +66332,7 @@ DELIMITER ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `productionControl`( - vWarehouseFk INT, + vWarehouseFk INT, vScopeDays INT ) proc: BEGIN @@ -65398,6 +66347,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -65414,7 +66368,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; @@ -65450,7 +66405,7 @@ proc: BEGIN wk.code salesPersonCode, p.id provinceFk, tls.productionOrder, - IFNULL(tls.alertLevel, 0) alertLevel, + IFNULL(tls.alertLevel, al.id) alertLevel, t.isBoxed palletized, IF(rm.isPickingAllowed, rm.bufferFk, NULL) ubicacion, tlu.lastUpdated, @@ -65464,6 +66419,7 @@ proc: BEGIN rm.bufferFk FROM tmp.productionTicket tt JOIN ticket t ON tt.ticketFk = t.id + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketStateToday tst ON tst.ticketFk = t.id LEFT JOIN `state` st ON st.id = tst.state LEFT JOIN client c ON c.id = t.clientFk @@ -65484,7 +66440,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 @@ -65492,12 +66448,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, @@ -66406,7 +67362,7 @@ BEGIN LEFT JOIN ticketTrolley tt ON tt.ticket = t.id LEFT JOIN zone zo ON t.zoneFk = zo.id LEFT JOIN routesMonitor rm ON rm.routeFk = t.routeFk - LEFT JOIN roadmapStop rs ON rs.id = rm.expeditionTruckFk + LEFT JOIN roadmapStop rs ON rs.id = rm.roadmapStopFk WHERE IF(vIsCollection, tc.collectionFk = vParam, tc.ticketFk = vParam) GROUP BY t.id ORDER BY cc.code; @@ -66708,7 +67664,7 @@ BEGIN SET rm.m3boxes = sub.m3boxes; UPDATE routesMonitor rm - JOIN vn.roadmapStop rs ON rs.id = rm.expeditionTruckFk + JOIN vn.roadmapStop rs ON rs.id = rm.roadmapStopFk SET rm.etd = rs.eta; DROP TEMPORARY TABLE tmp.routesMonitor; @@ -68440,12 +69396,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -68453,9 +69408,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; @@ -69085,6 +70040,37 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getMyPartial` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`localhost` PROCEDURE `sectorCollection_getMyPartial`() +BEGIN +/** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + */ + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + LEFT JOIN vn.sale sl ON sl.id = sgd.saleFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = sl.id + WHERE sc.userFk = account.myUser_getId() + AND (scsg.sectorCollectionFk IS NULL OR NOT iss.isPicked) + AND sc.created > util.VN_CURDATE() - INTERVAL 1 DAY; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `sectorCollection_getSale` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -69312,41 +70298,43 @@ proc: BEGIN CALL util.throw('parkingNotExist'); LEAVE proc; END IF; + + IF vParam REGEXP '^[0-9]+$' THEN + -- Se comprueba si es una preparación previa + SELECT COUNT(*) INTO vIsSaleGroup + FROM vn.saleGroup sg + WHERE sg.id = vParam; - -- Se comprueba si es una preparación previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; + IF vIsSaleGroup THEN + CALL vn.saleGroup_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; + -- Se comprueba si es un ticket + SELECT COUNT(*) INTO vIsTicket + FROM vn.ticket t + WHERE t.id = vParam + AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsTicket THEN + CALL vn.ticket_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + + -- Se comprueba si es una coleccion de tickets + SELECT COUNT(*) INTO vIsCollection + FROM vn.collection c + WHERE c.id = vParam + AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + + IF vIsCollection THEN + CALL vn.collection_setParking(vParam, vParkingFk); + LEAVE proc; + END IF; + ELSE + -- Por descarte, se considera una matrícula + CALL vn.shelving_setParking(vParam, vParkingFk); END IF; - - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Por descarte, se considera una matrícula - CALL vn.shelving_setParking(vParam, vParkingFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -70065,10 +71053,10 @@ CREATE DEFINER=`root`@`localhost` PROCEDURE `supplierPackaging_ReportSource`( ) BEGIN /** -* Selecciona los embalajes de un proveedor a partir de una fecha +* Create a report with packaging balance * -* @param vFromDated Fecha de la que partir -* @param vSupplierFk Id del proveedor +* @param vFromDated Starting date +* @param vSupplierFk Supplier ID */ SET @vBalance = 0; SET @vItemFk = NULL; @@ -70082,7 +71070,7 @@ BEGIN landed, `in`, `out`, - warehouse, + sref, buyingValue, IF ( NOT (@vItemFk <=> sub.itemFk), @@ -70091,19 +71079,20 @@ BEGIN ) balance, @vItemFk := sub.itemFk previousItemFk FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - CONCAT('E',entryFk) entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated + SELECT sp.supplierFk, + sp.itemFk, + sp.longName, + sp.supplier, + CONCAT('E',sp.entryFk) entryFk, + sp.landed, + sp.`in`, + sp.`out`, + e.invoiceNumber sref, + sp.buyingValue + FROM supplierPackaging sp + JOIN entry e ON e.id = sp.entryFk + WHERE sp.supplierFk = vSupplierFk + AND sp.landed >= vFromDated UNION ALL SELECT vSupplierFk, itemFk, @@ -70128,7 +71117,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -70159,6 +71148,7 @@ BEGIN WHERE su.id = vSupplierFk AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY s.itemFk UNION ALL SELECT vSupplierFk, @@ -70169,7 +71159,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -70198,8 +71188,9 @@ BEGIN JOIN client c ON c.id = t.clientFk JOIN supplier su ON su.nif = c.fi WHERE su.id = vSupplierFk - AND t.shipped >= vFromDated + AND t.shipped < vFromDated AND p.isPackageReturnable + AND NOT t.isDeleted GROUP BY p.itemFk ORDER BY itemFk, landed, entryFk ) sub @@ -70213,7 +71204,7 @@ BEGIN landed, CAST(`in` AS DECIMAL(10,0)) `in`, CAST(`out` AS DECIMAL(10,0)) `out`, - warehouse, + sref, buyingValue, balance FROM tSupplierPackaging @@ -71253,13 +72244,16 @@ BEGIN DECLARE vShipped DATE; DECLARE vWarehouse TINYINT; DECLARE vAlertLevel INT; + DECLARE vAlertLevelFree INT; - SELECT t.warehouseFk, t.shipped, ts.alertLevel INTO vWarehouse, vShipped, vAlertLevel + SELECT t.warehouseFk, t.shipped, ts.alertLevel, al.id + INTO vWarehouse, vShipped, vAlertLevel, vAlertLevelFree FROM ticket t + JOIN alertLevel al ON al.code = 'FREE' LEFT JOIN ticketState ts ON ts.ticketFk = vTicket WHERE t.id = vTicket; - IF vAlertLevel IS NULL OR vAlertLevel = 0 THEN + IF vAlertLevel IS NULL OR vAlertLevel = vAlertLevelFree THEN IF vShipped >= util.VN_CURDATE() THEN CALL cache.available_refresh(vAvailableCalc, FALSE, vWarehouse, vShipped); END IF; @@ -71283,68 +72277,6 @@ DELIMITER ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketMissed_List` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticketMissed_List`(vTicketFk INT) -BEGIN - - DECLARE vParkingFk INT; - DECLARE vParked DATETIME; - DECLARE vLevel INT; - DECLARE vCollectionFk INT; - - SELECT IFNULL(`level`,0), IFNULL(collectionFk,0) - INTO vLevel, vCollectionFk - FROM vn.ticketCollection - WHERE ticketFk = vTicketFk - LIMIT 1; - - 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 - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND ( - ( - ( IFNULL(tc.collectionFk,-1) != IFNULL(@vCollectionFk,0) AND tp.created < vParked ) - OR - ( tc.collectionFk = vCollectionFk AND LEFT(tc.level,1) < LEFT(vLevel,1) ) - ) - )) -- Etiquetas que no se han escaneado y ya estamos con una posterior - OR - (s.alertLevel > 1 - AND tp.parkingFk = vParkingFk - AND sc.isPackagingArea - AND tp.created < vParked - AND t.packages <=> 0); - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticketNotInvoicedByClient` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -71585,64 +72517,66 @@ 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 - JOIN vn.sector sc ON sc.id = p.sectorFk - LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk - JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk - JOIN vn.ticket t ON t.id = tp.ticketFk - JOIN vn.zone z ON z.id = t.zoneFk - JOIN vn.agencyMode am ON am.id = z.agencyModeFk - JOIN vn.state s ON s.id = tst.state - WHERE (s.alertLevel < 2 + JOIN vn.parking p ON p.id = tp.parkingFk + JOIN vn.sector sc ON sc.id = p.sectorFk + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = tp.ticketFk + JOIN vn.ticketStateToday tst ON tst.ticketFk = tp.ticketFk + JOIN vn.ticket t ON t.id = tp.ticketFk + JOIN vn.zone z ON z.id = t.zoneFk + JOIN vn.agencyMode am ON am.id = z.agencyModeFk + JOIN vn.state s ON s.id = tst.state + JOIN vn.alertLevel alPacked ON alPacked.code = 'PACKED' + JOIN vn.alertLevel alOnPreparation ON alOnPreparation.code = 'ON_PREPARATION' + WHERE (s.alertLevel < alPacked.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea 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 OR - (s.alertLevel > 1 + (s.alertLevel > alOnPreparation.id AND tp.parkingFk = vParkingFk AND sc.isPackagingArea - AND tp.created < vParked + AND tp.created < vParked AND t.packages <=> 0); END ;; DELIMITER ; @@ -71662,64 +72596,28 @@ 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 + DECLARE vAlertLevelPacked INT; + + SELECT s.alertLevel, al.id + INTO vAlertLevel, vAlertLevelPacked + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + JOIN alertLevel al ON al.code = 'PACKED' WHERE tst.ticketFk = vTicketFk LIMIT 1; - - IF vAlertLevel < 2 THEN - + + IF vAlertLevel < vAlertLevelPacked THEN + CALL vn.ticket_setState(vTicketFk, vStateCode); - - END IF; - -END ;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketStateUpdate` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; -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 - FROM vn.state s - JOIN vn.ticketState ts ON ts.stateFk = s.id - WHERE ts.ticketFk = vTicketFk; - - IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN - - INSERT INTO ticketTracking(stateFk, ticketFk, userFk) - SELECT id, vTicketFk, account.myUser_getId() - FROM vn.state - WHERE `code` = vStateCode collate utf8_unicode_ci; END IF; @@ -72396,14 +73294,14 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'IGNORE_SPACE,NO_ENGINE_SUBSTITUTION' */ ; /*!50003 DROP PROCEDURE IF EXISTS `ticket_Clone` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb3 */ ; -/*!50003 SET character_set_results = utf8mb3 */ ; -/*!50003 SET collation_connection = utf8mb3_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_Clone`(vOriginalTicket INT, OUT vNewTicket INT) BEGIN @@ -72415,6 +73313,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, @@ -72547,7 +73450,10 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_cloneWeekly`( + vDateFrom DATE, + vDateTo DATE +) BEGIN DECLARE vIsDone BOOL; DECLARE vLanding DATE; @@ -72587,9 +73493,16 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; - FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment; + FETCH rsTicket INTO + vTicketFk, + vClientFk, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + vShipment; IF vIsDone THEN LEAVE myLoop; @@ -72615,7 +73528,7 @@ BEGIN AND isDefaultAddress; END IF; - CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); + CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk, FALSE); SET vLanding = NULL; SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1; @@ -72636,16 +73549,22 @@ BEGIN SET clonedFrom = vTicketFk WHERE id = vNewTicket; - INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, - discount, priceFixed, isPriceFixed) + INSERT INTO sale (ticketFk, + itemFk, + concept, + quantity, + price, + discount, + priceFixed, + isPriceFixed) SELECT vNewTicket, - saleOrig.itemFk, - saleOrig.concept, - saleOrig.quantity, - saleOrig.price, - saleOrig.discount, - saleOrig.priceFixed, - saleOrig.isPriceFixed + saleOrig.itemFk, + saleOrig.concept, + saleOrig.quantity, + saleOrig.price, + saleOrig.discount, + saleOrig.priceFixed, + saleOrig.isPriceFixed FROM sale saleOrig WHERE saleOrig.ticketFk = vTicketFk; @@ -72671,20 +73590,20 @@ BEGIN ,attenderFk, ticketFk) SELECT description, - ordered, - shipped, - quantity, - price, - itemFk, - clientFk, - response, - total, - buyed, - requesterFk, - attenderFk, - vNewTicket + ordered, + shipped, + quantity, + price, + itemFk, + clientFk, + response, + total, + buyed, + requesterFk, + attenderFk, + vNewTicket FROM ticketRequest - WHERE ticketFk =vTicketFk; + WHERE ticketFk =vTicketFk; SELECT id INTO vSalesPersonFK FROM observationType @@ -72737,7 +73656,7 @@ BEGIN IF NOT vIsDuplicateMail THEN CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); END IF; - CALL ticketStateUpdate (vNewTicket, 'FIXING'); + CALL ticket_setState(vNewTicket, 'FIXING'); ELSE CALL ticketCalculateClon(vNewTicket, vTicketFk); END IF; @@ -73157,10 +74076,11 @@ BEGIN CREATE TEMPORARY TABLE tmp.ticket SELECT ticketFk FROM tmp.productionBuffer + JOIN alertLevel al ON al.code = 'FREE' WHERE shipped = util.VN_CURDATE() AND problem LIKE '%I:%' AND (HH <= vHour OR HH = vHour AND mm < vMinute) - AND alertLevel = 0; + AND alertLevel = al.id; OPEN cur1; @@ -73190,7 +74110,9 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`(vTicketFk INT) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_DelayTruckSplit`( + vTicketFk INT +) BEGIN /** * Splita las lineas de ticket que no estan ubicadas @@ -73241,7 +74163,7 @@ BEGIN SET s.ticketFk = vNewTicketFk; END IF; - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); + CALL ticket_setState(vNewTicketFk, 'FIXING'); DROP TEMPORARY TABLE tmp.SalesToSplit; END ;; @@ -73279,7 +74201,7 @@ BEGIN com.id companyFk, a.id addressFk, c2.defaultAddressFk, - su.id supplierFk, + IFNULL(sat.supplierFk, su.id) supplierFk, t.landed FROM ticket t JOIN ticketState ts ON ts.ticketFk = t.id @@ -73289,15 +74211,18 @@ BEGIN 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 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 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 + LEFT JOIN agencyMode am ON am.id = r.agencyModeFk + LEFT JOIN agency ag ON ag.id = am.agencyFk + LEFT JOIN supplierAgencyTerm sat ON sat.agencyFk = ag.id + AND wo.isFreelance WHERE al.code IN ('PACKED', 'DELIVERED') AND co.code <> 'ES' AND am.name <> 'ABONO' @@ -74936,7 +75861,11 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE) +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_split`( + vTicketFk INT, + vTicketFutureFk INT, + vDated DATE +) proc:BEGIN /** * Mueve las lineas con problemas a otro ticket existente o a uno nuevo. @@ -74954,61 +75883,57 @@ proc:BEGIN FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - SELECT count(*) INTO vTotalLines - FROM vn.sale s + SELECT COUNT(*) INTO vTotalLines + FROM sale s WHERE s.ticketFk = vTicketFk; SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - - UPDATE vn.ticket - SET landed = vDated + INTERVAL 1 DAY, + UPDATE ticket + SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, - nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) + nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname) WHERE id = vTicketFk; - SELECT "moved" message, NULL ticketFuture; + SELECT 'moved' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s - JOIN tmp.salesToSplit ss ON s.id = ss.saleFk + UPDATE 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 "future" message, NULL ticketFuture; + SELECT 'future' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket nuevo - CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk); + CALL ticket_Clone(vTicketFk, vTicketFutureFk); - UPDATE vn.ticket t - JOIN vn.productionConfig pc + UPDATE ticket t + JOIN productionConfig pc SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL), - t.landed = vDated + INTERVAL 1 DAY, + t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE 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'); + CALL ticket_setState(vTicketFutureFk, 'FIXING'); - SELECT "new" message,vTicketFutureFk ticketFuture; + SELECT 'new' message, vTicketFutureFk ticketFuture; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75025,8 +75950,11 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; DELIMITER ;; -CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1)) -proc:BEGIN +CREATE DEFINER=`root`@`localhost` PROCEDURE `ticket_splitItemPackingType`( + vTicketFk INT, + vOriginalItemPackingTypeFk VARCHAR(1) +) +BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. @@ -75048,22 +75976,27 @@ proc:BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + DELETE FROM vn.sale WHERE quantity = 0 AND ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale + CREATE OR REPLACE TEMPORARY TABLE tmp.sale (PRIMARY KEY (id)) + ENGINE = MEMORY SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros FROM vn.sale s JOIN vn.item i ON i.id = s.itemFk LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id WHERE s.ticketFk = vTicketFk; - DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup; - CREATE TEMPORARY TABLE tmp.saleGroup - SELECT itemPackingTypeFk , sum(litros) AS totalLitros + CREATE OR REPLACE TEMPORARY TABLE tmp.saleGroup + ENGINE = MEMORY + SELECT itemPackingTypeFk, SUM(litros) totalLitros FROM tmp.sale GROUP BY itemPackingTypeFk; @@ -75071,10 +76004,10 @@ proc:BEGIN FROM tmp.saleGroup WHERE itemPackingTypeFk IS NOT NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - (ticketFk INT, - itemPackingTypeFk VARCHAR(1)); + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT ( + ticketFk INT, + itemPackingTypeFk VARCHAR(1) + ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN @@ -75115,7 +76048,7 @@ proc:BEGIN SELECT itemPackingTypeFk INTO vItemPackingTypeFk FROM tmp.saleGroup sg - WHERE NOT ISNULL(sg.itemPackingTypeFk) + WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; @@ -75126,8 +76059,9 @@ proc:BEGIN WHERE ts.itemPackingTypeFk IS NULL; END CASE; - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE tmp.saleGroup; + DROP TEMPORARY TABLE + tmp.sale, + tmp.saleGroup; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -82100,23 +83034,6 @@ SET character_set_client = utf8; 1 AS `description` */; SET character_set_client = @saved_cs_client; --- --- Temporary table structure for view `Saldos_Prevision` --- - -DROP TABLE IF EXISTS `Saldos_Prevision`; -/*!50001 DROP VIEW IF EXISTS `Saldos_Prevision`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `Saldos_Prevision` AS SELECT - 1 AS `Saldos_Prevision_id`, - 1 AS `Descripcion`, - 1 AS `Importe`, - 1 AS `Fecha`, - 1 AS `Id_Banco`, - 1 AS `empresa_id` */; -SET character_set_client = @saved_cs_client; - -- -- Temporary table structure for view `Split_lines` -- @@ -82177,7 +83094,6 @@ SET character_set_client = utf8; 1 AS `Id_Trabajador`, 1 AS `Observaciones`, 1 AS `Firmado`, - 1 AS `Etiquetasemitidas`, 1 AS `PedidoImpreso`, 1 AS `Hora`, 1 AS `blocked`, @@ -85135,7 +86051,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 0 */; +/*!50001 VIEW `bufferDayMinute` AS select `b`.`id` AS `bufferFk`,`e`.`id` AS `expeditionFk`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,`e`.`position` AS `position`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) minute) AS `ETD`,`e2`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`es`.`description` AS `expeditionState` from ((((((((`srt`.`buffer` `b` left join `srt`.`expedition` `e` on(`b`.`id` = `e`.`bufferFk`)) left join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) left join `vn`.`expedition` `e2` on(`e2`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`e2`.`ticketFk` = `t`.`id`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`roadmapStopFk` = `rs`.`id`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) where `b`.`isActive` <> 0 */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85171,7 +86087,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`rs`.`id` is null,`c`.`bufferDefault`,`rs`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */; +/*!50001 VIEW `bufferStock` AS select `e`.`id` AS `expeditionFk`,`e`.`bufferFk` AS `bufferFk`,`e`.`position` AS `position`,`srt`.`dayMinute`(ifnull(`rs`.`eta`,`z`.`hour`)) AS `dayMinute`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `eta`,`ve`.`ticketFk` AS `ticketFk`,ifnull(`t`.`routeFk`,`t`.`agencyModeFk`) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`es`.`description` AS `expeditionState`,`b`.`hasWorkerWaiting` AS `hasWorkerWaiting`,`b`.`isActive` AS `isActive`,if(`rs`.`id` is null,`c`.`bufferDefault`,`rs`.`bufferFk`) AS `bufferTruck`,`bt`.`typeName` AS `typeName`,`rm`.`bufferFk` AS `routeBuffer` from (((((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) join `srt`.`expeditionState` `es` on(`es`.`id` = `e`.`stateFk`)) join `srt`.`buffer` `b` on(`b`.`id` = `e`.`bufferFk`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`roadmapStopFk` = `rs`.`id`)) join `srt`.`config` `c`) join `srt`.`bufferType` `bt` on(`bt`.`id` = `b`.`typeFk`)) where `bt`.`typeName` <> 'DISABLED' */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85261,7 +86177,7 @@ USE `srt`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`expeditionTruckFk` = `rs`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */; +/*!50001 VIEW `upperStickers` AS select `e`.`id` AS `expeditionFk`,`e`.`id` MOD 10000 AS `expedition`,ifnull(`rs`.`eta`,`util`.`VN_CURDATE`() + interval `srt`.`dayMinute`(`z`.`hour`) + 120 minute) AS `ETD`,`ve`.`ticketFk` AS `ticketFk`,right(ifnull(`t`.`routeFk`,`t`.`agencyModeFk`),3) AS `routeFk`,`z`.`name` AS `zonaTicket`,`rs`.`description` AS `truck`,`epo`.`workerCode` AS `worker`,`p`.`name` AS `labeler`,`ve`.`counter` AS `expeditionCounter`,`vn`.`ticketTotalVolume`(`t`.`id`) AS `m3`,`t`.`clientFk` AS `clientFk` from (((((((`srt`.`expedition` `e` left join `vn`.`expedition` `ve` on(`ve`.`id` = `e`.`id`)) left join `vn`.`ticket` `t` on(`t`.`id` = `ve`.`ticketFk`)) left join `vn`.`zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `vn`.`routesMonitor` `rm` on(`t`.`routeFk` = `rm`.`routeFk`)) left join `vn`.`roadmapStop` `rs` on(`rm`.`roadmapStopFk` = `rs`.`id`)) join `dipole`.`expedition_PrintOut` `epo` on(`epo`.`expeditionFk` = `e`.`id`)) join `vn`.`printer` `p` on(`p`.`id` = `epo`.`printerFk`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85681,7 +86597,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionCommon` AS select `rs`.`id` AS `truckFk`,`rs`.`eta` AS `eta`,ifnull(ucase(`rs`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`roadmapStop` `rs` left join `routesMonitor` `r` on(`rs`.`id` = `r`.`expeditionTruckFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `rs`.`eta` >= `util`.`VN_CURDATE`() */; +/*!50001 VIEW `expeditionCommon` AS select `rs`.`id` AS `truckFk`,`rs`.`eta` AS `eta`,ifnull(ucase(`rs`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`roadmapStopFk` AS `roadmapStopFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked`,`t`.`id` AS `ticketFk` from (((((`roadmapStop` `rs` left join `routesMonitor` `r` on(`rs`.`id` = `r`.`roadmapStopFk`)) left join `ticket` `t` on(`r`.`routeFk` = `t`.`routeFk`)) left join `expedition` `e` on(`t`.`id` = `e`.`ticketFk`)) left join `expeditionScan` `es` on(`e`.`id` = `es`.`expeditionFk`)) left join `expeditionPallet` `ep` on(`es`.`palletFk` = `ep`.`id`)) where `rs`.`eta` >= `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85699,7 +86615,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`expeditionTruckFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`expeditionTruckFk`)) group by `ep`.`id`,`t`.`routeFk` */; +/*!50001 VIEW `expeditionPallet_Print` AS select `rs2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,`rs`.`id` <=> `rm`.`roadmapStopFk` AS `isMatch`,`t`.`warehouseFk` AS `warehouseFk`,if(`r`.`created` > `util`.`VN_CURDATE`() + interval 1 day,ucase(dayname(`r`.`created`)),NULL) AS `nombreDia` from (((((((`roadmapStop` `rs` join `expeditionPallet` `ep` on(`ep`.`truckFk` = `rs`.`id`)) join `expeditionScan` `es` on(`es`.`palletFk` = `ep`.`id`)) join `expedition` `e` on(`e`.`id` = `es`.`expeditionFk`)) join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `r`.`id`)) left join `roadmapStop` `rs2` on(`rs2`.`id` = `rm`.`roadmapStopFk`)) group by `ep`.`id`,`t`.`routeFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85717,7 +86633,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */; +/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct if(`e`.`id` is null,`t`.`id`,NULL)) AS `tickets`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked`,`r`.`created` AS `created` from (((((`route` `r` left join `routesMonitor` `rm` on(`r`.`id` = `rm`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) join `ticket` `t` on(`t`.`routeFk` = `r`.`id`)) left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) left join `expeditionScan` `es` on(`es`.`expeditionFk` = `e`.`id`)) where `r`.`created` >= `util`.`yesterday`() group by `r`.`id` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85771,7 +86687,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`rs`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */; +/*!50001 VIEW `expeditionSticker` AS select `e`.`id` AS `expeditionFk`,`e`.`ticketFk` AS `ticketFk`,`t`.`addressFk` AS `addressFk`,`t`.`clientFk` AS `clientFk`,`a`.`street` AS `street`,`a`.`postalCode` AS `postalCode`,`a`.`city` AS `city`,`a`.`nickname` AS `nickname`,concat('R(',right(`t`.`routeFk`,3),')') AS `routeFk`,`rm`.`beachFk` AS `beachFk`,if(`t`.`routeFk`,ifnull(`rs`.`description`,replace(`am`.`name`,'ZONA ','Z')),`z`.`name`) AS `zona`,`p`.`name` AS `province`,ifnull(`c`.`mobile`,ifnull(`a`.`mobile`,ifnull(`c`.`phone`,`a`.`phone`))) AS `phone`,`w`.`code` AS `workerCode` from (((((((((((`expedition` `e` join `ticket` `t` on(`t`.`id` = `e`.`ticketFk`)) join `address` `a` on(`a`.`id` = `t`.`addressFk`)) join `province` `p` on(`p`.`id` = `a`.`provinceFk`)) left join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) left join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) left join `beach` `b` on(`b`.`code` = `rm`.`beachFk`)) left join `zone` `z` on(`z`.`id` = `t`.`zoneFk`)) left join `route` `r` on(`r`.`id` = `t`.`routeFk`)) left join `agencyMode` `am` on(`am`.`id` = `r`.`agencyModeFk`)) join `client` `c` on(`c`.`id` = `a`.`clientFk`)) join `worker` `w` on(`w`.`id` = `e`.`workerFk`)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85789,7 +86705,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`rs`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`expeditionTruckFk`)) where `e`.`id` is null and `rs`.`eta` > `util`.`VN_CURDATE`() */; +/*!50001 VIEW `expeditionTicket_NoBoxes` AS select `t`.`id` AS `ticketFk`,`t`.`warehouseFk` AS `warehouseFk`,`t`.`routeFk` AS `routeFk`,`rs`.`description` AS `description` from (((`ticket` `t` left join `expedition` `e` on(`e`.`ticketFk` = `t`.`id`)) join `routesMonitor` `rm` on(`rm`.`routeFk` = `t`.`routeFk`)) join `roadmapStop` `rs` on(`rs`.`id` = `rm`.`roadmapStopFk`)) where `e`.`id` is null and `rs`.`eta` > `util`.`VN_CURDATE`() */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -85825,61 +86741,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck` AS select `rs`.`id` AS `id`,`rs`.`roadmapFk` AS `roadmapFk`,`rs`.`warehouseFk` AS `warehouseFk`,`rs`.`eta` AS `eta`,`rs`.`description` AS `description`,`rs`.`bufferFk` AS `bufferFk`,`rs`.`created` AS `created`,`rs`.`userFk` AS `userFk` from `roadmapStop` `rs` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `ETD`,`e`.`description` AS `description`,count(distinct if(`e`.`expeditionFk` is null,`e`.`ticketFk`,NULL)) AS `ticketsSinBultos`,count(distinct `e`.`palletFk`) AS `pallets`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionFk`) AS `expeditions`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `expeditionCommon` `e` group by `e`.`truckFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`eta` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control_Detail` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionTruckFk`) AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `expeditionCommon` `e` group by `e`.`truckFk`,`e`.`palletFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`eta`,`e`.`truckFk` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control_Detail_Pallet` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`eta` AS `eta`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`rs`.`description` AS `destinos`,sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk`,max(`e`.`lastPacked`) AS `lastPacked` from (`expeditionCommon` `e` left join `roadmapStop` `rs` on(`rs`.`id` = `e`.`expeditionTruckFk`)) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by sum(`e`.`truckFk` <> `e`.`expeditionTruckFk`) desc,`e`.`palletFk` */; +/*!50001 VIEW `expeditionTruck` AS select `rs`.`id` AS `id`,`rs`.`roadmapFk` AS `roadmapFk`,`rs`.`eta` AS `eta`,`rs`.`description` AS `description`,`rs`.`bufferFk` AS `bufferFk`,`rs`.`created` AS `created`,`rs`.`userFk` AS `userFk` from `roadmapStop` `rs` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -87852,24 +88714,6 @@ USE `vn2008`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Final view structure for view `Saldos_Prevision` --- - -/*!50001 DROP VIEW IF EXISTS `Saldos_Prevision`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_unicode_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Saldos_Prevision` AS select `fb`.`id` AS `Saldos_Prevision_id`,`fb`.`description` AS `Descripcion`,`fb`.`amount` AS `Importe`,`fb`.`dated` AS `Fecha`,`fb`.`accountingFk` AS `Id_Banco`,`fb`.`companyFk` AS `empresa_id` from `vn`.`forecastedBalance` `fb` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Final view structure for view `Split_lines` -- @@ -87919,7 +88763,7 @@ USE `vn2008`; /*!50001 SET collation_connection = utf8mb4_unicode_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`localhost` SQL SECURITY DEFINER */ -/*!50001 VIEW `Tickets` AS select `t`.`id` AS `Id_Ticket`,`t`.`clientFk` AS `Id_Cliente`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipped` AS `Fecha`,`t`.`landed` AS `landing`,`t`.`nickname` AS `Alias`,`t`.`refFk` AS `Factura`,`t`.`addressFk` AS `Id_Consigna`,`t`.`location` AS `Localizacion`,`t`.`solution` AS `Solucion`,`t`.`routeFk` AS `Id_Ruta`,`t`.`companyFk` AS `empresa_id`,`t`.`agencyModeFk` AS `Id_Agencia`,`t`.`priority` AS `Prioridad`,`t`.`packages` AS `Bultos`,`t`.`isDeleted` AS `isDeleted`,`t`.`created` AS `odbc_date`,`t`.`workerFk` AS `Id_Trabajador`,`t`.`observations` AS `Observaciones`,`t`.`isSigned` AS `Firmado`,`t`.`isLabeled` AS `Etiquetasemitidas`,`t`.`isPrinted` AS `PedidoImpreso`,`t`.`hour` AS `Hora`,`t`.`isBlocked` AS `blocked`,`t`.`hasPriority` AS `priority`,`t`.`isBoxed` AS `boxed`,`t`.`zoneFk` AS `zoneFk`,`t`.`totalWithVat` AS `totalWithVat`,`t`.`totalWithoutVat` AS `totalWithoutVat` from `vn`.`ticket` `t` */; +/*!50001 VIEW `Tickets` AS select `t`.`id` AS `Id_Ticket`,`t`.`clientFk` AS `Id_Cliente`,`t`.`warehouseFk` AS `warehouse_id`,`t`.`shipped` AS `Fecha`,`t`.`landed` AS `landing`,`t`.`nickname` AS `Alias`,`t`.`refFk` AS `Factura`,`t`.`addressFk` AS `Id_Consigna`,`t`.`location` AS `Localizacion`,`t`.`solution` AS `Solucion`,`t`.`routeFk` AS `Id_Ruta`,`t`.`companyFk` AS `empresa_id`,`t`.`agencyModeFk` AS `Id_Agencia`,`t`.`priority` AS `Prioridad`,`t`.`packages` AS `Bultos`,`t`.`isDeleted` AS `isDeleted`,`t`.`created` AS `odbc_date`,`t`.`workerFk` AS `Id_Trabajador`,`t`.`observations` AS `Observaciones`,`t`.`isSigned` AS `Firmado`,`t`.`isPrinted` AS `PedidoImpreso`,`t`.`hour` AS `Hora`,`t`.`isBlocked` AS `blocked`,`t`.`hasPriority` AS `priority`,`t`.`isBoxed` AS `boxed`,`t`.`zoneFk` AS `zoneFk`,`t`.`totalWithVat` AS `totalWithVat`,`t`.`totalWithoutVat` AS `totalWithoutVat` from `vn`.`ticket` `t` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -89715,4 +90559,4 @@ USE `vn2008`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-11 6:35:36 +-- Dump completed on 2024-07-09 5:48:04 diff --git a/db/dump/.dump/triggers.sql b/db/dump/.dump/triggers.sql index b2f550bbe..41525b2eb 100644 --- a/db/dump/.dump/triggers.sql +++ b/db/dump/.dump/triggers.sql @@ -2140,24 +2140,22 @@ BEGIN 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, - 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; + SELECT util.hasDateOverlapped( + started, + ended, + NEW.started, + IFNULL(NEW.ended, b.started) + ) isOverlapped INTO isOverlapping + FROM vn.business b + WHERE workerFk = NEW.workerFK + AND b.id <> NEW.id + ORDER BY isOverlapped DESC + LIMIT 1; IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; - END IF; - END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2366,7 +2364,15 @@ trig:BEGIN LEAVE trig; END IF; - CALL entry_isEditable(OLD.entryFk); + IF NOT (NEW.entryFk <=> OLD.entryFk) OR + NOT (NEW.quantity <=> OLD.quantity) OR + NOT (NEW.buyingValue <=> OLD.buyingValue) OR + NOT (NEW.packing <=> OLD.packing) + THEN + + CALL entry_isEditable(OLD.entryFk); + END IF; + SET NEW.editorFk = account.myUser_getId(); SELECT defaultEntry INTO vDefaultEntry @@ -3010,6 +3016,52 @@ 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`.`claimRatio_afterInsert` + AFTER INSERT ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!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`.`claimRatio_afterUpdate` + AFTER UPDATE ON `claimRatio` + FOR EACH ROW +BEGIN + INSERT INTO clientRate(clientFk, `value`) + VALUES(NEW.clientFk, NEW.priceIncreasing) + ON DUPLICATE KEY UPDATE + `value` = VALUES(`value`); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!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`.`claimState_beforeInsert` BEFORE INSERT ON `claimState` FOR EACH ROW @@ -3198,11 +3250,11 @@ BEGIN END IF; END IF; - IF !(NEW.salesPersonFk <=> OLD.salesPersonFk) THEN + IF NOT (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 + IF NOT (NEW.businessTypeFk <=> OLD.businessTypeFk) AND (NEW.businessTypeFk = 'individual' OR OLD.businessTypeFk = 'individual') THEN SET NEW.isTaxDataChecked = 0; END IF; END */;; @@ -3224,13 +3276,36 @@ DELIMITER ;; AFTER UPDATE ON `client` FOR EACH ROW BEGIN - IF !(NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN + IF NOT (NEW.defaultAddressFk <=> OLD.defaultAddressFk) THEN UPDATE `address` SET isDefaultAddress = FALSE WHERE clientFk = NEW.id; UPDATE `address` SET isDefaultAddress = TRUE WHERE id = NEW.defaultAddressFk; END IF; + + IF NEW.id <> OLD.id + OR NOT (NEW.provinceFk <=> OLD.provinceFk) + OR NOT (NEW.socialName <=> OLD.socialName) + OR NOT (NEW.street <=> OLD.street) + OR NOT (NEW.accountingAccount <=> OLD.accountingAccount) + OR NOT (NEW.isVies <=> OLD.isVies) + OR NOT (NEW.fi <=> OLD.fi) + OR NOT (NEW.postcode <=> OLD.postcode) + OR NOT (NEW.city <=> OLD.city) + OR NOT (NEW.countryFk <=> OLD.countryFk) + OR NOT (NEW.taxTypeSageFk <=> OLD.taxTypeSageFk) + OR NOT (NEW.transactionTypeSageFk <=> OLD.transactionTypeSageFk) + OR NOT (NEW.email <=> OLD.email) + OR NOT (NEW.iban <=> OLD.iban) + OR NOT (NEW.phone <=> OLD.phone) + OR NOT (NEW.mobile <=> OLD.mobile) THEN + + UPDATE sage.clientSupplier + SET isSync = FALSE + WHERE idClientSupplier IN (NEW.id, OLD.id) + AND `type` = 'C'; + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3541,6 +3616,46 @@ 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`.`clientUnpaid_beforeInsert` + BEFORE INSERT ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!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`.`clientUnpaid_beforeUpdate` + BEFORE UPDATE ON `clientUnpaid` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!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`.`cmr_beforeDelete` BEFORE DELETE ON `cmr` FOR EACH ROW @@ -4203,31 +4318,6 @@ 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`.`deviceProductionConfig_afterUpdate` - AFTER UPDATE ON `deviceProductionConfig` - FOR EACH ROW -BEGIN - IF NEW.isAllUsersAllowed = 1 OR NEW.isAllUsersAllowed = -1 THEN - SET @username := (SELECT account.myUser_getName()); - INSERT INTO vn.mail (receiver, subject, body) - VALUES ('cau@verdnatura.es', 'Se ha activado la autenticación sin restricciones en la app', - CONCAT('El usuario ', @username,' ha habilitado la opción para que todos los usuarios puedan acceder a la app sin restricciones')); - END IF; -END */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!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`.`deviceProductionModels_beforeInsert` BEFORE INSERT ON `deviceProductionModels` FOR EACH ROW @@ -4617,10 +4707,19 @@ BEGIN DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; DECLARE vTotalBuy INT; - - IF NEW.isBooked = OLD.isBooked THEN + + IF NEW.isBooked = OLD.isBooked AND ( + NOT (NEW.supplierFk <=> OLD.supplierFk) OR + NOT (NEW.dated <=> OLD.dated) OR + NOT (NEW.travelFk <=> OLD.travelFk) OR + NOT (NEW.companyFk <=> OLD.companyFk) OR + NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR + NOT (NEW.typeFk <=> OLD.typeFk) + ) THEN + CALL entry_isEditable(OLD.id); ELSE + IF NEW.isBooked THEN SELECT COUNT(*) INTO vTotalBuy FROM buy @@ -4894,25 +4993,25 @@ DELIMITER ;; BEFORE INSERT ON `expedition` FOR EACH ROW BEGIN - DECLARE intcounter INT; - DECLARE vShipFk INT; + DECLARE vMaxCounter INT; SET NEW.editorFk = account.myUser_getId(); - IF NEW.freightItemFk IS NOT NULL THEN + IF NEW.freightItemFk IS NOT NULL THEN UPDATE ticket SET packages = IFNULL(packages, 0) + 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 vMaxCounter + FROM expedition e + JOIN alertLevel al ON al.code = 'DELIVERED' + JOIN ticket t1 ON e.ticketFk = t1.id LEFT JOIN ticketState ts ON ts.ticketFk = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + 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 < al.id AND t1.companyFk = t2.companyFk AND t1.agencyModeFk = t2.agencyModeFk; - SET NEW.`counter` = intcounter; + SET NEW.`counter` = vMaxCounter; END IF; END */;; DELIMITER ; @@ -6083,6 +6182,7 @@ DELIMITER ;; BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); + SET NEW.available = NEW.visible; END */;; DELIMITER ; @@ -6099,48 +6199,20 @@ 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`.`itemShelving_afterInsert` - AFTER INSERT ON `itemShelving` - FOR EACH ROW -INSERT INTO vn.itemShelvingLog( itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing) - VALUES( NEW.id, - NEW.userFk, - 'CREA REGISTRO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing - ) */;; -DELIMITER ; -/*!50003 SET sql_mode = @saved_sql_mode */ ; -/*!50003 SET character_set_client = @saved_cs_client */ ; -/*!50003 SET character_set_results = @saved_cs_results */ ; -/*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; -/*!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`.`itemShelving_beforeUpdate` BEFORE UPDATE ON `itemShelving` FOR EACH ROW BEGIN + SET NEW.editorFk = account.myUser_getId(); IF NEW.userFk IS NULL THEN SET NEW.userFk = account.myUser_getId(); END IF; + + IF (NEW.visible <> OLD.visible) THEN + SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0); + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6159,7 +6231,8 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelving_afterUpdate` AFTER UPDATE ON `itemShelving` FOR EACH ROW -INSERT INTO itemShelvingLog +BEGIN + INSERT INTO itemShelvingLog SET itemShelvingFk = NEW.id, workerFk = account.myUser_getId(), accion = 'CAMBIO', @@ -6167,7 +6240,10 @@ INSERT INTO itemShelvingLog shelvingFk = NEW.shelvingFk, visible = NEW.visible, `grouping` = NEW.`grouping`, - packing = NEW.packing */;; + packing = NEW.packing, + available = NEW.available; + +END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; /*!50003 SET character_set_client = @saved_cs_client */ ; @@ -6236,12 +6312,12 @@ DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`itemShelvingSale_afterInsert` AFTER INSERT ON `itemShelvingSale` FOR EACH ROW -BEGIN - - UPDATE vn.sale - SET isPicked = TRUE - WHERE id = NEW.saleFk; - +BEGIN + + UPDATE sale s + JOIN operator o ON o.workerFk = account.myUser_getId() + SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) + WHERE id = NEW.saleFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8525,6 +8601,44 @@ 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`.`supplier_afterUpdate` + BEFORE UPDATE ON `supplier` + FOR EACH ROW +BEGIN + IF NEW.id <> OLD.id + OR NOT (NEW.name <=> OLD.name) + OR NOT (NEW.street <=> OLD.street) + OR NOT (NEW.account <=> OLD.account) + OR NOT (NEW.nif <=> OLD.nif) + OR NOT (NEW.isVies <=> OLD.isVies) + OR NOT (NEW.provinceFk <=> OLD.provinceFk) + OR NOT (NEW.countryFk <=> OLD.countryFk) + OR NOT (NEW.postCode <=> OLD.postCode) + OR NOT (NEW.city <=> OLD.city) + OR NOT (NEW.taxTypeSageFk <=> OLD.taxTypeSageFk) + OR NOT (NEW.transactionTypeSageFk <=> OLD.transactionTypeSageFk) + OR NOT (NEW.withholdingSageFk <=> OLD.withholdingSageFk) THEN + + UPDATE sage.clientSupplier + SET isSync = FALSE + WHERE idClientSupplier IN (NEW.id, OLD.id) + AND `type` = 'P'; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ; +/*!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`.`supplier_afterDelete` AFTER DELETE ON `supplier` FOR EACH ROW @@ -10825,4 +10939,4 @@ USE `vn2008`; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2024-06-11 6:35:55 +-- Dump completed on 2024-07-09 5:48:24 diff --git a/db/dump/fixtures.after.sql b/db/dump/fixtures.after.sql index 562ea02d8..84ce0d940 100644 --- a/db/dump/fixtures.after.sql +++ b/db/dump/fixtures.after.sql @@ -314,5 +314,4 @@ INSERT INTO mysql.roles_mapping (`User`, `Host`, `Role`, `Admin_option`) SELECT SUBSTR(`User`, @prefixLen + 1), `Host`, `Role`, `Admin_option` FROM mysql.roles_mapping WHERE `User` LIKE @prefixedLike AND `Host` = @genRoleHost; - FLUSH PRIVILEGES; diff --git a/db/dump/fixtures.before.sql b/db/dump/fixtures.before.sql index f800a1da1..fffdcf7df 100644 --- a/db/dump/fixtures.before.sql +++ b/db/dump/fixtures.before.sql @@ -115,10 +115,13 @@ INSERT INTO `hedera`.`tpvConfig`(`id`, `currency`, `terminal`, `transactionType` VALUES (1, 978, 1, 0, 2000, 9, 0); +INSERT INTO hedera.orderConfig (`id`, `employeeFk`, `defaultAgencyFk`, `guestMethod`, `guestAgencyFk`, `reserveTime`, `defaultCompanyFk`) + VALUES (1, 1, 2, 'PICKUP', 1, '00:20:00', 442); + INSERT INTO `account`.`user`(`id`,`name`,`nickname`, `password`,`role`,`active`,`email`,`lang`, `image`) VALUES (1101, 'brucewayne', 'Bruce Wayne', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'BruceWayne@mydomain.com', 'es','1101'), - (1102, 'petterparker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'PetterParker@mydomain.com', 'en','1102'), + (1102, 'petterparker', 'Petter Parker', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 131, 1, 'PetterParker@mydomain.com', 'en','1102'), (1103, 'clarkkent', 'Clark Kent', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'ClarkKent@mydomain.com', 'fr','1103'), (1104, 'tonystark', 'Tony Stark', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'TonyStark@mydomain.com', 'es','1104'), (1105, 'maxeisenhardt', 'Max Eisenhardt', '$2b$10$UzQHth.9UUQ1T5aiQJ21lOU0oVlbxoqH4PFM9V8T90KNSAcg0eEL2', 2, 1, 'MaxEisenhardt@mydomain.com', 'pt','1105'), @@ -301,6 +304,17 @@ UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 8; UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 4 WHERE `id` = 23; UPDATE `vn`.`agencyMode` SET `deliveryMethodFk` = 1 WHERE `id` = 10; +UPDATE `vn`.`agencyMode` SET `description` = 'inhouse pickup' WHERE `id` = 1; +UPDATE `vn`.`agencyMode` SET `description` = 'Super-Man delivery' WHERE `id` = 2; +UPDATE `vn`.`agencyMode` SET `description` = 'Teleportation device' WHERE `id` = 3; +UPDATE `vn`.`agencyMode` SET `description` = 'Entanglement' WHERE `id` = 4; +UPDATE `vn`.`agencyMode` SET `description` = 'Quantum break device' WHERE `id` = 5; +UPDATE `vn`.`agencyMode` SET `description` = 'Walking' WHERE `id` = 6; +UPDATE `vn`.`agencyMode` SET `description` = 'Gotham247' WHERE `id` = 7; +UPDATE `vn`.`agencyMode` SET `description` = 'Gotham247Expensive' WHERE `id` = 8; +UPDATE `vn`.`agencyMode` SET `description` = 'Other agency' WHERE `id` = 10; +UPDATE `vn`.`agencyMode` SET `description` = 'Refund' WHERE `id` = 23; + UPDATE `vn`.`agencyMode` SET `web` = 1, `reportMail` = 'no-reply@gothamcity.com'; UPDATE `vn`.`agencyMode` SET `code` = 'refund' WHERE `id` = 23; @@ -528,7 +542,8 @@ INSERT INTO `vn`.`observationType`(`id`,`description`, `code`) (5, 'Administrative', 'administrative'), (6, 'Weight', 'weight'), (7, 'InvoiceOut', 'invoiceOut'), - (8, 'DropOff', 'dropOff'); + (8, 'DropOff', 'dropOff'), + (9, 'Sustitución', 'substitution'); INSERT INTO `vn`.`addressObservation`(`id`,`addressFk`,`observationTypeFk`,`description`) VALUES @@ -978,6 +993,14 @@ INSERT INTO `vn`.`priceFixed`(`id`, `itemFk`, `rate0`, `rate1`, `rate2`, `rate3` (2, 3, 10, 10, 10, 10, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 0, 1, util.VN_CURDATE()), (3, 13, 8.5, 10, 7.5, 6, util.VN_CURDATE(), DATE_ADD(util.VN_CURDATE(), INTERVAL +1 MONTH), 1, 2, util.VN_CURDATE()); +INSERT INTO `vn`.`itemMinimumQuantity`(`itemFk`, `quantity`, `started`, `ended`, `warehouseFk`) + VALUES + (1, 5, util.VN_CURDATE() - INTERVAL 2 MONTH, util.VN_CURDATE() + INTERVAL 1 MONTH, 1), + (2, 10, util.VN_CURDATE() - INTERVAL 2 DAY, util.VN_CURDATE() - INTERVAL 1 DAY, 2), + (3, 15, util.VN_CURDATE() + INTERVAL 3 DAY, util.VN_CURDATE() + INTERVAL 2 WEEK, 3), + (2, 10, util.VN_CURDATE() + INTERVAL 2 MONTH, NULL, 5), + (4, 8, util.VN_CURDATE() - INTERVAL 3 MONTH, NULL, NULL); + INSERT INTO `vn`.`expeditionBoxVol`(`boxFk`, `m3`, `ratio`) VALUES (71,0.141,1); @@ -1477,7 +1500,8 @@ INSERT INTO `vn`.`travel`(`id`,`shipped`, `landed`, `warehouseInFk`, `warehouseO (5, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 3, 3, 1, 50.00, 500, 'fifth travel', 1, 1, 5), (6, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 4, 4, 1, 50.00, 500, 'sixth travel', 1, 2, 6), (7, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 4, 1, 50.00, 500, 'seventh travel', 2, 1, 7), - (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10); + (8, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 1, 1, 50.00, 500, 'eight travel', 1, 2, 10), + (10, DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), DATE_ADD(util.VN_CURDATE(), INTERVAL + 5 DAY), 5, 1, 1, 50.00, 500, 'nineth travel', 1, 2, 10); INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed`, `companyFk`, `invoiceNumber`, `reference`, `isExcludedFromAvailable`, `isRaid`, `evaNotes`) VALUES @@ -1488,7 +1512,9 @@ INSERT INTO `vn`.`entry`(`id`, `supplierFk`, `created`, `travelFk`, `isConfirmed (5, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 5, 0, 442, 'IN2005', 'Movement 5', 0, 0, 'observation five'), (6, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 6, 0, 442, 'IN2006', 'Movement 6', 0, 0, 'observation six'), (7, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2007', 'Movement 7', 0, 0, 'observation seven'), - (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''); + (8, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL -1 MONTH), 7, 0, 442, 'IN2008', 'Movement 8', 1, 1, ''), + (9, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''), + (10, 2, DATE_ADD(util.VN_CURDATE(), INTERVAL +2 DAY), 10, 0, 442, 'IN2009', 'Movement 9', 1, 1, ''); INSERT INTO `bs`.`waste`(`buyer`, `year`, `week`, `family`, `itemFk`, `itemTypeFk`, `saleTotal`, `saleWaste`, `rate`) VALUES @@ -1942,7 +1968,7 @@ INSERT INTO `vn`.`orderTicket`(`orderFk`, `ticketFk`) (21, 21), (22, 22); -INSERT INTO `vn`.`userConfig` (`userFk`, `warehouseFk`, `companyFk`) +INSERT INTO `vn`.`userMultiConfig` (`userFk`, `warehouseFk`, `companyFk`) VALUES (1, 1, 69), (5, 1, 442), @@ -2868,7 +2894,8 @@ INSERT INTO `util`.`notification` (`id`, `name`, `description`) (5, 'modified-entry', 'An entry has been modified'), (6, 'book-entry-deleted', 'accounting entries deleted'), (7, 'zone-included','An email to notify zoneCollisions'), - (8, 'backup-printer-selected','A backup printer has been selected'); + (8, 'backup-printer-selected','A backup printer has been selected'), + (9, 'mrw-deadline','The MRW deadline has passed'); TRUNCATE `util`.`notificationAcl`; INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) @@ -2881,7 +2908,8 @@ INSERT INTO `util`.`notificationAcl` (`notificationFk`, `roleFk`) (5, 9), (6, 9), (7, 9), - (8, 66); + (8, 66), + (9, 56); TRUNCATE `util`.`notificationQueue`; INSERT INTO `util`.`notificationQueue` (`id`, `notificationFk`, `params`, `authorFk`, `status`, `created`) @@ -3230,7 +3258,6 @@ INSERT IGNORE INTO vn.itemType workerFk = 103, isInventory = TRUE, life = 10, - density = 250, itemPackingTypeFk = NULL, temperatureFk = 'warm'; @@ -3845,6 +3872,13 @@ INSERT INTO `vn`.`ledgerCompany` SET INSERT INTO `vn`.`ledgerConfig` SET maxTolerance = 0.01; + +INSERT INTO vn.trainingCourse (workerFk,trainingCourseTypeFk,centerFk,started,ended,hasDiscount,hasDiploma) + VALUES + (9,2,1,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',0,1), + (9,1,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,0), + (9,2,2,'2018-06-20 00:00:00.000','2020-06-24 00:00:00.000',1,1); + INSERT INTO vn.sectorCollection SET id = 2, userFk = 18, @@ -3882,3 +3916,40 @@ INSERT INTO `vn`.`calendarHolidays` (calendarHolidaysTypeFk, dated, calendarHoli (1, '2001-05-17', 1, 5), (1, '2001-05-18', 1, 5); +INSERT INTO vn.payrollComponent +(id, name, isSalaryAgreed, isVariable, isException) + VALUES + (1, 'Salario1', 1, 0, 0), + (2, 'Salario2', 1, 1, 0), + (3, 'Salario3', 1, 0, 1); + + +INSERT INTO vn.workerIncome +(debit, credit, incomeTypeFk, paymentDate, workerFk, concept) + VALUES + (1000.00, 900.00, 2, '2000-01-01', 1106, NULL), + (1001.00, 800.00, 2, '2000-01-01', 1106, NULL); + + +INSERT INTO dipole.printer (id, description) +VALUES(1, ''); + +INSERT INTO dipole.expedition_PrintOut (expeditionFk, ticketFk, addressFk, street, postalCode, city, shopName, isPrinted, created, printerFk, routeFk, parkingCode, +truckName, clientFk, phone, province, agency, m3, workerCode, itemFk, quantity, longName, shelvingFk, comments) +VALUES(1, 1, 0, ' ', ' ', ' ', ' ', 0, '2001-01-01 00:00:00', 1, 0, ' ', ' ', 0, NULL, '', NULL, 0.000, NULL, 10, NULL, NULL, 'NCC', NULL); + +INSERT INTO vn.accountDetail +(id, value, accountDetailTypeFk, supplierAccountFk) +VALUES + (21, 'ES12345B12345678', 3, 241), + (35, 'ES12346B12345679', 3, 241); + +INSERT INTO vn.accountDetailType +(id, description) +VALUES + (1, 'IBAN'), + (2, 'SWIFT'), + (3, 'Referencia Remesas'), + (4, 'Referencia Transferencias'), + (5, 'Referencia Nominas'), + (6, 'ABA'); diff --git a/db/routines/account/triggers/mailAliasAccount_afterDelete.sql b/db/routines/account/triggers/mailAliasAccount_afterDelete.sql new file mode 100644 index 000000000..83af7169c --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_afterDelete` + AFTER DELETE ON `mailAliasAccount` + FOR EACH ROW +BEGIN + INSERT INTO userLog + SET `action` = 'delete', + `changedModel` = 'MailAliasAccount', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql b/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql new file mode 100644 index 000000000..a435832f2 --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeInsert` + BEFORE INSERT ON `mailAliasAccount` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql b/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql new file mode 100644 index 000000000..471a34900 --- /dev/null +++ b/db/routines/account/triggers/mailAliasAccount_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `account`.`mailAliasAccount_beforeUpdate` + BEFORE UPDATE ON `mailAliasAccount` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/bi/procedures/rutasAnalyze.sql b/db/routines/bi/procedures/rutasAnalyze.sql index 5f0d55c7a..e277968bf 100644 --- a/db/routines/bi/procedures/rutasAnalyze.sql +++ b/db/routines/bi/procedures/rutasAnalyze.sql @@ -59,7 +59,7 @@ BEGIN 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 - WHERE ct.code = 'FREIGHT' + WHERE ct.code = 'freight' AND r.created BETWEEN vDatedFrom AND vDatedTo GROUP BY r.id ) sub ON sub.routeFk = r.Id_Ruta diff --git a/db/routines/bi/views/tarifa_componentes_series.sql b/db/routines/bi/views/tarifa_componentes_series.sql index f231ae420..ed2f8e29a 100644 --- a/db/routines/bi/views/tarifa_componentes_series.sql +++ b/db/routines/bi/views/tarifa_componentes_series.sql @@ -2,7 +2,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `bi`.`tarifa_componentes_series` AS SELECT `ct`.`id` AS `tarifa_componentes_series_id`, - `ct`.`type` AS `Serie`, + `ct`.`name` AS `Serie`, `ct`.`isBase` AS `base`, `ct`.`isMargin` AS `margen` FROM `vn`.`componentType` `ct` diff --git a/db/routines/cache/procedures/availableNoRaids_refresh.sql b/db/routines/cache/procedures/availableNoRaids_refresh.sql index 383e35436..37715d270 100644 --- a/db/routines/cache/procedures/availableNoRaids_refresh.sql +++ b/db/routines/cache/procedures/availableNoRaids_refresh.sql @@ -117,7 +117,7 @@ proc: BEGIN )sub GROUP BY sub.itemFk; - DROP TEMPORARY TABLE tmp.itemCalc, tItemRange; + DROP TEMPORARY TABLE tmp.itemCalc, tItemRange, tmp.itemList; CALL cache_calc_end (vCalc); END$$ DELIMITER ; diff --git a/db/routines/cache/procedures/available_refresh.sql b/db/routines/cache/procedures/available_refresh.sql index d0939e568..abf023a41 100644 --- a/db/routines/cache/procedures/available_refresh.sql +++ b/db/routines/cache/procedures/available_refresh.sql @@ -121,7 +121,7 @@ proc: BEGIN )sub GROUP BY sub.itemFk; - DROP TEMPORARY TABLE tmp.itemCalc, itemRange; + DROP TEMPORARY TABLE tmp.itemCalc, itemRange, tmp.itemList; CALL cache_calc_end (vCalc); END$$ DELIMITER ; diff --git a/db/routines/cache/procedures/visible_refresh.sql b/db/routines/cache/procedures/visible_refresh.sql index 63b42dfd9..78d23dbfb 100644 --- a/db/routines/cache/procedures/visible_refresh.sql +++ b/db/routines/cache/procedures/visible_refresh.sql @@ -1,13 +1,13 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `cache`.`visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT) -proc: BEGIN +proc:BEGIN DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN CALL cache_calc_unlock (v_calc); RESIGNAL; END; - CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); + CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse); IF !v_refresh THEN LEAVE proc; @@ -15,22 +15,23 @@ proc: BEGIN -- Calculamos el stock hasta ayer - CALL `cache`.stock_refresh(false); + CALL cache.stock_refresh(false); CREATE OR REPLACE TEMPORARY TABLE tmp.itemVisible (PRIMARY KEY (item_id)) ENGINE = MEMORY - SELECT item_id, amount stock, amount visible FROM `cache`.stock + SELECT item_id, amount stock, amount visible + FROM cache.stock WHERE warehouse_id = v_warehouse; -- Calculamos los movimientos confirmados de hoy - CALL vn.item_GetVisible(v_warehouse, NULL); + CALL vn.item_calcVisible(NULL, v_warehouse); DELETE FROM visible WHERE calc_id = v_calc; INSERT INTO visible (calc_id, item_id,visible) SELECT v_calc, item_id, visible FROM tmp.itemVisible; - CALL cache_calc_end (v_calc); + CALL cache_calc_end (v_calc); DROP TEMPORARY TABLE tmp.itemVisible; END$$ diff --git a/db/routines/edi/procedures/ekt_refresh.sql b/db/routines/edi/procedures/ekt_refresh.sql index 0e9ed7d3c..8ba438c0a 100644 --- a/db/routines/edi/procedures/ekt_refresh.sql +++ b/db/routines/edi/procedures/ekt_refresh.sql @@ -7,7 +7,6 @@ BEGIN */ DECLARE vRewriteKop INT DEFAULT NULL; DECLARE vTruncatePutOrder INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; DECLARE vKop INT; DECLARE vPutOrderFk BIGINT; @@ -16,17 +15,6 @@ BEGIN FROM ekt WHERE id = vSelf; - -- Generates the barcode - - SELECT CONCAT( - LPAD(IFNULL(auction,0), 3, 0), - LPAD(IFNULL(klo, 99), 2, 0), - LPAD(DAYOFYEAR(fec), 3, 0), - COALESCE(agj, RIGHT(batchNumber,7), id)) - INTO vBarcode - FROM ekt - WHERE id = vSelf; - -- Rewrites the kop parameter IF vKop IS NULL THEN @@ -46,10 +34,9 @@ BEGIN -- Refresh EKT - UPDATE ekt SET - barcode = vBarcode - ,kop = vKop - ,putOrderFk = vTruncatePutOrder + UPDATE ekt + SET kop = vKop, + putOrderFk = vTruncatePutOrder WHERE id = vSelf; END$$ DELIMITER ; diff --git a/db/routines/edi/views/ektRecent.sql b/db/routines/edi/views/ektRecent.sql index 3e41490ab..66ff7875e 100644 --- a/db/routines/edi/views/ektRecent.sql +++ b/db/routines/edi/views/ektRecent.sql @@ -2,7 +2,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `edi`.`ektRecent` AS SELECT `e`.`id` AS `id`, - `e`.`barcode` AS `barcode`, `e`.`entryYear` AS `entryYear`, `e`.`batchNumber` AS `batchNumber`, `e`.`deliveryNumber` AS `deliveryNumber`, diff --git a/db/routines/floranet/events/clean.sql b/db/routines/floranet/events/clean.sql deleted file mode 100644 index 4477112fd..000000000 --- a/db/routines/floranet/events/clean.sql +++ /dev/null @@ -1,22 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE - DEFINER=`root`@`localhost` - EVENT `floranet`.`clean` - ON SCHEDULE EVERY 1 DAY - STARTS '2024-01-01 23:00:00.000' - ON COMPLETION PRESERVE - ENABLE -DO -BEGIN - DELETE - FROM `order` - WHERE created < CURDATE() - AND isPaid = FALSE; - - DELETE c.* - FROM catalogue c - LEFT JOIN `order` o ON o.catalogueFk = c.id - WHERE c.created < CURDATE() - AND o.id IS NULL; -END$$ -DELIMITER ; \ No newline at end of file diff --git a/db/routines/floranet/procedures/catalogue_get.sql b/db/routines/floranet/procedures/catalogue_get.sql index 7ce32cfac..1e224c810 100644 --- a/db/routines/floranet/procedures/catalogue_get.sql +++ b/db/routines/floranet/procedures/catalogue_get.sql @@ -1,16 +1,15 @@ -DROP PROCEDURE IF EXISTS floranet.catalogue_get; - DELIMITER $$ $$ -CREATE DEFINER=`root`@`localhost` PROCEDURE floranet.catalogue_get(vLanded DATE, vPostalCode VARCHAR(15)) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE floranet.catalogue_get(vLanded DATE, vPostalCode VARCHAR(15)) READS SQL DATA proc:BEGIN /** - * Returns list, price and all the stuff regarding the floranet items. + * Returns list, price and all the stuff regarding the floranet items, for the designed shop * * @param vLanded Delivery date * @param vPostalCode Delivery address postal code */ + DECLARE vAddressFk INT; DECLARE vLastCatalogueFk INT; DECLARE vLockName VARCHAR(20); DECLARE vLockTime INT; @@ -21,7 +20,7 @@ proc:BEGIN RESIGNAL; END; - + SET vLockName = 'catalogue_get'; SET vLockTime = 15; @@ -32,6 +31,15 @@ proc:BEGIN SELECT MAX(id) INTO vLastCatalogueFk FROM catalogue; + SELECT addressFk + INTO vAddressFk + FROM addressPostCode apc + WHERE apc.dayOfWeek = dayOfWeek(vLanded) + AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR + AND apc.postCode = vPostalCode + -- Aquí hay que incluir los criterios de selección de tienda + LIMIT 1; + INSERT INTO catalogue( name, price, @@ -51,17 +59,14 @@ proc:BEGIN it.name, CONCAT('https://cdn.verdnatura.es/image/catalog/1600x900/', i.image), i.description, - apc.addressFk + vAddressFk FROM vn.item i JOIN (SELECT itemFk, SUM(quantity * cost) price FROM recipe GROUP BY itemFk) r ON r.itemFk = i.id JOIN vn.itemType it ON it.id = i.typeFk - JOIN addressPostCode apc - ON apc.dayOfWeek = dayOfWeek(vLanded) - AND NOW() < vLanded - INTERVAL apc.hoursInAdvance HOUR - AND apc.postCode = vPostalCode - JOIN vn.address a ON a.id = apc.addressFk; + JOIN addressPostCode apc ON addressFk = vAddressFk + JOIN vn.address a ON a.id = vAddressFk; SELECT * FROM catalogue diff --git a/db/routines/floranet/procedures/deliveryDate_get.sql b/db/routines/floranet/procedures/deliveryDate_get.sql index a235e8c31..70cb48818 100644 --- a/db/routines/floranet/procedures/deliveryDate_get.sql +++ b/db/routines/floranet/procedures/deliveryDate_get.sql @@ -1,8 +1,6 @@ -DROP PROCEDURE IF EXISTS floranet.deliveryDate_get; - DELIMITER $$ $$ -CREATE DEFINER=`root`@`localhost` PROCEDURE `floranet`.`deliveryDate_get`(vPostalCode VARCHAR(15)) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `floranet`.`deliveryDate_get`(vPostalCode VARCHAR(15)) READS SQL DATA BEGIN /** diff --git a/db/routines/floranet/procedures/order_confirm.sql b/db/routines/floranet/procedures/order_confirm.sql index 3b9413da9..98e15bbab 100644 --- a/db/routines/floranet/procedures/order_confirm.sql +++ b/db/routines/floranet/procedures/order_confirm.sql @@ -101,7 +101,7 @@ proc:BEGIN vNewTicketFk, c.itemFk, CONCAT('Entrega: ',c.name), - - c.price, + - apc.deliveryCost, 1 FROM catalogue c JOIN addressPostCode apc @@ -119,7 +119,7 @@ proc:BEGIN vNewTicketFk, r.elementFk, i.longName, - r.cost, + 0, r.quantity FROM catalogue c JOIN recipe r ON r.itemFk = c.itemFk diff --git a/db/routines/hedera/procedures/item_calcCatalog.sql b/db/routines/hedera/procedures/item_calcCatalog.sql index e72c2fd06..fae89bd5c 100644 --- a/db/routines/hedera/procedures/item_calcCatalog.sql +++ b/db/routines/hedera/procedures/item_calcCatalog.sql @@ -25,11 +25,7 @@ BEGIN JOIN vn.warehouse w ON w.id = p.warehouseFk ORDER BY warehouseFk, `grouping`; - DROP TEMPORARY TABLE - tmp.ticketCalculateItem, - tmp.ticketComponentPrice, - tmp.ticketComponent, - tmp.ticketLot, - tmp.zoneGetShipped; + CALL vn.ticketCalculatePurge(); + DROP TEMPORARY TABLE tmp.item; END$$ DELIMITER ; diff --git a/db/routines/hedera/procedures/order_addItem.sql b/db/routines/hedera/procedures/order_addItem.sql index d9c15c0eb..f690f9aa6 100644 --- a/db/routines/hedera/procedures/order_addItem.sql +++ b/db/routines/hedera/procedures/order_addItem.sql @@ -56,11 +56,23 @@ BEGIN CALL util.throw ('ORDER_ROW_UNAVAILABLE'); END IF; - SELECT IFNULL(minQuantity, 0) INTO vMinQuantity - FROM vn.item - WHERE id = vItem; + WITH itemMinQuantityPriority AS ( + SELECT quantity, + ROW_NUMBER() OVER ( + PARTITION BY itemFk + ORDER BY warehouseFk IS NULL + ) priority + FROM vn.itemMinimumQuantity + WHERE itemFk = vItem + AND `started` <= vShipment + AND (`ended` >= vShipment OR `ended` IS NULL) + AND (warehouseFk = vWarehouse OR warehouseFk IS NULL) + ) + SELECT quantity INTO vMinQuantity + FROM itemMinQuantityPriority + WHERE priority = 1; - IF vAmount < LEAST(vMinQuantity, vAvailable) THEN + IF vAmount < LEAST(IFNULL(vMinQuantity, 0), vAvailable) THEN CALL util.throw ('quantityLessThanMin'); END IF; diff --git a/db/routines/pbx/views/queueConf.sql b/db/routines/pbx/views/queueConf.sql index 07c241589..107989801 100644 --- a/db/routines/pbx/views/queueConf.sql +++ b/db/routines/pbx/views/queueConf.sql @@ -10,5 +10,5 @@ AS SELECT `q`.`name` AS `name`, `c`.`ringInUse` AS `ringinuse` FROM ( `pbx`.`queue` `q` - JOIN `pbx`.`queueConfig` `c` ON(`q`.`config` = `c`.`id`) + JOIN `pbx`.`queueMultiConfig` `c` ON(`q`.`config` = `c`.`id`) ) diff --git a/db/routines/sage/procedures/accountingMovements_add.sql b/db/routines/sage/procedures/accountingMovements_add.sql index ada954334..8c129beb2 100644 --- a/db/routines/sage/procedures/accountingMovements_add.sql +++ b/db/routines/sage/procedures/accountingMovements_add.sql @@ -410,15 +410,26 @@ BEGIN FROM sage.movConta mc JOIN vn.supplier s ON s.account = mc.CodigoCuenta WHERE NOT enlazadoSage - )SELECT idClientSupplier, `type` + ),clientSupplierSync AS( + SELECT idClientSupplier, `type` + FROM sage.clientSupplier cs + WHERE isSync + ) + SELECT idClientSupplier, `type` FROM sage.clientSupplier cs WHERE NOT isSync UNION SELECT id, 'C' - FROM client + FROM client c + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = c.id + AND cs.Type ='C' + WHERE cs.idClientSupplier IS NULL UNION SELECT id, 'P' - FROM supplier; + FROM supplier s + LEFT JOIN clientSupplierSync cs ON cs.idClientSupplier = s.id + AND cs.Type ='P' + WHERE cs.idClientSupplier IS NULL; CALL clientSupplier_add(vCompanyFk); diff --git a/db/routines/vn/events/claim_changeState.sql b/db/routines/vn/events/claim_changeState.sql new file mode 100644 index 000000000..5d94170a0 --- /dev/null +++ b/db/routines/vn/events/claim_changeState.sql @@ -0,0 +1,22 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`claim_changeState` + ON SCHEDULE EVERY 1 DAY + STARTS '2024-06-06 07:52:46.000' + ON COMPLETION PRESERVE + ENABLE +DO BEGIN + + DECLARE vClaimState INT; + + SELECT id INTO vClaimState + FROM claimState cs + WHERE cs.code = 'canceled'; + + UPDATE claim c + JOIN claimState cs ON cs.id = c.claimStateFk + SET c.claimStateFk = vClaimState + WHERE c.created < util.VN_CURDATE() - INTERVAL 2 MONTH + AND cs.code IN('incomplete','coming','waiting','out'); + +END$$ +DELIMITER ; diff --git a/db/routines/vn/events/itemShelvingSale_doReserve.sql b/db/routines/vn/events/itemShelvingSale_doReserve.sql new file mode 100644 index 000000000..228886556 --- /dev/null +++ b/db/routines/vn/events/itemShelvingSale_doReserve.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` EVENT `vn`.`itemShelvingSale_doReserve` + ON SCHEDULE EVERY 15 SECOND + STARTS '2023-10-16 00:00:00' + ON COMPLETION PRESERVE + ENABLE +DO CALL vn.itemShelvingSale_doReserve$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/functions/ticket_get.sql b/db/routines/vn/functions/ticket_get.sql index 1f0e9a25a..b55b1297e 100644 --- a/db/routines/vn/functions/ticket_get.sql +++ b/db/routines/vn/functions/ticket_get.sql @@ -1,64 +1,44 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_get`(vParamFk INT) - RETURNS int(11) + RETURNS INT(11) NOT DETERMINISTIC 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; +BEGIN +/** + * Devuelve el número de ticket / collection / sectorCollection consultando + * en que tabla se encuantra en la última semana + * + * @param vParamFk Número a validar + * @return vReturn Identificador validado + */ + DECLARE vReturn INT DEFAULT NULL; + DECLARE vDated DATE; - -- 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 - WHERE sg.id = vParamFk - AND sg.created > TIMESTAMPADD(WEEK,-1, util.VN_CURDATE()) - LIMIT 1; - - IF vValidFk THEN - - RETURN vValidFk; - - LEAVE proc; - - END IF; + SET vDated = util.VN_CURDATE() - INTERVAL 1 WEEK; - -- Tabla vn.collection - SELECT c.id INTO vValidFk - 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; + SELECT COALESCE( + (SELECT s.ticketFk + FROM sale s + JOIN saleGroupDetail sgd ON sgd.saleFk = s.id + JOIN saleGroup sg ON sg.id = sgd.saleGroupFk + WHERE sg.id = vParamFk + AND sg.created > vDated + LIMIT 1), + (SELECT c.id + FROM collection c + WHERE c.id = vParamFk + AND c.created > vDated), + (SELECT id + FROM ticket + WHERE id = vParamFk + AND shipped > vDated), + (SELECT id + FROM sectorCollection + WHERE id = vParamFk + AND created > vDated) + ) INTO vReturn; - -- Tabla vn.ticket - SELECT t.id INTO vValidFk - 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; + RETURN vReturn; END$$ DELIMITER ; diff --git a/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql b/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql new file mode 100644 index 000000000..4974a8c76 --- /dev/null +++ b/db/routines/vn/functions/ticket_isProblemCalcNeeded.sql @@ -0,0 +1,27 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION `vn`.`ticket_isProblemCalcNeeded`( + vSelf INT +) + RETURNS BOOL + DETERMINISTIC +BEGIN +/** + * Check if the ticket requires to update column vn.ticket.problem + * + * @param vSelf Id ticket + * @return BOOL + */ + DECLARE vIsProblemCalcNeeded BOOL; + + SELECT COUNT(*) INTO vIsProblemCalcNeeded + FROM ticket t + JOIN client c ON c.id = t.clientFk + JOIN agencyMode am ON am.id = t.agencyModeFk + JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk + WHERE t.id = vSelf + AND dm.code IN ('AGENCY','DELIVERY','PICKUP') + AND c.typeFk = 'normal'; + + RETURN vIsProblemCalcNeeded; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/XDiario_check.sql b/db/routines/vn/procedures/XDiario_check.sql index 0fb1c410d..ef969924b 100644 --- a/db/routines/vn/procedures/XDiario_check.sql +++ b/db/routines/vn/procedures/XDiario_check.sql @@ -6,19 +6,6 @@ BEGIN * identificando y notificando los asientos descuadrados * y ajustando los saldos en caso necesario. */ - INSERT INTO mail (receiver, subject, body) - SELECT 'cau@verdnatura.es', - 'Asientos descuadrados', - GROUP_CONCAT(CONCAT(' Asiento: ', ASIEN, ' - Importe:', recon) SEPARATOR ' | \n') - FROM ( - SELECT ASIEN, - SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0)) recon - FROM XDiario - WHERE NOT enlazado - GROUP BY ASIEN - HAVING ABS(SUM(IFNULL(ROUND(Eurodebe, 2), 0)) - SUM(IFNULL(ROUND(EUROHABER, 2), 0))) > 0.01 - ) sub - HAVING COUNT(*); UPDATE XDiario xd JOIN ( diff --git a/db/routines/vn/procedures/address_updateCoordinates.sql b/db/routines/vn/procedures/address_updateCoordinates.sql new file mode 100644 index 000000000..bdeb886df --- /dev/null +++ b/db/routines/vn/procedures/address_updateCoordinates.sql @@ -0,0 +1,25 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`address_updateCoordinates`( + vTicketFk INT, + vLongitude INT, + vLatitude INT) +BEGIN +/** + * Actualiza las coordenadas de una dirección. + * + * @param vTicketFk Id del ticket + * @param vLongitude Longitud de la dirección + * @param vLatitude Latitud de la dirección + */ + DECLARE vAddressFK INT; + + SELECT addressFK INTO vAddressFK + FROM ticket + WHERE id = vTicketFk; + + UPDATE address + SET longitude = vLongitude, + latitude = vLatitude + WHERE id = vAddressFK; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/buyUltimate.sql b/db/routines/vn/procedures/buyUltimate.sql index 4346ef640..98b16cbc0 100644 --- a/db/routines/vn/procedures/buyUltimate.sql +++ b/db/routines/vn/procedures/buyUltimate.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`(vWarehouseFk SMALLINT, vDated DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimate`( + vWarehouseFk SMALLINT, + vDated DATE +) BEGIN /** * Calcula las últimas compras realizadas hasta una fecha @@ -19,21 +22,22 @@ BEGIN FROM cache.last_buy WHERE warehouse_id = vWarehouseFk OR vWarehouseFk IS NULL; - CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); + IF vDated >= util.VN_CURDATE() THEN + CALL buyUltimateFromInterval(vWarehouseFk, util.VN_CURDATE(), vDated); - REPLACE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed <= vDated - AND NOT isIgnored; - - INSERT IGNORE INTO tmp.buyUltimate - SELECT itemFk, buyFk, warehouseFk, landed landing - FROM tmp.buyUltimateFromInterval - WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) - AND landed > vDated - ORDER BY isIgnored = FALSE DESC; + REPLACE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed <= vDated + AND NOT isIgnored; + INSERT IGNORE INTO tmp.buyUltimate + SELECT itemFk, buyFk, warehouseFk, landed landing + FROM tmp.buyUltimateFromInterval + WHERE (warehouseFk = vWarehouseFk OR vWarehouseFk IS NULL) + AND landed > vDated + ORDER BY isIgnored = FALSE DESC; + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/buyUltimateFromInterval.sql b/db/routines/vn/procedures/buyUltimateFromInterval.sql index e264b500d..5879b58e1 100644 --- a/db/routines/vn/procedures/buyUltimateFromInterval.sql +++ b/db/routines/vn/procedures/buyUltimateFromInterval.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`(vWarehouseFk SMALLINT, vStarted DATE, vEnded DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`buyUltimateFromInterval`( + vWarehouseFk SMALLINT, + vStarted DATE, + vEnded DATE +) BEGIN /** * Calcula las últimas compras realizadas @@ -21,12 +25,13 @@ BEGIN -- Item DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimateFromInterval; CREATE TEMPORARY TABLE tmp.buyUltimateFromInterval - (PRIMARY KEY (itemFk, warehouseFk), INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) + (PRIMARY KEY (itemFk, warehouseFk), + INDEX(buyFk), INDEX(landed), INDEX(warehouseFk), INDEX(itemFk)) ENGINE = MEMORY SELECT itemFk, warehouseFk, buyFk, - MAX(landed) landed, + landed, isIgnored FROM (SELECT b.itemFk, t.warehouseInFk warehouseFk, @@ -45,93 +50,117 @@ BEGIN INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed > vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - GROUP BY itemFk, warehouseInFk; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.quantity = 0 - GROUP BY itemFk, warehouseInFk; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + ORDER BY NOT b.isIgnored DESC, t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; -- ItemOriginal INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) SELECT itemFk, - warehouseFk, - buyFk, - MAX(landed) landed, - isIgnored - FROM (SELECT b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - itemOriginalFk, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND b.quantity > 0 - AND itemOriginalFk - ORDER BY t.landed DESC, b.id DESC - LIMIT 10000000000000000000) sub - GROUP BY itemOriginalFk, warehouseFk; + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + itemOriginalFk, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND b.quantity > 0 + AND itemOriginalFk + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; + INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed > vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.price2 > 0 + AND NOT b.isIgnored + AND itemOriginalFk + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed > vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.price2 > 0 - AND NOT b.isIgnored - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; - - INSERT IGNORE INTO tmp.buyUltimateFromInterval(itemFk, warehouseFk, buyFk, landed, isIgnored) - SELECT - b.itemFk, - t.warehouseInFk warehouseFk, - b.id buyFk, - t.landed, - b.isIgnored - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - WHERE t.landed BETWEEN vStarted AND vEnded - AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) - AND b.quantity = 0 - AND itemOriginalFk - GROUP BY itemOriginalFk, warehouseInFk; + SELECT itemFk, + warehouseFk, + buyFk, + landed, + isIgnored + FROM + (SELECT b.itemFk, + t.warehouseInFk warehouseFk, + b.id buyFk, + t.landed, + b.isIgnored + FROM buy b + JOIN entry e ON e.id = b.entryFk + JOIN travel t ON t.id = e.travelFk + WHERE t.landed BETWEEN vStarted AND vEnded + AND (vWarehouseFk IS NULL OR t.warehouseInFk = vWarehouseFk) + AND b.quantity = 0 + AND itemOriginalFk + ORDER BY t.landed DESC, b.id DESC + LIMIT 10000000000000000000) sub + GROUP BY itemFk, warehouseFk; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/catalog_calculate.sql b/db/routines/vn/procedures/catalog_calculate.sql index bb52020df..963e33507 100644 --- a/db/routines/vn/procedures/catalog_calculate.sql +++ b/db/routines/vn/procedures/catalog_calculate.sql @@ -45,8 +45,7 @@ BEGIN CALL catalog_componentPrepare(); - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketCalculateItem( itemFk INT(11) NOT NULL, available INT(11), producer VARCHAR(50), @@ -60,11 +59,11 @@ BEGIN price DECIMAL(10,2), priceKg DECIMAL(10,2), `grouping` INT(10) UNSIGNED, + minQuantity INT(10) UNSIGNED, PRIMARY KEY `itemFk` (`itemFk`) ) ENGINE = MEMORY DEFAULT CHARSET=utf8; OPEN cTravelTree; - l: LOOP SET vDone = FALSE; FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; @@ -136,7 +135,7 @@ BEGIN CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); - INSERT INTO tmp.ticketCalculateItem ( + INSERT INTO tmp.ticketCalculateItem( itemFk, available, producer, @@ -149,9 +148,9 @@ BEGIN origin, price, priceKg, - `grouping`) - SELECT - tl.itemFk, + `grouping`, + minQuantity) + SELECT tl.itemFk, SUM(tl.available) available, p.name producer, i.name item, @@ -163,7 +162,8 @@ BEGIN o.code origin, bl.price, bl.priceKg, - bl.`grouping` + bl.`grouping`, + mq.quantity FROM tmp.ticketLot tl JOIN item i ON tl.itemFk = i.id LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible @@ -179,12 +179,28 @@ BEGIN ) sub GROUP BY itemFk ) bl ON bl.itemFk = tl.itemFk - WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + LEFT JOIN ( + WITH itemMinQuantityPriority AS ( + SELECT itemFk, + quantity, + ROW_NUMBER() OVER ( + PARTITION BY itemFk + ORDER BY warehouseFk IS NULL + ) priority + FROM vn.itemMinimumQuantity + WHERE `started` <= vShipped + AND (`ended` >= vShipped OR `ended` IS NULL) + AND (warehouseFk = vWarehouseFk OR warehouseFk IS NULL) + ) + SELECT itemFk, quantity + FROM itemMinQuantityPriority + WHERE priority = 1 + ) mq ON mq.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk + AND tl.warehouseFk = vWarehouseFk GROUP BY tl.itemFk ON DUPLICATE KEY UPDATE available = available + VALUES(available); - END LOOP; - CLOSE cTravelTree; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/client_create.sql b/db/routines/vn/procedures/client_create.sql index d5d7258a1..f2321e129 100644 --- a/db/routines/vn/procedures/client_create.sql +++ b/db/routines/vn/procedures/client_create.sql @@ -34,20 +34,25 @@ BEGIN DECLARE vIsTaxDataChecked TINYINT(1); DECLARE vHasCoreVnl BOOLEAN; DECLARE vMandateTypeFk INT; + DECLARE vHasDailyInvoice BOOLEAN; - SELECT defaultPayMethodFk, - defaultDueDay, - defaultCredit, - defaultIsTaxDataChecked, - defaultHasCoreVnl, - defaultMandateTypeFk + SELECT cc.defaultPayMethodFk, + cc.defaultDueDay, + cc.defaultCredit, + cc.defaultIsTaxDataChecked, + cc.defaultHasCoreVnl, + cc.defaultMandateTypeFk, + c.hasDailyInvoice INTO vPayMethodFk, vDueDay, vDefaultCredit, vIsTaxDataChecked, vHasCoreVnl, - vMandateTypeFk - FROM clientConfig; + vMandateTypeFk, + vHasDailyInvoice + FROM clientConfig cc + LEFT JOIN province p ON p.id = vProvinceFk + LEFT JOIN country c ON c.id = p.countryFk; INSERT INTO `client` SET id = vUserFk, @@ -65,7 +70,8 @@ BEGIN credit = vDefaultCredit, isTaxDataChecked = vIsTaxDataChecked, hasCoreVnl = vHasCoreVnl, - isEqualizated = FALSE + isEqualizated = FALSE, + hasDailyInvoice = vHasDailyInvoice ON duplicate KEY UPDATE payMethodFk = vPayMethodFk, dueDay = vDueDay, diff --git a/db/routines/vn/procedures/client_unassignSalesPerson.sql b/db/routines/vn/procedures/client_unassignSalesPerson.sql index f939ae68b..8773104ca 100644 --- a/db/routines/vn/procedures/client_unassignSalesPerson.sql +++ b/db/routines/vn/procedures/client_unassignSalesPerson.sql @@ -26,6 +26,7 @@ BEGIN JOIN province p ON p.id = c.provinceFk LEFT JOIN autonomy a ON a.id = p.autonomyFk JOIN country co ON co.id = p.countryFk + JOIN bs.clientDiedPeriod cdp ON cdp.countryFk = co.id WHERE cd.warning = 'third' AND cp.clientFk IS NULL AND sp.salesPersonFk IS NULL diff --git a/db/routines/vn/procedures/collection_addWithReservation.sql b/db/routines/vn/procedures/collection_addWithReservation.sql new file mode 100644 index 000000000..e3f4eb8d2 --- /dev/null +++ b/db/routines/vn/procedures/collection_addWithReservation.sql @@ -0,0 +1,89 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_addWithReservation`( + vItemFk INT, + vQuantity INT, + vTicketFk INT, + vSaleGroupFk INT +) +BEGIN +/** + * En el ámbito de las colecciones se añade una línea de sale a un ticket + * de una colección en caso de tener disponible y se realiza la reserva. + * + * @param vItemFk id of item + * @param vQuantity quantity to be added to the ticket + * @param vTicketFk ticket to which the sales line is added + * @param vSaleGroupFk saleGroupFk id to add saleGroupDetail + */ + + DECLARE vWarehouseFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vAvailable INT; + DECLARE vSaleFk INT; + DECLARE vConcept VARCHAR(50); + DECLARE vItemName VARCHAR(50); + DECLARE vHasThrow BOOLEAN DEFAULT FALSE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT t.warehouseFk INTO vWarehouseFk + FROM ticket t + JOIN ticketCollection tc ON tc.ticketFk = t.id + WHERE t.id = vTicketFk; + + CALL cache.available_refresh( + vCacheAvailableFk, + FALSE, + vWarehouseFk, + util.VN_CURDATE()); + + SELECT available INTO vAvailable + FROM cache.available + WHERE calc_id = vCacheAvailableFk + AND item_id = vItemFk; + + IF vAvailable < vQuantity THEN + SET vHasThrow = TRUE; + ELSE + SELECT `name`, + CONCAT(getUser(), ' ', DATE_FORMAT(util.VN_NOW(), '%H:%i'), ' ', name) + INTO vItemName, vConcept + FROM item + WHERE id = vItemFk; + + START TRANSACTION; + + INSERT INTO sale + SET itemFk = vItemFk, + ticketFk = vTicketFk, + concept = vConcept, + quantity = vQuantity, + isAdded = TRUE; + + SELECT LAST_INSERT_ID() INTO vSaleFk; + + CALL sale_calculateComponent(vSaleFk, NULL); + CALL itemShelvingSale_addBySale(vSaleFk); + + IF NOT EXISTS (SELECT TRUE FROM itemShelvingSale WHERE saleFk = vSaleFk LIMIT 1) THEN + SET vHasThrow = TRUE; + END IF; + END IF; + + IF vHasThrow THEN + CALL util.throw("There is no available for the selected item"); + END IF; + + IF vSaleGroupFk THEN + INSERT INTO saleGroupDetail + SET saleFk = vSaleFk, + saleGroupFk = vSaleGroupFk; + END IF; + + COMMIT; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/collection_assign.sql b/db/routines/vn/procedures/collection_assign.sql index fc9f9a711..f9032a91d 100644 --- a/db/routines/vn/procedures/collection_assign.sql +++ b/db/routines/vn/procedures/collection_assign.sql @@ -13,21 +13,63 @@ BEGIN * @param vCollectionFk Id de colección */ DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; + + CALL util.debugAdd('collection_assign', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk + )); -- Tmp + + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + END IF; + RESIGNAL; + END; -- Si hay colecciones sin terminar, sale del proceso CALL collection_get(vUserFk); - SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0 - INTO vHasTooMuchCollections + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName FROM productionConfig pc - LEFT JOIN tCollection ON TRUE; + LEFT JOIN tmp.collection ON TRUE; - DROP TEMPORARY TABLE tCollection; + DROP TEMPORARY TABLE tmp.collection; IF vHasTooMuchCollections THEN CALL util.throw('Hay colecciones pendientes'); END IF; + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + -- Se eliminan las colecciones sin asignar que estan obsoletas INSERT INTO ticketTracking(stateFk, ticketFk) SELECT s.id, tc.ticketFk @@ -35,7 +77,7 @@ BEGIN JOIN ticketCollection tc ON tc.collectionFk = c.id JOIN `state` s ON s.code = 'PRINTED_AUTO' JOIN productionConfig pc - WHERE c.workerFk IS NULL + WHERE c.workerFk IS NULL AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; DELETE c.* @@ -75,5 +117,7 @@ BEGIN UPDATE `collection` SET workerFk = vUserFk WHERE id = vCollectionFk; + + DO RELEASE_LOCK(vLockName); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_get.sql b/db/routines/vn/procedures/collection_get.sql index 372d963c0..d29f14ca9 100644 --- a/db/routines/vn/procedures/collection_get.sql +++ b/db/routines/vn/procedures/collection_get.sql @@ -7,27 +7,32 @@ BEGIN * @param vWorkerFk id del worker. * @table Devuelve tabla temporal con las colecciones pendientes */ - DROP TEMPORARY TABLE IF EXISTS tCollection; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; - CREATE TEMPORARY TABLE tCollection - 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 - 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 - AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge - AND s.quantity != 0 - AND s2.order < pc.pendingCollectionsOrder - GROUP BY c.id - HAVING COUNT(*) > COUNT(DISTINCT st.id); + CREATE OR REPLACE TEMPORARY TABLE tmp.collection + ENGINE = MEMORY + 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 + 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 + AND TIMESTAMPDIFF(HOUR, c.created , util.VN_NOW()) < pc.pendingCollectionsAge + AND s.quantity + AND s2.order < pc.pendingCollectionsOrder + GROUP BY c.id + HAVING COUNT(*) > COUNT(DISTINCT st.id); - SELECT * FROM tCollection; + SELECT * FROM tmp.collection; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_getAssigned.sql b/db/routines/vn/procedures/collection_getAssigned.sql new file mode 100644 index 000000000..947b53229 --- /dev/null +++ b/db/routines/vn/procedures/collection_getAssigned.sql @@ -0,0 +1,104 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getAssigned`( + vUserFk INT, + OUT vCollectionFk INT +) +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 y hace la reserva para la colección + * + * @param vUserFk Id de usuario + * @param vCollectionFk Id de colección + */ + DECLARE vHasTooMuchCollections BOOL; + DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vWarehouseFk INT; + DECLARE vLockName VARCHAR(215); + DECLARE vLockTime INT DEFAULT 30; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF vLockName IS NOT NULL THEN + DO RELEASE_LOCK(vLockName); + END IF; + + RESIGNAL; + END; + + -- Si hay colecciones sin terminar, sale del proceso + CALL collection_get(vUserFk); + + SELECT (pc.maxNotReadyCollections - COUNT(*)) <= 0, + pc.collection_assign_lockname + INTO vHasTooMuchCollections, + vLockName + FROM tmp.collection c + JOIN productionConfig pc; + + DROP TEMPORARY TABLE tmp.collection; + + IF vHasTooMuchCollections THEN + CALL util.throw('There are pending collections'); + END IF; + + SELECT warehouseFk, itemPackingTypeFk + INTO vWarehouseFk, vItemPackingTypeFk + FROM operator + WHERE workerFk = vUserFk; + + SET vLockName = CONCAT_WS('/', + vLockName, + vWarehouseFk, + vItemPackingTypeFk + ); + + IF NOT GET_LOCK(vLockName, vLockTime) THEN + CALL util.throw(CONCAT('Cannot get lock: ', vLockName)); + END IF; + + -- Se eliminan las colecciones sin asignar que estan obsoletas + INSERT INTO ticketTracking(stateFk, ticketFk) + SELECT s.id, tc.ticketFk + FROM collection c + JOIN ticketCollection tc ON tc.collectionFk = c.id + JOIN state s ON s.code = 'PRINTED_AUTO' + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + DELETE c + FROM collection c + JOIN productionConfig pc + WHERE c.workerFk IS NULL + AND TIMEDIFF(util.VN_NOW(), c.created) > pc.maxNotAssignedCollectionLifeTime; + + -- Se añade registro al semillero + INSERT INTO collectionHotbed + SET userFk = vUserFk; + + -- Comprueba si hay colecciones disponibles que se ajustan a su configuracion + SELECT MIN(c.id) INTO vCollectionFk + FROM collection c + JOIN operator o ON (o.itemPackingTypeFk = c.itemPackingTypeFk + OR c.itemPackingTypeFk IS NULL) + AND o.numberOfWagons = c.wagons + AND o.trainFk = c.trainFk + AND o.warehouseFk = c.warehouseFk + AND c.workerFk IS NULL + WHERE o.workerFk = vUserFk; + + IF vCollectionFk IS NULL THEN + CALL collection_new(vUserFk, vCollectionFk); + END IF; + + UPDATE collection + SET workerFk = vUserFk + WHERE id = vCollectionFk; + + CALL itemShelvingSale_addByCollection(vCollectionFk); + + DO RELEASE_LOCK(vLockName); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/collection_getTickets.sql b/db/routines/vn/procedures/collection_getTickets.sql index 0a71ada78..7ecff571a 100644 --- a/db/routines/vn/procedures/collection_getTickets.sql +++ b/db/routines/vn/procedures/collection_getTickets.sql @@ -2,61 +2,88 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_getTickets`(vParamFk INT) BEGIN /** - * Selecciona los tickets de una colección/ticket - * @param vParamFk ticketFk/collectionFk - * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observaciones + * Selecciona los tickets de una colección/ticket/sectorCollection + * @param vParamFk ticketFk/collectionFk/sectorCollection + * @return Retorna ticketFk, level, agencyName, warehouseFk, salesPersonFk, observation */ DECLARE vItemPackingTypeFk VARCHAR(1); + DECLARE vYesterday DATE; -- Si los sacadores son los de pruebas, pinta los colores - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection + SELECT itemPackingTypeFk + INTO vItemPackingTypeFk + FROM collection WHERE id = vParamFk; + + SET vYesterday = util.yesterday(); - SELECT t.id ticketFk, - IF (!(vItemPackingTypeFk <=> 'V'), cc.code,CONCAT(SUBSTRING('ABCDEFGH',tc.wagon, 1),'-',tc.`level` )) `level`, - am.name agencyName, - t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description,'') observaciones, - cc.rgb - 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` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 - 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 - AND tob.observationTypeFk = 1 - WHERE t.id = vParamFk - AND t.shipped >= util.yesterday() - UNION ALL + WITH observation AS ( + SELECT tob.ticketFk, tob.description + FROM vn.ticketObservation tob + JOIN vn.ticketCollection tc ON tc.ticketFk = tob.ticketFk + LEFT JOIN vn.observationType ot ON ot.id = tob.observationTypeFk + WHERE ot.`code` = 'itemPicker' + AND tc.collectionFk = vParamFk + ) SELECT t.id ticketFk, IF(!(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, am.name agencyName, t.warehouseFk, - w.id salesPersonFk, - IFNULL(tob.description, '') observaciones, - IF(!(vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + w.id salesPersonFk, + IFNULL(ob.description,'') observaciones, + cc.rgb 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.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk LEFT JOIN vn.collectionColors cc ON cc.wagon = tc.wagon - AND cc.shelve = tc.`level` - AND cc.trainFk = c2.trainFk -- PAK 23/12/21 + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk 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 - AND tob.observationTypeFk = 1 - WHERE tc.collectionFk = vParamFk; - + LEFT JOIN observation ob ON ob.ticketFk = t.id + WHERE t.id = vParamFk + AND t.shipped >= vYesterday + UNION ALL + SELECT t.id ticketFk, + IF(NOT(vItemPackingTypeFk <=> 'V'), cc.code, CONCAT(SUBSTRING('ABCDEFGH', tc.wagon, 1), '-', tc.`level`)) `level`, + am.name agencyName, + t.warehouseFk, + w.id salesPersonFk, + ob.description, + IF(NOT (vItemPackingTypeFk <=> 'V'), cc.rgb, NULL) `rgb` + FROM vn.ticket t + JOIN vn.ticketCollection tc ON t.id = tc.ticketFk + LEFT JOIN vn.collection c2 ON c2.id = tc.collectionFk + LEFT JOIN vn.collectionColors cc + ON cc.wagon = tc.wagon + AND cc.shelve = tc.`level` + AND cc.trainFk = c2.trainFk + 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 observation ob ON ob.ticketFk = t.id + WHERE tc.collectionFk = vParamFk + UNION ALL + SELECT sg.ticketFk, + NULL `level`, + am.name agencyName, + t.warehouseFk, + c.salesPersonFk, + ob.description, + NULL `rgb` + FROM vn.sectorCollection sc + JOIN vn.sectorCollectionSaleGroup ss ON ss.sectorCollectionFk = sc.id + JOIN vn.saleGroup sg ON sg.id = ss.saleGroupFk + JOIN vn.ticket t ON t.id = sg.ticketFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN observation ob ON ob.ticketFk = t.id + LEFT JOIN vn.client c ON c.id = t.clientFk + WHERE sc.id = vParamFk + AND t.shipped >= vYesterday; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/collection_new.sql b/db/routines/vn/procedures/collection_new.sql index b022d8dcc..0bd6e1b25 100644 --- a/db/routines/vn/procedures/collection_new.sql +++ b/db/routines/vn/procedures/collection_new.sql @@ -53,16 +53,17 @@ BEGIN vErrorNumber = MYSQL_ERRNO, vErrorMsg = MESSAGE_TEXT; + CALL util.debugAdd('collection_new', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'lockName', vLockName, + 'userFk', vUserFk, + 'ticketFk', vTicketFk + )); -- Tmp + IF vLockName IS NOT NULL THEN DO RELEASE_LOCK(vLockName); - CALL util.debugAdd('collection_new', JSON_OBJECT( - 'errorNumber', vErrorNumber, - 'errorMsg', vErrorMsg, - 'lockName', vLockName, - 'userFk', vUserFk - )); -- Tmp END IF; - RESIGNAL; END; diff --git a/db/routines/vn/procedures/collection_setParking.sql b/db/routines/vn/procedures/collection_setParking.sql index 73aa87bfb..5f6ca75da 100644 --- a/db/routines/vn/procedures/collection_setParking.sql +++ b/db/routines/vn/procedures/collection_setParking.sql @@ -1,15 +1,18 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`(IN `vCollectionFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`collection_setParking`( + vSelf INT, + vParkingFk INT +) +BEGIN /** * Aparca una colección en un parking. * - * @param vCollectionFk Id de la colección - * @param vParkingFk Id del parking + * @param vSelf Id colección + * @param vParkingFk Id parking */ - REPLACE vn.ticketParking(ticketFk, parkingFk) + REPLACE ticketParking(ticketFk, parkingFk) SELECT tc.ticketFk, vParkingFk - FROM vn.ticketCollection tc - WHERE tc.collectionFk = vCollectionFk; + FROM ticketCollection tc + WHERE tc.collectionFk = vSelf; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/company_getFiscaldata.sql b/db/routines/vn/procedures/company_getFiscaldata.sql index 7c56382e9..b59ae38e1 100644 --- a/db/routines/vn/procedures/company_getFiscaldata.sql +++ b/db/routines/vn/procedures/company_getFiscaldata.sql @@ -7,7 +7,7 @@ DECLARE vCompanyFk INT; SELECT IFNULL(uc.companyFk, rc.defaultCompanyFk) INTO vCompanyFk FROM vn.routeConfig rc - LEFT JOIN userConfig uc ON uc.userFk = workerFk; + LEFT JOIN userMultiConfig uc ON uc.userFk = workerFk; SELECT diff --git a/db/routines/vn/procedures/copyComponentsFromSaleList.sql b/db/routines/vn/procedures/copyComponentsFromSaleList.sql index 17cf487b1..8db8409f1 100644 --- a/db/routines/vn/procedures/copyComponentsFromSaleList.sql +++ b/db/routines/vn/procedures/copyComponentsFromSaleList.sql @@ -16,9 +16,9 @@ BEGIN SET @order = 0; - DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList; + DROP TEMPORARY TABLE IF EXISTS tNewSaleList; - CREATE TEMPORARY TABLE tmp.newSaleList + CREATE TEMPORARY TABLE tNewSaleList SELECT id as saleFk, @order := @order + 1 as orden FROM vn.sale WHERE ticketFk = vTargetTicketFk @@ -28,7 +28,8 @@ BEGIN SELECT ns.saleFk, sc.componentFk, sc.value FROM vn.saleComponent sc JOIN tmp.saleList s ON s.saleFk = sc.saleFk - JOIN tmp.newSaleList ns ON ns.orden = s.orden; + JOIN tNewSaleList ns ON ns.orden = s.orden; + DROP TEMPORARY TABLE tNewSaleList; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/duaInvoiceInBooking.sql b/db/routines/vn/procedures/duaInvoiceInBooking.sql index 1f026e96b..10c0714e5 100644 --- a/db/routines/vn/procedures/duaInvoiceInBooking.sql +++ b/db/routines/vn/procedures/duaInvoiceInBooking.sql @@ -36,7 +36,7 @@ BEGIN SELECT ASIEN INTO vBookEntry FROM dua WHERE id = vDuaFk; - IF vBookEntry IS NULL THEN + IF vBookEntry IS NULL THEN SELECT YEAR(IFNULL(ii.bookEntried, d.bookEntried)) INTO vFiscalYear FROM invoiceIn ii JOIN `entry` e ON e.invoiceInFk = ii.id @@ -45,7 +45,7 @@ BEGIN WHERE d.id = vDuaFk LIMIT 1; CALL ledger_nextTx(vFiscalYear, vBookEntry); - END IF; + END IF; OPEN vInvoicesIn; @@ -75,14 +75,14 @@ BEGIN JOIN ( WITH entries AS ( SELECT e.id, de.duaFk - FROM `entry` e - JOIN duaEntry de ON de.entryFk = e.id + FROM vn.`entry` e + JOIN vn.duaEntry de ON de.entryFk = e.id WHERE de.duaFk = vDuaFk AND (NOT e.isBooked OR NOT e.isConfirmed) ), notBookedEntries AS ( - SELECT e.id - FROM duaEntry + SELECT entryFk + FROM vn.duaEntry WHERE duaFk = vDuaFk AND NOT customsValue ) diff --git a/db/routines/vn/procedures/entry_isEditable.sql b/db/routines/vn/procedures/entry_isEditable.sql index a05a1fd92..c279fac65 100644 --- a/db/routines/vn/procedures/entry_isEditable.sql +++ b/db/routines/vn/procedures/entry_isEditable.sql @@ -18,7 +18,7 @@ BEGIN AND e.id = vSelf; IF vIsEditable AND NOT IFNULL(@isModeInventory, FALSE) THEN - CALL util.throw('Entry is not editable'); + CALL util.throw(CONCAT('Entry ', vSelf, ' is not editable')); END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/entry_splitByShelving.sql b/db/routines/vn/procedures/entry_splitByShelving.sql index 2898141ea..eb07c12b7 100644 --- a/db/routines/vn/procedures/entry_splitByShelving.sql +++ b/db/routines/vn/procedures/entry_splitByShelving.sql @@ -13,60 +13,45 @@ 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 + FROM itemShelving ish 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 - 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, - 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 + FROM 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) + AND bb.stickers >= FLOOR(ish.visible / ish.packing) + WHERE ish.shelvingFk = vShelvingFk COLLATE utf8_general_ci + AND NOT ish.isSplit GROUP BY ish.id; - + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + 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 + UPDATE buy SET entryFk = vToEntryFk WHERE id = vBuyFk; ELSE - UPDATE vn.buy + UPDATE buy SET stickers = stickers - vIshStickers, quantity = stickers * packing WHERE id = vBuyFk; - - INSERT INTO vn.buy(entryFk, + + INSERT INTO buy(entryFk, itemFk, quantity, buyingValue, @@ -117,13 +102,16 @@ BEGIN weight, deliveryFk, itemOriginalFk - FROM vn.buy + FROM buy WHERE id = vBuyFk; UPDATE buy SET printedStickers = vIshStickers WHERE id = LAST_INSERT_ID(); END IF; - END LOOP; + UPDATE itemShelving + SET isSplit = TRUE + WHERE shelvingFk = vShelvingFk; + END LOOP; CLOSE cur; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/expeditionPallet_printLabel.sql b/db/routines/vn/procedures/expeditionPallet_printLabel.sql index ada11daab..7aaf8cedb 100644 --- a/db/routines/vn/procedures/expeditionPallet_printLabel.sql +++ b/db/routines/vn/procedures/expeditionPallet_printLabel.sql @@ -9,7 +9,16 @@ BEGIN */ DECLARE vPrinterFk INT; DECLARE vUserFk INT DEFAULT account.myUser_getId(); - + DECLARE vIsInExpeditionPallet BOOL; + + SELECT COUNT(id) INTO vIsInExpeditionPallet + FROM expeditionPallet + WHERE id = vSelf; + + IF NOT vIsInExpeditionPallet THEN + CALL util.throw("ExpeditionPallet not exists"); + END IF; + SELECT o.labelerFk INTO vPrinterFk FROM operator o WHERE o.workerFk = vUserFk; diff --git a/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql index 60ec34696..962cc5224 100644 --- a/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql +++ b/db/routines/vn/procedures/invoiceInTax_afterUpsert.sql @@ -8,7 +8,6 @@ BEGIN */ DECLARE vTaxRowLimit INT; DECLARE vLines INT; - DECLARE vHasDistinctTransactions INT; SELECT taxRowLimit INTO vTaxRowLimit FROM invoiceInConfig; @@ -20,17 +19,5 @@ BEGIN IF vLines >= vTaxRowLimit THEN CALL util.throw (CONCAT('The maximum number of lines is ', vTaxRowLimit)); END IF; - - SELECT COUNT(DISTINCT transactionTypeSageFk) INTO vHasDistinctTransactions - FROM invoiceIn ii - JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN invoiceInSerial iis ON iis.code = ii.serial - WHERE ii.id = vInvoiceInFk - AND iis.taxAreaFk = 'CEE' - AND transactionTypeSageFk; - - IF vHasDistinctTransactions > 1 THEN - CALL util.throw ('This invoice does not allow different types of transactions'); - END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/invoiceIn_booking.sql b/db/routines/vn/procedures/invoiceIn_booking.sql index ef124bb46..c194a774d 100644 --- a/db/routines/vn/procedures/invoiceIn_booking.sql +++ b/db/routines/vn/procedures/invoiceIn_booking.sql @@ -13,6 +13,31 @@ BEGIN * @param vBookEntry Id de asiento, si es NULL se genera uno nuevo */ DECLARE vFiscalYear INT; + DECLARE vDistinctTransactions INT; + DECLARE vHasRepeatedTransactions BOOL; + + SELECT COUNT(DISTINCT iit.transactionTypeSageFk) INTO vDistinctTransactions + FROM invoiceIn ii + JOIN invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN invoiceInSerial iis ON iis.code = ii.serial + WHERE iit.invoiceInFk = vSelf + AND iis.taxAreaFk = 'CEE' + AND iit.transactionTypeSageFk; + + IF vDistinctTransactions > 1 THEN + CALL util.throw ('This invoice does not allow different types of transactions'); + END IF; + + SELECT TRUE INTO vHasRepeatedTransactions + FROM invoiceInTax + WHERE invoiceInFk = vSelf + GROUP BY transactionTypeSageFk + HAVING COUNT(transactionTypeSageFk) > 1 + LIMIT 1; + + IF vHasRepeatedTransactions THEN + CALL util.throw ('This invoice contains repeated types of transactions'); + END IF; CREATE OR REPLACE TEMPORARY TABLE tInvoiceIn ENGINE = MEMORY diff --git a/db/routines/vn/procedures/invoiceOut_new.sql b/db/routines/vn/procedures/invoiceOut_new.sql index 42c3f99da..c9b94027e 100644 --- a/db/routines/vn/procedures/invoiceOut_new.sql +++ b/db/routines/vn/procedures/invoiceOut_new.sql @@ -216,7 +216,7 @@ BEGIN i.transactionTypeSageFk, @vTaxCodeGeneral := i.taxClassCodeFk FROM tmp.ticketServiceTax tst - JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tst.code + JOIN invoiceOutTaxMultiConfig i ON i.taxClassCodeFk = tst.code WHERE i.isService HAVING taxableBase ) sub; @@ -229,7 +229,7 @@ BEGIN i.taxTypeSageFk , i.transactionTypeSageFk FROM tmp.ticketTax tt - JOIN invoiceOutTaxConfig i ON i.taxClassCodeFk = tt.code + JOIN invoiceOutTaxMultiConfig i ON i.taxClassCodeFk = tt.code WHERE !i.isService GROUP BY tt.pgcFk HAVING taxableBase diff --git a/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql new file mode 100644 index 000000000..7f9cc6616 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_addByCollection.sql @@ -0,0 +1,51 @@ + +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addByCollection`( + vCollectionFk INT(11) +) +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una colección + * + * @param vCollectionFk Identificador de collection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + WITH sales AS ( + SELECT s.id saleFk, s.quantity, SUM(IFNULL(iss.quantity, 0)) quantityReserved + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + LEFT JOIN vn.itemShelvingSale iss ON iss.saleFk = s.id + WHERE tc.collectionFk = vCollectionFk + GROUP BY s.id + HAVING quantity <> quantityReserved + ), trackedSales AS ( + SELECT sa.saleFk + FROM sales sa + JOIN vn.saleTracking st ON st.saleFk = sa.saleFk + JOIN vn.`state` s ON s.id = st.stateFk + WHERE st.isChecked + AND s.`code` IN ('PREVIOUS_PREPARATION', 'OK PREVIOUS', 'OK STOWAWAY') + GROUP BY sa.saleFk + ) SELECT s.saleFk + FROM sales s + LEFT JOIN trackedSales ts ON ts.saleFk = s.saleFk + WHERE ts.saleFk IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySale.sql b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql new file mode 100644 index 000000000..909ce5155 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_addBySale.sql @@ -0,0 +1,114 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_addBySale`( + vSaleFk INT +) +proc: BEGIN +/** + * Reserva una línea de venta en la ubicación más óptima + * + * @param vSaleFk Id de sale + * @param vItemShelvingSaleFk Id de reserva + */ + DECLARE vLastPickingOrder INT; + DECLARE vDone INT DEFAULT FALSE; + DECLARE vItemShelvingFk INT; + DECLARE vAvailable INT; + DECLARE vReservedQuantity INT; + DECLARE vOutStanding INT; + DECLARE vUserFk INT; + DECLARE vTotalReservedQuantity INT; + DECLARE vSaleQuantity INT; + + DECLARE vItemShelvingAvailable CURSOR FOR + SELECT ish.id itemShelvingFk, + ish.available + FROM sale s + JOIN itemShelving ish ON ish.itemFk = s.itemFk + 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 productionConfig pc + WHERE s.id = vSaleFk + AND NOT sc.isHideForPickers + ORDER BY s.id, + p.pickingOrder >= vLastPickingOrder, + sh.priority DESC, + ish.available >= s.quantity DESC, + s.quantity MOD ish.grouping = 0 DESC, + ish.grouping DESC, + IF(pc.orderMode = 'Location', p.pickingOrder, ish.created); + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SELECT MAX(p.pickingOrder), s.quantity - SUM(IFNULL(iss.quantity, 0)), s.quantity + INTO vLastPickingOrder, vOutStanding, vSaleQuantity + FROM sale s + 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 + WHERE s.id = vSaleFk; + + IF vOutStanding <= 0 THEN + LEAVE proc; + END IF; + + SELECT getUser() INTO vUserFk; + + OPEN vItemShelvingAvailable; + l: LOOP + SET vDone = FALSE; + FETCH vItemShelvingAvailable INTO vItemShelvingFk, vAvailable; + + IF vOutStanding <= 0 OR vDone THEN + SELECT SUM(IFNULL(quantity, 0)) + INTO vTotalReservedQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vTotalReservedQuantity <> vSaleQuantity THEN + UPDATE sale + SET quantity = vTotalReservedQuantity + WHERE id = vSaleFk; + END IF; + LEAVE l; + END IF; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + SELECT LEAST(vOutStanding, vAvailable) INTO vReservedQuantity; + SET vOutStanding = vOutStanding - vReservedQuantity; + + IF vReservedQuantity > 0 THEN + + INSERT INTO itemShelvingSale( + itemShelvingFk, + saleFk, + quantity, + userFk) + SELECT vItemShelvingFk, + vSaleFk, + vReservedQuantity, + vUserFk; + + UPDATE itemShelving + SET available = available - vReservedQuantity + WHERE id = vItemShelvingFk; + + END IF; + + COMMIT; + END LOOP; + CLOSE vItemShelvingAvailable; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_addBySectorCollection.sql b/db/routines/vn/procedures/itemShelvingSale_addBySectorCollection.sql new file mode 100644 index 000000000..442abcf5d --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_addBySectorCollection.sql @@ -0,0 +1,41 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE + `vn`.`itemShelvingSale_addBySectorCollection`(vSectorCollectionFk INT(11)) +BEGIN +/** + * Reserva cantidades con ubicaciones para el contenido de una preparación previa + * de la cual ya tiene generada la asociación del saleGroup con sectorCollection + * + * @param vSectorCollectionFk Identificador de sectorCollection + */ + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vSaleFk INT; + DECLARE vSales CURSOR FOR + SELECT s.id + FROM sectorCollectionSaleGroup sc + JOIN saleGroupDetail sg ON sg.saleGroupFk = sc.saleGroupFk + JOIN sale s ON sg.saleFk = s.id + JOIN saleTracking str ON str.saleFk = s.id + JOIN `state` st ON st.id = str.stateFk + AND st.code = 'PREVIOUS_PREPARATION' + LEFT JOIN itemShelvingSale iss ON iss.saleFk = s.id + WHERE sc.sectorCollectionFk = vSectorCollectionFk + AND str.workerFk = account.myUser_getId() + AND iss.id IS NULL; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSales; + l: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE l; + END IF; + + CALL itemShelvingSale_addBySale(vSaleFk); + END LOOP; + CLOSE vSales; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_doReserve.sql b/db/routines/vn/procedures/itemShelvingSale_doReserve.sql new file mode 100644 index 000000000..629e303b3 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_doReserve.sql @@ -0,0 +1,52 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_doReserve`() +proc: BEGIN +/** + * Genera reservas de la tabla vn.itemShelvingSaleReserve + */ + DECLARE vDone BOOL; + DECLARE vSaleFk INT; + + DECLARE vSales CURSOR FOR + SELECT DISTINCT saleFk FROM tSale; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); + ROLLBACK; + RESIGNAL; + END; + + IF !GET_LOCK('vn.itemShelvingSale_doReserve', 0) THEN + LEAVE proc; + END IF; + + CREATE OR REPLACE TEMPORARY TABLE tSale + ENGINE = MEMORY + SELECT id, saleFk FROM itemShelvingSaleReserve; + + OPEN vSales; + + myLoop: LOOP + SET vDone = FALSE; + FETCH vSales INTO vSaleFk; + + IF vDone THEN + LEAVE myLoop; + END IF; + + CALL itemShelvingSale_addBySale (vSaleFk); + END LOOP; + + CLOSE vSales; + + DELETE iss FROM itemShelvingSaleReserve iss JOIN tSale s ON s.id = iss.id; + + DROP TEMPORARY TABLE tSale; + + DO RELEASE_LOCK('vn.itemShelvingSale_doReserve'); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_reallocate.sql b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql new file mode 100644 index 000000000..85230a386 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_reallocate.sql @@ -0,0 +1,49 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reallocate`( + vItemShelvingFk INT(10), + vItemFk INT(10) +) +BEGIN +/** + * Elimina reservas de un itemShelving e intenta reservar en otra ubicación + * + * @param vItemShelvingFk Id itemShelving + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = 0, + available = 0 + WHERE id = vItemShelvingFk + AND itemFk = vItemFk; + + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT DISTINCT iss.saleFk + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + + DELETE iss + FROM itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + WHERE iss.itemShelvingFk = vItemShelvingFk + AND ish.itemFk = vItemFk + AND NOT iss.isPicked; + COMMIT; + + CALL itemShelvingSale_doReserve(); +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_reserve.sql b/db/routines/vn/procedures/itemShelvingSale_reserve.sql deleted file mode 100644 index afe65bd78..000000000 --- a/db/routines/vn/procedures/itemShelvingSale_reserve.sql +++ /dev/null @@ -1,92 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_reserve`() -BEGIN -/** - * Reserva cantidades con ubicaciones para un conjunto de sales del mismo - * almacen. - * - * @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 ; diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql b/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql deleted file mode 100644 index 9a97130dd..000000000 --- a/db/routines/vn/procedures/itemShelvingSale_reserveByCollection.sql +++ /dev/null @@ -1,29 +0,0 @@ -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 ; diff --git a/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql b/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql deleted file mode 100644 index fb245062e..000000000 --- a/db/routines/vn/procedures/itemShelvingSale_reserveBySale.sql +++ /dev/null @@ -1,21 +0,0 @@ -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 ; diff --git a/db/routines/vn/procedures/itemShelvingSale_setPicked.sql b/db/routines/vn/procedures/itemShelvingSale_setPicked.sql new file mode 100644 index 000000000..c1e58a9d1 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_setPicked.sql @@ -0,0 +1,34 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_setPicked`( + vSaleGroupFk INT(10) +) +BEGIN +/** + * Gestiona la reserva de un vn.saleGroup actualizando vn.itemShelvingSale.isPicked + * y cambiando el estado de la vn.sale + * + * @param vSaleGroupFk Id saleGroupFk + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF NOT (SELECT COUNT(*) FROM saleGroup WHERE id = vSaleGroupFk) THEN + CALL util.throw('Sale group not exists'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + JOIN saleGroupDetail sg ON sg.saleFk = s.id + SET iss.isPicked = TRUE + WHERE sg.saleGroupFk = vSaleGroupFk; + + CALL saleTracking_addPreparedSaleGroup(vSaleGroupFk); + + COMMIT; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql index b792534fb..85f56ee68 100644 --- a/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql +++ b/db/routines/vn/procedures/itemShelvingSale_setQuantity.sql @@ -1,118 +1,104 @@ -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_setQuantity`( + vItemShelvingSaleFk INT(10), + vQuantity DECIMAL(10,0), + vIsItemShelvingSaleEmpty BOOLEAN +) +BEGIN +/** + * Gestiona la reserva de un itemShelvingFk, actualizando isPicked y quantity + * en itemShelvingSale y 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 la ubicación itemShelvingSale se ha + * quedado vacio tras el movimiento + */ + DECLARE vSaleFk INT; + DECLARE vItemShelvingFk INT; + DECLARE vReservedQuantity INT; + DECLARE vRemainingQuantity INT; + DECLARE vItemFk INT; + DECLARE vTotalQuantity INT; + DECLARE vStateCode VARCHAR(45); + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT isPicked FROM itemShelvingSale WHERE id = vItemShelvingSaleFk) THEN + CALL util.throw('Reservation completed'); + END IF; + + SELECT s.itemFk, + iss.saleFk, + iss.itemShelvingFk, + SUM(IFNULL(iss.quantity,0)), + IF(sgd.id, 'PREVIOUS_PREPARATION', 'PREPARED') + INTO vItemFk, + vSaleFk, + vItemShelvingFk, + vReservedQuantity, + vStateCode + FROM itemShelvingSale iss + JOIN sale s ON s.id = iss.saleFk + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = iss.saleFk + WHERE iss.id = vItemShelvingSaleFk + AND NOT iss.isPicked; + + IF vQuantity > vReservedQuantity + OR (vQuantity < vReservedQuantity AND + (NOT vIsItemShelvingSaleEmpty OR vIsItemShelvingSaleEmpty IS NULL)) + OR (vIsItemShelvingSaleEmpty IS NOT NULL AND vQuantity = vReservedQuantity) THEN + CALL util.throw('The quantity cannot be different from the reserved'); + END IF; + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = TRUE, + quantity = vQuantity + WHERE id = vItemShelvingSaleFk; + + SELECT id INTO vItemShelvingFk + FROM itemShelving + WHERE id = vItemShelvingFk + FOR UPDATE; + + UPDATE itemShelving + SET visible = GREATEST(0, visible - vQuantity) + WHERE id = vItemShelvingFk; + + SELECT SUM(IF(isPicked, 0, quantity)), SUM(quantity) + INTO vRemainingQuantity, vTotalQuantity + FROM itemShelvingSale + WHERE saleFk = vSaleFk; + + IF vRemainingQuantity = 0 AND NOT vIsItemShelvingSaleEmpty THEN + CALL saleTracking_new( + vSaleFk, + TRUE, + vTotalQuantity, + `account`.`myUser_getId`(), + NULL, + vStateCode, + TRUE); + + UPDATE sale s + SET s.quantity = vTotalQuantity, + isPicked = TRUE + WHERE s.id = vSaleFk; + END IF; + + COMMIT; + + IF vIsItemShelvingSaleEmpty AND vQuantity <> vReservedQuantity THEN + INSERT INTO itemShelvingSaleReserve (saleFk) + SELECT vSaleFk; + CALL itemShelvingSale_reallocate(vItemShelvingFk, vItemFk); + END IF; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelvingSale_unpicked.sql b/db/routines/vn/procedures/itemShelvingSale_unpicked.sql new file mode 100644 index 000000000..889cadfd0 --- /dev/null +++ b/db/routines/vn/procedures/itemShelvingSale_unpicked.sql @@ -0,0 +1,60 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingSale_unpicked`( + vSelf INT(11) +) +BEGIN +/** + * Desmarca una línea que ya estaba sacada, devolviendo la cantidad al itemShelving + * + * @param vSelf Identificador del itemShelvingSale + */ + DECLARE vSaleFk INT; + DECLARE vReservedQuantity INT; + DECLARE vIsSaleGroup BOOL; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + IF (SELECT NOT isPicked FROM itemShelvingSale WHERE id = vSelf) THEN + CALL util.throw('Reserva no completada'); + END IF; + + SELECT ish.saleFk, ish.quantity, IF(sg.id, TRUE, FALSE) + INTO vSaleFk, vReservedQuantity, vIsSaleGroup + FROM itemShelvingSale ish + LEFT JOIN saleGroupDetail sg ON sg.saleFk = ish.saleFk + WHERE ish.id = vSelf; + + /*IF vIsSaleGroup THEN + CALL util.throw('Can not unpicked a sale group'); + END IF;*/ + + START TRANSACTION; + + UPDATE itemShelvingSale + SET isPicked = FALSE + WHERE id = vSelf; + + UPDATE sale s + JOIN itemShelvingSale ish ON ish.saleFk = s.id + SET s.isPicked = FALSE + WHERE ish.id = vSelf; + + UPDATE itemShelvingSale iss + JOIN itemShelving ish ON ish.id = iss.itemShelvingFk + SET ish.visible = ish.visible + iss.quantity + WHERE iss.id = vSelf; + + CALL saleTracking_new( + vSaleFk, + FALSE, + vReservedQuantity, + `account`.`myUser_getId`(), + NULL, + 'ON_PREPARATION', + TRUE); + COMMIT; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelving_add.sql b/db/routines/vn/procedures/itemShelving_add.sql index c308304ef..a1bca5b6c 100644 --- a/db/routines/vn/procedures/itemShelving_add.sql +++ b/db/routines/vn/procedures/itemShelving_add.sql @@ -70,4 +70,4 @@ BEGIN WHERE id = vBuyFk; END IF; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/itemShelving_filterBuyer.sql b/db/routines/vn/procedures/itemShelving_filterBuyer.sql index 7112aa48e..d4675ea0e 100644 --- a/db/routines/vn/procedures/itemShelving_filterBuyer.sql +++ b/db/routines/vn/procedures/itemShelving_filterBuyer.sql @@ -21,7 +21,8 @@ proc:BEGIN sub.downstairs, sub.visible, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) nicho, - sub.name itemColour + sub.name itemColour, + CAST(sub2.pendiente AS DECIMAL(10,0)) pendingAmount FROM (SELECT iss.itemFk, CONCAT(i.longName, ' ', IFNULL(i.size, ''),' ', IFNULL(i.subName, '') ) longName, '' size, @@ -58,7 +59,8 @@ proc:BEGIN 0, v.visible, v.visible nicho, - ik.name itemColour + ik.name itemColour, + CAST(sub5.pendiente AS DECIMAL(10,0)) pendingAmount FROM cache.visible v JOIN item i ON i.id = v.item_id LEFT JOIN ink ik ON ik.id = i.inkFk diff --git a/db/routines/vn/procedures/itemShelving_inventory.sql b/db/routines/vn/procedures/itemShelving_inventory.sql index 73e438fbb..f4b8ae165 100644 --- a/db/routines/vn/procedures/itemShelving_inventory.sql +++ b/db/routines/vn/procedures/itemShelving_inventory.sql @@ -59,5 +59,7 @@ BEGIN WHERE p.pickingOrder BETWEEN vPickingOrderFrom AND vPickingOrderTo AND p.sectorFk = vSectorFk ORDER BY p.pickingOrder; + + DROP TEMPORARY TABLE tmp.stockMisfit; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/itemShelvingTransfer.sql b/db/routines/vn/procedures/itemShelving_transfer.sql similarity index 85% rename from db/routines/vn/procedures/itemShelvingTransfer.sql rename to db/routines/vn/procedures/itemShelving_transfer.sql index ae82bfe9d..47a9a7cf0 100644 --- a/db/routines/vn/procedures/itemShelvingTransfer.sql +++ b/db/routines/vn/procedures/itemShelving_transfer.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelvingTransfer`(vItemShelvingFk INT, vShelvingFk VARCHAR(3)) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`itemShelving_transfer`( + vItemShelvingFk INT, + vShelvingFk VARCHAR(10) +) BEGIN /** * Transfiere producto de una ubicación a otra, fusionando si coincide el @@ -21,8 +24,7 @@ BEGIN buyFk FROM itemShelving WHERE id = vItemShelvingFk - ) ish2 - ON ish2.itemFk = ish.itemFk + ) ish2 ON ish2.itemFk = ish.itemFk AND ish2.packing = ish.packing AND date(ish2.created) = date(ish.created) AND ish2.buyFk = ish.buyFk @@ -30,7 +32,7 @@ BEGIN IF vNewItemShelvingFk THEN UPDATE itemShelving ish - JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk + JOIN itemShelving ish2 ON ish2.id = vItemShelvingFk SET ish.visible = ish.visible + ish2.visible WHERE ish.id = vNewItemShelvingFk; @@ -41,7 +43,6 @@ BEGIN SET shelvingFk = vShelvingFk WHERE id = vItemShelvingFk; END IF; - SELECT true; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/item_GetVisible.sql b/db/routines/vn/procedures/item_GetVisible.sql deleted file mode 100644 index ca5e43107..000000000 --- a/db/routines/vn/procedures/item_GetVisible.sql +++ /dev/null @@ -1,43 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_GetVisible`(vWarehouse SMALLINT, vItem INT) -BEGIN - DECLARE vTomorrow DATETIME DEFAULT TIMESTAMPADD(DAY, 1, util.VN_CURDATE()); - - INSERT INTO tmp.itemVisible (item_id, visible) - SELECT item_id, SUM(amount) amount - FROM ( - SELECT i.itemFk AS item_id, quantity AS amount - FROM itemTicketOut i - LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk - JOIN state s ON s.id = ts.stateFk - LEFT JOIN (SELECT DISTINCT saleFk - FROM saleTracking st - JOIN state s ON s.id = st.stateFk - WHERE st.created > util.VN_CURDATE() - AND (s.isPicked OR st.isChecked) - ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk - WHERE i.warehouseFk = vWarehouse - AND (vItem IS NULL OR i.itemFk = vItem) - AND (s.isPicked OR i.reserved OR stPrevious.saleFk ) - AND i.shipped >= util.VN_CURDATE() AND i.shipped < vTomorrow - UNION ALL - SELECT iei.itemFk, quantity - FROM itemEntryIn iei - WHERE (iei.isReceived != FALSE /*OR ip.modificationDate > util.VN_CURDATE()*/) - AND iei.landed >= util.VN_CURDATE() AND iei.landed < vTomorrow - AND iei.warehouseInFk = vWarehouse - AND (vItem IS NULL OR iei.itemFk = vItem) - AND iei.isVirtualStock is FALSE - UNION ALL - SELECT itemFk, quantity - FROM itemEntryOut - WHERE isDelivered != FALSE - AND shipped >= util.VN_CURDATE() AND shipped < vTomorrow - AND warehouseOutFk = vWarehouse - AND (vItem IS NULL OR itemFk = vItem) - ) t - GROUP BY item_id - ON DUPLICATE KEY UPDATE - visible = IFNULL(stock,0) + VALUES(visible); -END$$ -DELIMITER ; diff --git a/db/routines/vn/procedures/item_calcVisible.sql b/db/routines/vn/procedures/item_calcVisible.sql new file mode 100644 index 000000000..820e73a7e --- /dev/null +++ b/db/routines/vn/procedures/item_calcVisible.sql @@ -0,0 +1,56 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_calcVisible`( + vSelf INT, + vWarehouseFk INT +) +BEGIN +/** + * Calcula el visible de un artículo o de todos. + * + * @param vWarehouse Warehouse id + * @param vSelf Item id + * @param tmp.itemVisible(item_id, stock, visible) + */ + DECLARE vDated DATE DEFAULT util.VN_CURDATE(); + DECLARE vTomorrow DATETIME DEFAULT util.tomorrow(); + + INSERT INTO tmp.itemVisible(item_id, visible) + SELECT itemFk, SUM(quantity) + FROM ( + SELECT i.itemFk, i.quantity + FROM itemTicketOut i + LEFT JOIN ticketState ts ON ts.ticketFk = i.ticketFk + JOIN `state` s ON s.id = ts.stateFk + LEFT JOIN ( + SELECT DISTINCT st.saleFk + FROM saleTracking st + JOIN state s ON s.id = st.stateFk + WHERE st.created > vDated + AND (s.isPicked OR st.isChecked) + ) stPrevious ON `stPrevious`.`saleFk` = i.saleFk + WHERE IFNULL(vWarehouseFk, i.warehouseFk) = i.warehouseFk + AND (vSelf IS NULL OR i.itemFk = vSelf) + AND (s.isPicked OR i.reserved OR stPrevious.saleFk) + AND i.shipped >= vDated AND i.shipped < vTomorrow + UNION ALL + SELECT itemFk, quantity + FROM itemEntryIn + WHERE isReceived + AND landed >= vDated AND landed < vTomorrow + AND IFNULL(vWarehouseFk, warehouseInFk) = warehouseInFk + AND (vSelf IS NULL OR itemFk = vSelf) + AND NOT isVirtualStock + UNION ALL + SELECT itemFk, quantity + FROM itemEntryOut + WHERE isDelivered + AND shipped >= vDated + AND shipped < vTomorrow + AND IFNULL(vWarehouseFk, warehouseOutFk) = warehouseOutFk + AND (vSelf IS NULL OR itemFk = vSelf) + ) t + GROUP BY itemFk + ON DUPLICATE KEY UPDATE + visible = IFNULL(stock, 0) + VALUES(visible); +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/item_comparative.sql b/db/routines/vn/procedures/item_comparative.sql index d429cf009..2625a87a5 100644 --- a/db/routines/vn/procedures/item_comparative.sql +++ b/db/routines/vn/procedures/item_comparative.sql @@ -10,19 +10,20 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_comparative`( ) proc: BEGIN /** - * Genera una tabla de comparativa de artículos por itemType/comprador/fecha. - * Los datos se calculan en función de los parámetros proporcionados. + * Generates a comparison table of items by itemType/buyer/date. + * The data is calculated based on the provided parameters. * - * @param vDate La fecha para la cual se generará la comparativa. - * @param vDayRange El rango de días a considerar para la comparativa. - * @param vWarehouseFk El identificador del almacén para filtrar los artículos. - * @param vAvailableSince La fecha de disponibilidad desde la cual se consideran los artículos disponibles. - * @param vBuyerFk El identificador del comprador para filtrar los artículos. - * @param vIsFloramondo Indica si se deben incluir solo los artículos de Floramondo (opcional). - * @param vCountryFk El identificador del país. - * @param tmp.comparativeFilterType(filterFk INT ,itemTypeFk INT) + * @param vDate The date for which the comparison will be generated. + * @param vDayRange The range of days to consider for the comparison. + * @param vWarehouseFk The warehouse identifier to filter the items. + * @param vAvailableSince The availability date from which the items are considered available. + * @param vBuyerFk The buyer identifier to filter the items. + * @param vIsFloramondo Indicates whether only Floramondo items should be included (optional). + * @param vCountryFk The country identifier. + * @param tmp.comparativeFilterType(filterFk INT, itemTypeFk INT) * @return tmp.comparative */ + DECLARE vDayRangeStart DATE; DECLARE vDayRangeEnd DATE; DECLARE w1, w2, w3, w4, w5, w6, w7 INT; diff --git a/db/routines/vn/procedures/item_devalueA2.sql b/db/routines/vn/procedures/item_devalueA2.sql index c9f716d8f..5b03fc872 100644 --- a/db/routines/vn/procedures/item_devalueA2.sql +++ b/db/routines/vn/procedures/item_devalueA2.sql @@ -42,7 +42,7 @@ BEGIN END IF; SELECT warehouseFk INTO vWarehouseFk - FROM userConfig + FROM userMultiConfig WHERE userFk = account.myUser_getId(); IF NOT vWarehouseFk OR vWarehouseFk IS NULL THEN diff --git a/db/routines/vn/procedures/item_getBalance.sql b/db/routines/vn/procedures/item_getBalance.sql index a4942af6f..0de59b478 100644 --- a/db/routines/vn/procedures/item_getBalance.sql +++ b/db/routines/vn/procedures/item_getBalance.sql @@ -2,94 +2,84 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_getBalance`( vItemFk INT, vWarehouseFk INT, - vDate DATETIME + vDated DATETIME ) BEGIN /** - * @vItemFk item a buscar - * @vWarehouseFk almacen donde buscar - * @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 de vDate. + * Calcula el balance de un artículo. + * + * @vItemFk Id de artículo + * @vWarehouseFk Id de almacén + * @vDated Fecha a calcular, si es NULL muestra el histórico desde el inventario */ - DECLARE vDateInventory DATETIME; + DECLARE vDateInventory DATETIME + DEFAULT ( + SELECT IF(vDated, uc.mockUtcTime, c.inventoried) + FROM config c + JOIN util.config uc + ); + DECLARE vSupplierInventoryFk INT + DEFAULT (SELECT supplierFk FROM inventoryConfig); - IF vDate IS NULL THEN - SELECT inventoried INTO vDateInventory - FROM config; - ELSE - SELECT mockUtcTime INTO vDateInventory - FROM util.config; + IF NOT vSupplierInventoryFk OR NOT vDateInventory THEN + CALL util.throw('Config variables are not set'); END IF; - CREATE OR REPLACE TEMPORARY TABLE tItemDiary( - shipped DATE, - `in` INT(11), - `out` INT(11), - alertLevel INT(11), - stateName VARCHAR(20), - `name` VARCHAR(50), - reference VARCHAR(50), - origin INT(11), - clientFk INT(11), - isPicked INT(11), - isTicket TINYINT(1), - lineFk INT(11), - `order` TINYINT(3) UNSIGNED, - clientType VARCHAR(20), - claimFk INT(10) UNSIGNED, - inventorySupplierFk INT(10) - ); - - INSERT INTO tItemDiary + CREATE OR REPLACE TEMPORARY TABLE tItemDiary + ENGINE = MEMORY WITH entriesIn AS ( - SELECT tr.landed shipped, + SELECT 'entry' originType, + e.id originId, + tr.landed shipped, b.quantity `in`, NULL `out`, st.alertLevel , st.name stateName, - s.name `name`, e.invoiceNumber reference, - e.id origin, - s.id clientFk, + 'supplier' entityType, + s.id entityId, + s.name entityName, IF(st.`code` = 'DELIVERED', TRUE, FALSE) isPicked, FALSE isTicket, b.id lineFk, NULL `order`, NULL clientType, NULL claimFk, - ec.inventorySupplierFk + vSupplierInventoryFk inventorySupplierFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.supplier s ON s.id = e.supplierFk - JOIN vn.state st ON st.`code` = IF( tr.landed < util.VN_CURDATE() + JOIN vn.state st ON st.`code` = IF(tr.landed < util.VN_CURDATE() OR (util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') - JOIN vn.entryConfig ec WHERE tr.landed >= vDateInventory - AND vWarehouseFk = tr.warehouseInFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND tr.warehouseInFk = vWarehouseFk + AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT e.isRaid - ), entriesOut AS ( - SELECT tr.shipped, + ), + entriesOut AS ( + SELECT 'entry', + e.id originType, + tr.shipped, NULL, b.quantity, st.alertLevel, st.name stateName, - s.name , e.invoiceNumber, - e.id entryFk, - s.id supplierFk, + 'supplier' entityType, + s.id entityId, + s.name, IF(st.`code` = 'DELIVERED' , TRUE, FALSE), FALSE isTicket, b.id, NULL `order`, NULL clientType, NULL claimFk, - ec.inventorySupplierFk + vSupplierInventoryFk FROM vn.buy b JOIN vn.entry e ON e.id = b.entryFk JOIN vn.travel tr ON tr.id = e.travelFk @@ -99,86 +89,108 @@ BEGIN OR (tr.shipped = util.VN_CURDATE() AND tr.isReceived), 'DELIVERED', 'FREE') - JOIN vn.entryConfig ec WHERE tr.shipped >= vDateInventory - AND vWarehouseFk = tr.warehouseOutFk - AND (s.id <> ec.inventorySupplierFk OR vDate IS NULL) + AND tr.warehouseOutFk = vWarehouseFk + AND (s.id <> vSupplierInventoryFk OR vDated IS NULL) AND b.itemFk = vItemFk AND NOT e.isExcludedFromAvailable AND NOT w.isFeedStock AND NOT e.isRaid - ), sales AS ( - SELECT DATE(t.shipped) shipped, - s.quantity, - st2.alertLevel, - st2.name, - t.nickname, - t.refFk, - t.id ticketFk, - t.clientFk, - s.id saleFk, - st.`order`, - c.typeFk, - cb.claimFk - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id - LEFT JOIN vn.state st ON st.`code` = ts.`code` - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), - 'DELIVERED', - IF (t.shipped > util.dayEnd(util.VN_CURDATE()), - 'FREE', - IFNULL(ts.code, 'FREE'))) - LEFT JOIN vn.claimBeginning cb ON s.id = cb.saleFk - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemFk - AND vWarehouseFk = t.warehouseFk - ),sale AS ( - SELECT s.shipped, + ), + sales AS ( + WITH itemSales AS ( + SELECT DATE(t.shipped) shipped, + s.quantity, + st2.alertLevel, + st2.name, + t.refFk, + t.id ticketFk, + 'client' entityType, + t.clientFk entityId, + t.nickname, + s.id saleFk, + st.`order`, + c.typeFk, + cb.claimFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + LEFT JOIN vn.ticketState ts ON ts.ticketFk = t.id + LEFT JOIN vn.state st ON st.code = ts.code + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.state st2 ON st2.`code` = IF(t.shipped < util.VN_CURDATE(), + 'DELIVERED', + IF (t.shipped > util.dayEnd(util.VN_CURDATE()), + 'FREE', + IFNULL(st.code, 'FREE'))) + LEFT JOIN vn.claimBeginning cb ON cb.saleFk = s.id + WHERE t.shipped >= vDateInventory + AND s.itemFk = vItemFk + AND t.warehouseFk = vWarehouseFk + ) + SELECT 'ticket', + s.ticketFk, + s.shipped, NULL `in`, s.quantity, s.alertLevel, s.name, - s.nickname, s.refFk, - s.ticketFk, - s.clientFk, - IF(stk.saleFk, TRUE, NULL), + s.entityType, + s.entityId, + s.nickname, + IF(stk.saleFk, TRUE, FALSE), TRUE, s.saleFk, s.`order`, s.typeFk, s.claimFk, NULL - FROM sales s + FROM itemSales s LEFT JOIN vn.state stPrep ON stPrep.`code` = 'PREPARED' LEFT JOIN vn.saleTracking stk ON stk.saleFk = s.saleFk AND stk.stateFk = stPrep.id GROUP BY s.saleFk - ) SELECT shipped, - `in`, - `out`, - alertLevel, - stateName, - `name`, - reference, - origin, - clientFk, - isPicked, - isTicket, - lineFk, - `order`, - clientType, - claimFk, - inventorySupplierFk - FROM entriesIn + ), + orders AS ( + SELECT 'order' originType, + o.id originId, + r.shipment, + NULL 'in', + r.amount, + NULL alertLevel, + NULL stateName, + NULL invoiceNumber, + 'client' entityType, + c.id, + c.name, + FALSE, + FALSE isTicket, + NULL buyFk, + NULL 'order', + c.typeFk, + NULL claimFk, + NULL + FROM hedera.orderRow r + JOIN hedera.`order` o ON o.id = r.orderFk + JOIN vn.client c ON c.id = o.customer_id + WHERE r.shipment >= vDateInventory + AND r.warehouseFk = vWarehouseFk + AND r.created >= ( + SELECT SUBTIME(util.VN_NOW(), reserveTime) + FROM hedera.orderConfig + ) + AND NOT o.confirmed + AND r.itemFk = vItemFk + ) + SELECT * FROM entriesIn UNION ALL SELECT * FROM entriesOut UNION ALL - SELECT * FROM sale + SELECT * FROM sales + UNION ALL + SELECT * FROM orders ORDER BY shipped, - (inventorySupplierFk = clientFk) DESC, + (inventorySupplierFk = entityId) DESC, alertLevel DESC, isTicket, `order` DESC, @@ -186,19 +198,20 @@ BEGIN `in` DESC, `out` DESC; - IF vDate IS NULL THEN - + IF vDated IS NULL THEN SET @a := 0; SET @currentLineFk := 0; SET @shipped := ''; - SELECT DATE(@shipped:= t.shipped) shipped, + SELECT t.originType, + t.originId, + DATE(@shipped:= t.shipped) shipped, t.alertLevel, t.stateName, - t.origin, t.reference, - t.clientFk, - t.name, + t.entityType, + t.entityId, + t.entityName, t.`in` invalue, t.`out`, @a := @a + IFNULL(t.`in`, 0) - IFNULL(t.`out`, 0) balance, @@ -214,37 +227,41 @@ BEGIN t.`order` FROM tItemDiary t LEFT JOIN alertLevel a ON a.id = t.alertLevel; - ELSE SELECT IFNULL(SUM(IFNULL(`in`, 0)) - SUM(IFNULL(`out`, 0)), 0) INTO @a FROM tItemDiary - WHERE shipped < vDate; + WHERE shipped < vDated; - SELECT vDate shipped, - 0 alertLevel, - 0 stateName, - 0 origin, - '' reference, - 0 clientFk, + SELECT NULL originType, + NULL originId, + vDated shipped, + NULL alertLevel, + NULL stateName, + NULL reference, + NULL entityType, + NULL entityId, 'Inventario calculado', @a invalue, NULL `out`, @a balance, - 0 lastPreparedLineFk, - 0 isTicket, - 0 lineFk, - 0 isPicked, - 0 clientType, - 0 claimFk, + NULL lastPreparedLineFk, + NULL isTicket, + NULL lineFk, + NULL isPicked, + NULL clientType, + NULL claimFk, NULL `order` UNION ALL - SELECT shipped, + SELECT originType, + originId, + shipped, alertlevel, stateName, - origin, - reference, - clientFk, - name, `in`, + reference, + entityType, + entityId, + entityName, + `in`, `out`, @a := @a + IFNULL(`in`, 0) - IFNULL(`out`, 0), 0, @@ -255,7 +272,7 @@ BEGIN claimFk, `order` FROM tItemDiary - WHERE shipped >= vDate; + WHERE shipped >= vDated; END IF; DROP TEMPORARY TABLE tItemDiary; diff --git a/db/routines/vn/procedures/item_getMinacum.sql b/db/routines/vn/procedures/item_getMinacum.sql index 7573759f7..a3ebedb12 100644 --- a/db/routines/vn/procedures/item_getMinacum.sql +++ b/db/routines/vn/procedures/item_getMinacum.sql @@ -76,5 +76,7 @@ BEGIN i.quantity amount FROM tmp.itemAtp i HAVING amount != 0; + + DROP TEMPORARY TABLE tmp.itemAtp; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/item_getSimilar.sql b/db/routines/vn/procedures/item_getSimilar.sql index 762c25342..72c543b40 100644 --- a/db/routines/vn/procedures/item_getSimilar.sql +++ b/db/routines/vn/procedures/item_getSimilar.sql @@ -15,14 +15,13 @@ BEGIN * @param vDated Fecha * @param vShowType Mostrar tipos */ - DECLARE vCalcFk INT; + DECLARE vAvailableCalcFk INT; + DECLARE vVisibleCalcFk INT; DECLARE vTypeFk INT; DECLARE vPriority INT DEFAULT 1; - CALL cache.available_refresh(vCalcFk, FALSE, vWarehouseFk, vDated); - - -- Añadido temporalmente para que no se cuelgue la db - SET vShowType = TRUE; + CALL cache.available_refresh(vAvailableCalcFk, FALSE, vWarehouseFk, vDated); + CALL cache.visible_refresh(vVisibleCalcFk, FALSE, vWarehouseFk); WITH itemTags AS ( SELECT i.id, @@ -64,22 +63,22 @@ BEGIN WHEN b.groupingMode = 'grouping' THEN b.grouping WHEN b.groupingMode = 'packing' THEN b.packing ELSE 1 - END AS minQuantity, - iss.visible located, + END minQuantity, + v.visible located, b.price2 FROM vn.item i JOIN cache.available a ON a.item_id = i.id - AND a.calc_id = vCalcFk + AND a.calc_id = vAvailableCalcFk + LEFT JOIN cache.visible v ON v.item_id = i.id + AND v.calc_id = vVisibleCalcFk + LEFT JOIN cache.last_buy lb ON lb.item_id = i.id + AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.itemProposal ip ON ip.mateFk = i.id AND ip.itemFk = vSelf LEFT JOIN vn.itemTag it ON it.itemFk = i.id AND it.priority = vPriority LEFT JOIN vn.tag t ON t.id = it.tagFk - LEFT JOIN cache.last_buy lb ON lb.item_id = i.id - AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = lb.buy_id - LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = i.id - AND iss.warehouseFk = vWarehouseFk JOIN itemTags its WHERE a.available > 0 AND (i.typeFk = its.typeFk OR NOT vShowType) diff --git a/db/routines/vn/procedures/item_refreshFromTags.sql b/db/routines/vn/procedures/item_refreshFromTags.sql index 398c01d8e..35f7c74e7 100644 --- a/db/routines/vn/procedures/item_refreshFromTags.sql +++ b/db/routines/vn/procedures/item_refreshFromTags.sql @@ -46,12 +46,18 @@ BEGIN i.tag8 = JSON_VALUE(vTags, '$.8'), i.tag9 = JSON_VALUE(vTags, '$.9'), i.tag10 = JSON_VALUE(vTags, '$.10'), + i.tag11 = JSON_VALUE(vTags, '$.11'), + i.tag12 = JSON_VALUE(vTags, '$.12'), + i.tag13 = JSON_VALUE(vTags, '$.13'), i.value5 = JSON_VALUE(vValues, '$.5'), i.value6 = JSON_VALUE(vValues, '$.6'), i.value7 = JSON_VALUE(vValues, '$.7'), i.value8 = JSON_VALUE(vValues, '$.8'), i.value9 = JSON_VALUE(vValues, '$.9'), i.value10 = JSON_VALUE(vValues, '$.10'), + i.value11 = JSON_VALUE(vValues, '$.11'), + i.value12 = JSON_VALUE(vValues, '$.12'), + i.value13 = JSON_VALUE(vValues, '$.13'), i.producerFk = p.id, i.inkFk = k.id, i.originFk = IFNULL(o.id, i.originFk) diff --git a/db/routines/vn/procedures/item_setVisibleDiscard.sql b/db/routines/vn/procedures/item_setVisibleDiscard.sql index 0a6c54971..a44d87333 100644 --- a/db/routines/vn/procedures/item_setVisibleDiscard.sql +++ b/db/routines/vn/procedures/item_setVisibleDiscard.sql @@ -6,7 +6,8 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`item_setVisibleDisc 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 + * Procedimiento para dar dar de baja/alta un item, si vAdressFk 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 diff --git a/db/routines/vn/procedures/multipleInventory.sql b/db/routines/vn/procedures/multipleInventory.sql index 2a28aa9a0..6cd584c6e 100644 --- a/db/routines/vn/procedures/multipleInventory.sql +++ b/db/routines/vn/procedures/multipleInventory.sql @@ -1,15 +1,16 @@ -DELIMITER $$ +DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`multipleInventory`( vDate DATE, vWarehouseFk TINYINT, vMaxDays TINYINT -) +) proc: BEGIN DECLARE vDateTomorrow DATE DEFAULT vDate + INTERVAL 1 DAY; DECLARE vDateFrom DATE DEFAULT vDate; DECLARE vDateTo DATETIME; DECLARE vDateToTomorrow DATETIME; DECLARE vDefaultDayRange INT; + DECLARE vCalcFk INT; IF vDate < util.VN_CURDATE() THEN LEAVE proc; @@ -36,9 +37,11 @@ proc: BEGIN ADD `life` TINYINT NOT NULL DEFAULT '0'; -- Calculo del inventario - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal + CREATE OR REPLACE TEMPORARY TABLE tItemInventoryCalc + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT itemFk, + SUM(quantity) quantity FROM ( SELECT s.itemFk, - s.quantity quantity FROM sale s @@ -69,56 +72,29 @@ proc: BEGIN AND w.isComparative AND NOT e.isExcludedFromAvailable AND NOT e.isRaid - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.inventory = sub.Subtotal, - ai.visible = sub.Subtotal, - ai.avalaible = sub.Subtotal, - ai.sd = sub.Subtotal; + ) sub + GROUP BY itemFk; + + UPDATE tmp.itemInventory ai + JOIN tItemInventoryCalc iic ON iic.itemFk = ai.id + SET ai.inventory = iic.quantity, + ai.visible = iic.quantity, + ai.avalaible = iic.quantity, + ai.sd = iic.quantity; -- Cálculo del visible - UPDATE tmp.itemInventory ai - JOIN ( - SELECT itemFk Id_Article, SUM(quantity) Subtotal - FROM ( - SELECT s.itemFk, s.quantity - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.shipped >= vDate - AND t.shipped < vDateTomorrow - AND (NOT isPicked AND NOT t.isLabeled AND t.refFk IS NULL) - AND IFNULL(vWarehouseFk, t.warehouseFk) = t.warehouseFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, - b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseInFk - WHERE t.landed = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseInFk) = t.warehouseInFk - AND w.isComparative - UNION ALL - SELECT b.itemFk, b.quantity - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel t ON t.id = e.travelFk - JOIN warehouse w ON w.id = t.warehouseOutFk - WHERE t.shipped = vDate - AND NOT t.isReceived - AND NOT e.isExcludedFromAvailable - AND NOT e.isRaid - AND IFNULL(vWarehouseFk, t.warehouseOutFk) = t.warehouseOutFk - AND w.isComparative - ) sub2 - GROUP BY itemFk - ) sub ON ai.id = sub.Id_Article - SET ai.visible = ai.visible + sub.Subtotal; + CALL cache.visible_refresh(vCalcFk, FALSE, vWarehouseFk); + + CREATE OR REPLACE TEMPORARY TABLE tItemVisibleCalc + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT item_id, visible + FROM cache.visible + WHERE calc_id = vCalcFk; + + UPDATE tmp.itemInventory it + JOIN tItemVisibleCalc ivc ON ivc.item_id = it.id + SET it.visible = it.visible + ivc.visible; -- Calculo del disponible CREATE OR REPLACE TEMPORARY TABLE tmp.itemCalc @@ -189,6 +165,8 @@ proc: BEGIN DROP TEMPORARY TABLE tmp.itemTravel, tmp.itemCalc, - tmp.itemAtp; -END$$ -DELIMITER ; + tmp.itemAtp, + tItemInventoryCalc, + tItemVisibleCalc; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/productionControl.sql b/db/routines/vn/procedures/productionControl.sql index 09c01d1ef..dad46393d 100644 --- a/db/routines/vn/procedures/productionControl.sql +++ b/db/routines/vn/procedures/productionControl.sql @@ -15,6 +15,11 @@ proc: BEGIN DECLARE vEndingDate DATETIME; DECLARE vIsTodayRelative BOOLEAN; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT util.dayEnd(util.VN_CURDATE()) + INTERVAL LEAST(vScopeDays, maxProductionScopeDays) DAY INTO vEndingDate FROM productionConfig; @@ -31,7 +36,8 @@ proc: BEGIN CALL prepareClientList(); CREATE OR REPLACE TEMPORARY TABLE tmp.sale_getProblems - (INDEX (ticketFk)) ENGINE = MEMORY + (INDEX (ticketFk)) + ENGINE = MEMORY SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped FROM tmp.productionTicket tt JOIN ticket t ON t.id = tt.ticketFk; diff --git a/db/routines/vn/procedures/productionSectorList.sql b/db/routines/vn/procedures/productionSectorList.sql index 5447f10d0..e1445ca52 100644 --- a/db/routines/vn/procedures/productionSectorList.sql +++ b/db/routines/vn/procedures/productionSectorList.sql @@ -104,5 +104,6 @@ BEGIN ) sub; DROP TEMPORARY TABLE tmp.whiteTicket; DROP TEMPORARY TABLE tmp.sectorTypeTicket; + DROP TEMPORARY TABLE tmp.productionBuffer; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/saleGroup_setParking.sql b/db/routines/vn/procedures/saleGroup_setParking.sql index 4872f74c6..551ca6386 100644 --- a/db/routines/vn/procedures/saleGroup_setParking.sql +++ b/db/routines/vn/procedures/saleGroup_setParking.sql @@ -1,17 +1,25 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`(IN `vSaleGroupFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`saleGroup_setParking`( + vSaleGroupFk VARCHAR(8), + vParkingFk INT +) +BEGIN /** - * Aparca una preparación previa en un parking + * Aparca una preparación previa en un parking. * * @param vSaleGroupFk id de la preparación previa * @param vParkingFk id del parking */ - UPDATE vn.saleGroup sg + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + + UPDATE saleGroup sg SET sg.parkingFk = vParkingFk WHERE sg.id = vSaleGroupFk - AND sg.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); + AND sg.created >= util.VN_CURDATE() - INTERVAL 1 WEEK; - CALL vn.ticket_setNextState(vn.ticket_get(vSaleGroupFk)); + CALL ticket_setNextState(ticket_get(vSaleGroupFk)); END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/sale_PriceFix.sql b/db/routines/vn/procedures/sale_PriceFix.sql index 8ffa77070..5f956cba8 100644 --- a/db/routines/vn/procedures/sale_PriceFix.sql +++ b/db/routines/vn/procedures/sale_PriceFix.sql @@ -8,7 +8,7 @@ BEGIN JOIN vn.component c ON c.id = sc.componentFk JOIN vn.componentType ct ON ct.id = c.typeFk WHERE s.ticketFk = vTicketFk - AND ct.`type` = 'otros'; + AND ct.code = 'other'; UPDATE vn.sale s JOIN ( diff --git a/db/routines/vn/procedures/sale_getBoxPickingList.sql b/db/routines/vn/procedures/sale_getBoxPickingList.sql index 7466eb9be..a95ed5b0c 100644 --- a/db/routines/vn/procedures/sale_getBoxPickingList.sql +++ b/db/routines/vn/procedures/sale_getBoxPickingList.sql @@ -19,21 +19,20 @@ BEGIN CREATE OR REPLACE TEMPORARY TABLE tmp.sale (saleFk INT PRIMARY KEY) - SELECT - s.ticketFk, - s.id saleFk, - s.itemFk, - s.concept, - s.quantity, - MAKETIME(pb.HH,pb.mm,0) etd, - pb.routeFk, - FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers, - IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing, - b.packagingFk + SELECT s.ticketFk, + s.id saleFk, + s.itemFk, + s.concept, + s.quantity, + MAKETIME(pb.HH,pb.mm,0) etd, + pb.routeFk, + FLOOR(s.quantity / IF(i.isBoxPickingMode, ish.packing, i.packingOut)) stickers, + IF(i.isBoxPickingMode, ish.packing, i.packingOut) packing, + IF(pa.isPackageReturnable, pc.defaultBigPackageFk, b.packagingFk) packagingFk FROM sale s JOIN item i ON i.id = s.itemFk JOIN itemShelving ish ON ish.itemFk = s.itemFk - LEFT JOIN ( SELECT iss.itemShelvingFk, + LEFT JOIN ( SELECT iss.itemShelvingFk, s.itemFk, SUM(iss.quantity) reserve FROM itemShelvingSale iss @@ -52,6 +51,8 @@ BEGIN LEFT JOIN ticketState ts ON ts.ticketFk = s.ticketFk LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk LEFT JOIN buy b ON b.id = lb.buy_id + LEFT JOIN packaging pa ON pa.id = b.packagingFk + JOIN packagingConfig pc WHERE IF(i.isBoxPickingMode, ish.packing, i.packingOut) <= LEAST(s.quantity, ish.visible - IFNULL(tISS.reserve,0)) AND NOT pb.problem diff --git a/db/routines/vn/procedures/sale_getProblems.sql b/db/routines/vn/procedures/sale_getProblems.sql index 9944ab0c2..ba4ff5857 100644 --- a/db/routines/vn/procedures/sale_getProblems.sql +++ b/db/routines/vn/procedures/sale_getProblems.sql @@ -278,12 +278,11 @@ BEGIN -- Redondeo: Cantidad pedida incorrecta en al grouping de la última compra CALL buyUltimate(vWarehouseFk, vDate); INSERT INTO tmp.sale_problems(ticketFk, hasRounding, saleFk) - SELECT ticketFk, problem, saleFk + SELECT ticketFk, problem ,saleFk FROM ( SELECT tl.ticketFk, - s.id saleFk , - LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,''), ' '), 250) problem, - MOD(s.quantity, b.`grouping`) hasRounding + s.id saleFk, + LEFT(GROUP_CONCAT('RE: ',i.id, ' ', IFNULL(i.longName,'') SEPARATOR ', '), 250) problem FROM tmp.ticket_list tl JOIN ticket t ON t.id = tl.ticketFk AND t.warehouseFk = vWarehouseFk @@ -291,9 +290,9 @@ BEGIN JOIN item i ON i.id = s.itemFk JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk JOIN buy b ON b.id = bu.buyFk + WHERE MOD(s.quantity, b.`grouping`) GROUP BY tl.ticketFk - HAVING hasRounding - ) sub + )sub ON DUPLICATE KEY UPDATE hasRounding = sub.problem, saleFk = sub.saleFk; END LOOP; CLOSE vCursor; diff --git a/db/routines/vn/procedures/sale_setProblem.sql b/db/routines/vn/procedures/sale_setProblem.sql index 20319cc3f..b0870089f 100644 --- a/db/routines/vn/procedures/sale_setProblem.sql +++ b/db/routines/vn/procedures/sale_setProblem.sql @@ -5,14 +5,32 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sale_setProblem`( BEGIN /** * Update column sale.problem with a problem code + * * @param vProblemCode Code to set or unset - * @table tmp.sale(saleFk, hasProblem) + * @table tmp.sale(saleFk, hasProblem, isProblemCalcNeeded) */ - UPDATE sale s - JOIN tmp.sale ts ON ts.saleFk = s.id - SET s.problem = CONCAT( - IF(ts.hasProblem, - CONCAT(s.problem, ',', vProblemCode), - REPLACE(s.problem, vProblemCode , ''))); + DECLARE vSaleFk INT; + DECLARE vHasProblem INT; + DECLARE vDone BOOL; + DECLARE vSaleList CURSOR FOR SELECT saleFk, hasProblem FROM tmp.sale; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vSaleList; + l: LOOP + SET vDone = FALSE; + FETCH vSaleList INTO vSaleFk, vHasProblem; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE sale + SET problem = CONCAT( + IF(vHasProblem, + CONCAT(problem, ',', vProblemCode), + REPLACE(problem, vProblemCode , ''))) + WHERE id = vSaleFk; + END LOOP; + CLOSE vSaleList; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/sale_setProblemComponentLack.sql b/db/routines/vn/procedures/sale_setProblemComponentLack.sql index 363663a00..aa5f5f1be 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLack.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLack.sql @@ -10,9 +10,13 @@ BEGIN * @param vSelf Id del sale */ CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) + (INDEX(saleFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT vSelf saleFk, sale_hasComponentLack(vSelf) hasProblem; + SELECT vSelf saleFk, + sale_hasComponentLack(vSelf) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded + FROM sale + WHERE id = vSelf; CALL sale_setProblem('hasComponentLack'); diff --git a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql index b911327dd..2ee49b656 100644 --- a/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql +++ b/db/routines/vn/procedures/sale_setProblemComponentLackByComponent.sql @@ -10,11 +10,13 @@ BEGIN * @param vComponentFk Id component */ CREATE OR REPLACE TEMPORARY TABLE tmp.sale - (INDEX(saleFk)) + (INDEX(saleFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT saleFk, sale_hasComponentLack(saleFk)hasProblem + SELECT saleFk, + sale_hasComponentLack(saleFk) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded FROM ( - SELECT s.id saleFk + SELECT s.id saleFk, s.ticketFk FROM ticket t JOIN sale s ON s.ticketFk = t.id LEFT JOIN saleComponent sc ON sc.saleFk = s.id diff --git a/db/routines/vn/procedures/sale_setProblemRounding.sql b/db/routines/vn/procedures/sale_setProblemRounding.sql index f14cd408f..f58d00799 100644 --- a/db/routines/vn/procedures/sale_setProblemRounding.sql +++ b/db/routines/vn/procedures/sale_setProblemRounding.sql @@ -11,9 +11,10 @@ BEGIN DECLARE vWarehouseFk INT; DECLARE vShipped DATE; DECLARE vQuantity INT; + DECLARE vIsProblemCalcNeeded BOOL; - SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity - INTO vItemFk, vWarehouseFk, vShipped, vQuantity + SELECT s.itemFk, t.warehouseFk, t.shipped, s.quantity, ticket_isProblemCalcNeeded(t.id) + INTO vItemFk, vWarehouseFk, vShipped, vQuantity, vIsProblemCalcNeeded FROM sale s JOIN ticket t ON t.id = s.ticketFk WHERE s.id = vSelf; @@ -21,7 +22,9 @@ BEGIN CALL buyUltimate(vWarehouseFk, vShipped); CREATE OR REPLACE TEMPORARY TABLE tmp.sale - SELECT vSelf saleFk, MOD(vQuantity, b.`grouping`) hasProblem + SELECT vSelf saleFk, + MOD(vQuantity, b.`grouping`) hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded FROM tmp.buyUltimate bu JOIN buy b ON b.id = bu.buyFk WHERE bu.itemFk = vItemFk; diff --git a/db/routines/vn/procedures/sectorCollection_getMyPartial.sql b/db/routines/vn/procedures/sectorCollection_getMyPartial.sql new file mode 100644 index 000000000..21f26770a --- /dev/null +++ b/db/routines/vn/procedures/sectorCollection_getMyPartial.sql @@ -0,0 +1,18 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`sectorCollection_getMyPartial`() +BEGIN +/** + * Devuelve las colecciones del sector que corresponden al usuario conectado, y que estan incompletas + * + */ + SELECT DISTINCT sc.id collectionFk, sc.created + FROM vn.sectorCollection sc + LEFT JOIN vn.sectorCollectionSaleGroup scsg ON scsg.sectorCollectionFk = sc.id + LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleGroupFk = scsg.saleGroupFk + LEFT JOIN vn.sale sl ON sl.id = sgd.saleFk + LEFT JOIN itemShelvingSale iss ON iss.saleFk = sl.id + WHERE sc.userFk = account.myUser_getId() + AND (scsg.sectorCollectionFk IS NULL OR NOT iss.isPicked) + AND sc.created > util.VN_CURDATE() - INTERVAL 1 DAY; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql new file mode 100644 index 000000000..acb460190 --- /dev/null +++ b/db/routines/vn/procedures/sectorCollection_hasSalesReserved.sql @@ -0,0 +1,25 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` FUNCTION vn.sectorCollection_hasSalesReserved(vSelf INT) RETURNS tinyint(1) +DETERMINISTIC +BEGIN +/** + * Devuelve si sectorCollection tiene reservas + * @param vSelf Id de sectorCollection + * + * returns BOOLEAN + */ + DECLARE vHasSalesReserved BOOLEAN; + + SELECT DISTINCT COUNT(*) INTO vHasSalesReserved + FROM sectorCollection sc + JOIN sectorCollectionSaleGroup scsg ON sc.id = scsg.sectorCollectionFk + JOIN saleGroup sg ON sg.id = scsg.saleGroupFk + JOIN saleGroupDetail sgd ON sgd.saleGroupFk = sg.id + JOIN sale s ON s.id = sgd.saleFk + JOIN itemShelvingSale iss ON iss.saleFk = s.id + JOIN saleTracking st ON st.saleFk = s.id + WHERE sc.id = vSelf; + + RETURN vHasSalesReserved; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/setParking.sql b/db/routines/vn/procedures/setParking.sql index 97a40bbe0..1aa4f920a 100644 --- a/db/routines/vn/procedures/setParking.sql +++ b/db/routines/vn/procedures/setParking.sql @@ -1,6 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`(IN `vParam` VARCHAR(8), IN `vParkingCode` VARCHAR(8)) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`setParking`( + vParam VARCHAR(8), + vParkingCode VARCHAR(8) +) +BEGIN /** * Aparca una colección, un ticket, un saleGroup o un shelving en un parking * @@ -8,54 +11,41 @@ proc: BEGIN * @param vParkingCode código del parking */ DECLARE vParkingFk INT; - DECLARE vIsSaleGroup BOOL; - DECLARE vIsTicket BOOL; - DECLARE vIsCollection BOOL; + DECLARE vLastWeek DATE; - SET vParkingCode = replace(vParkingCode,' ',''); + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SET vParkingCode = REPLACE(vParkingCode, ' ', ''); SELECT id INTO vParkingFk - FROM vn.parking + FROM parking WHERE code = vParkingCode COLLATE utf8_unicode_ci; IF vParkingFk IS NULL THEN CALL util.throw('parkingNotExist'); - LEAVE proc; END IF; - -- Se comprueba si es una preparación previa - SELECT COUNT(*) INTO vIsSaleGroup - FROM vn.saleGroup sg - WHERE sg.id = vParam; + START TRANSACTION; - IF vIsSaleGroup THEN - CALL vn.saleGroup_setParking(vParam, vParkingFk); - LEAVE proc; + SET vLastWeek = util.VN_CURDATE() - INTERVAL 1 WEEK; + + -- Comprobamos si es una prep. previa, ticket, colección o shelving + IF (SELECT TRUE FROM saleGroup WHERE id = vParam) THEN + CALL saleGroup_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM ticket WHERE id = vParam AND shipped >= vLastWeek) THEN + CALL ticket_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM `collection` WHERE id = vParam AND created >= vLastWeek) THEN + CALL collection_setParking(vParam, vParkingFk); + ELSEIF (SELECT TRUE FROM shelving WHERE code = vParam COLLATE utf8_unicode_ci) THEN + CALL shelving_setParking(vParam, vParkingFk); + ELSE + CALL util.throw('paramNotExist'); END IF; - -- Se comprueba si es un ticket - SELECT COUNT(*) INTO vIsTicket - FROM vn.ticket t - WHERE t.id = vParam - AND t.shipped >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsTicket THEN - CALL vn.ticket_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Se comprueba si es una coleccion de tickets - SELECT COUNT(*) INTO vIsCollection - FROM vn.collection c - WHERE c.id = vParam - AND c.created >= TIMESTAMPADD(WEEK,-1,util.VN_CURDATE()); - - IF vIsCollection THEN - CALL vn.collection_setParking(vParam, vParkingFk); - LEAVE proc; - END IF; - - -- Por descarte, se considera una matrícula - CALL vn.shelving_setParking(vParam, vParkingFk); + COMMIT; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql index 7cc72848f..63285203b 100644 --- a/db/routines/vn/procedures/supplierPackaging_ReportSource.sql +++ b/db/routines/vn/procedures/supplierPackaging_ReportSource.sql @@ -22,7 +22,7 @@ BEGIN landed, `in`, `out`, - warehouse, + sref, buyingValue, IF ( NOT (@vItemFk <=> sub.itemFk), @@ -31,19 +31,20 @@ BEGIN ) balance, @vItemFk := sub.itemFk previousItemFk FROM ( - SELECT supplierFk, - itemFk, - longName, - supplier, - CONCAT('E',entryFk) entryFk, - landed, - `in`, - `out`, - warehouse, - buyingValue - FROM supplierPackaging - WHERE supplierFk = vSupplierFk - AND landed >= vFromDated + SELECT sp.supplierFk, + sp.itemFk, + sp.longName, + sp.supplier, + CONCAT('E',sp.entryFk) entryFk, + sp.landed, + sp.`in`, + sp.`out`, + e.invoiceNumber sref, + sp.buyingValue + FROM supplierPackaging sp + JOIN entry e ON e.id = sp.entryFk + WHERE sp.supplierFk = vSupplierFk + AND sp.landed >= vFromDated UNION ALL SELECT vSupplierFk, itemFk, @@ -68,7 +69,7 @@ BEGIN DATE(t.shipped), -LEAST(s.quantity,0) `in`, GREATEST(s.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, s.price * (100 - s.discount) / 100 FROM sale s JOIN item i ON i.id = s.itemFk @@ -110,7 +111,7 @@ BEGIN DATE(t.shipped), -LEAST(tp.quantity,0) `in`, GREATEST(tp.quantity,0) `out`, - t.warehouseFk, + t.cmrFk, 0 FROM ticketPackaging tp JOIN packaging p ON p.id = tp.packagingFk @@ -155,7 +156,7 @@ BEGIN landed, CAST(`in` AS DECIMAL(10,0)) `in`, CAST(`out` AS DECIMAL(10,0)) `out`, - warehouse, + sref, buyingValue, balance FROM tSupplierPackaging diff --git a/db/routines/vn/procedures/ticket_Clone.sql b/db/routines/vn/procedures/ticket_Clone.sql index 7670e832e..d22d3c7ff 100644 --- a/db/routines/vn/procedures/ticket_Clone.sql +++ b/db/routines/vn/procedures/ticket_Clone.sql @@ -9,6 +9,11 @@ BEGIN */ DECLARE vStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO ticket ( clientFk, shipped, diff --git a/db/routines/vn/procedures/ticket_DelayTruck.sql b/db/routines/vn/procedures/ticket_DelayTruck.sql index 20601ee49..81896dd8e 100644 --- a/db/routines/vn/procedures/ticket_DelayTruck.sql +++ b/db/routines/vn/procedures/ticket_DelayTruck.sql @@ -3,14 +3,14 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruck`( BEGIN DECLARE done INT DEFAULT FALSE; DECLARE vTicketFk INT; - DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tmp.ticket; + DECLARE cur1 CURSOR FOR SELECT ticketFk FROM tTicket; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; CALL vn.productionControl(vWarehouserFk,0) ; - DROP TEMPORARY TABLE IF EXISTS tmp.ticket; - CREATE TEMPORARY TABLE tmp.ticket + DROP TEMPORARY TABLE IF EXISTS tTicket; + CREATE TEMPORARY TABLE tTicket SELECT ticketFk FROM tmp.productionBuffer JOIN alertLevel al ON al.code = 'FREE' @@ -31,5 +31,6 @@ BEGIN END LOOP; CLOSE cur1; + DROP TEMPORARY TABLE tTicket, tmp.productionBuffer; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql index c7de6a984..3e5195d9c 100644 --- a/db/routines/vn/procedures/ticket_DelayTruckSplit.sql +++ b/db/routines/vn/procedures/ticket_DelayTruckSplit.sql @@ -1,5 +1,7 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`(vTicketFk INT) +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_DelayTruckSplit`( + vTicketFk INT +) BEGIN /** * Splita las lineas de ticket que no estan ubicadas @@ -50,8 +52,8 @@ BEGIN SET s.ticketFk = vNewTicketFk; END IF; - CALL ticketStateUpdate(vNewTicketFk, 'FIXING'); + CALL ticket_setState(vNewTicketFk, 'FIXING'); DROP TEMPORARY TABLE tmp.SalesToSplit; -END$$ -DELIMITER ; +END$$ +DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_add.sql b/db/routines/vn/procedures/ticket_add.sql index 5c3c28081..d9b68997c 100644 --- a/db/routines/vn/procedures/ticket_add.sql +++ b/db/routines/vn/procedures/ticket_add.sql @@ -65,6 +65,8 @@ BEGIN IF (vZoneFk IS NULL OR vZoneFk = 0) AND vIsRequiredZone THEN CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); END IF; + + DROP TEMPORARY TABLE tmp.zoneGetShipped; END IF; INSERT INTO ticket ( diff --git a/db/routines/vn/procedures/ticket_checkNoComponents.sql b/db/routines/vn/procedures/ticket_checkNoComponents.sql index 28fe333f0..b03427192 100644 --- a/db/routines/vn/procedures/ticket_checkNoComponents.sql +++ b/db/routines/vn/procedures/ticket_checkNoComponents.sql @@ -20,7 +20,8 @@ BEGIN JOIN itemCategory ic ON ic.id = tp.categoryFk JOIN saleComponent sc ON sc.saleFk = s.id JOIN component c ON c.id = sc.componentFk - JOIN componentType ct ON ct.id = c.typeFk AND ct.id = 1 + JOIN componentType ct ON ct.id = c.typeFk + AND ct.code = 'cost' WHERE t.shipped BETWEEN vShippedFrom AND vShippedTo AND ic.merchandise; diff --git a/db/routines/vn/procedures/ticket_cloneWeekly.sql b/db/routines/vn/procedures/ticket_cloneWeekly.sql index 6bceb2fdf..fd45dc9fa 100644 --- a/db/routines/vn/procedures/ticket_cloneWeekly.sql +++ b/db/routines/vn/procedures/ticket_cloneWeekly.sql @@ -1,5 +1,8 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`(vDateFrom DATE, vDateTo DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_cloneWeekly`( + vDateFrom DATE, + vDateTo DATE +) BEGIN DECLARE vIsDone BOOL; DECLARE vLanding DATE; @@ -39,9 +42,16 @@ BEGIN DECLARE vIsDuplicateMail BOOL; DECLARE vSubject VARCHAR(150); DECLARE vMessage TEXT; - + SET vIsDone = FALSE; - FETCH rsTicket INTO vTicketFk,vClientFk, vWarehouseFk, vCompanyFk, vAddressFk, vAgencyModeFk,vShipment; + FETCH rsTicket INTO + vTicketFk, + vClientFk, + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + vShipment; IF vIsDone THEN LEAVE myLoop; @@ -67,7 +77,7 @@ BEGIN AND isDefaultAddress; END IF; - CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk,FALSE); + CALL zone_getLanded(vShipment, vAddressFk, vAgencyModeFk, vWarehouseFk, FALSE); SET vLanding = NULL; SELECT landed INTO vLanding FROM tmp.zoneGetLanded LIMIT 1; @@ -88,16 +98,22 @@ BEGIN SET clonedFrom = vTicketFk WHERE id = vNewTicket; - INSERT INTO sale (ticketFk, itemFk, concept, quantity, price, - discount, priceFixed, isPriceFixed) + INSERT INTO sale (ticketFk, + itemFk, + concept, + quantity, + price, + discount, + priceFixed, + isPriceFixed) SELECT vNewTicket, - saleOrig.itemFk, - saleOrig.concept, - saleOrig.quantity, - saleOrig.price, - saleOrig.discount, - saleOrig.priceFixed, - saleOrig.isPriceFixed + saleOrig.itemFk, + saleOrig.concept, + saleOrig.quantity, + saleOrig.price, + saleOrig.discount, + saleOrig.priceFixed, + saleOrig.isPriceFixed FROM sale saleOrig WHERE saleOrig.ticketFk = vTicketFk; @@ -123,20 +139,20 @@ BEGIN ,attenderFk, ticketFk) SELECT description, - ordered, - shipped, - quantity, - price, - itemFk, - clientFk, - response, - total, - buyed, - requesterFk, - attenderFk, - vNewTicket + ordered, + shipped, + quantity, + price, + itemFk, + clientFk, + response, + total, + buyed, + requesterFk, + attenderFk, + vNewTicket FROM ticketRequest - WHERE ticketFk =vTicketFk; + WHERE ticketFk =vTicketFk; SELECT id INTO vSalesPersonFK FROM observationType @@ -189,7 +205,7 @@ BEGIN IF NOT vIsDuplicateMail THEN CALL mail_insert(vSalesPersonEmail, NULL, vSubject, vMessage); END IF; - CALL ticketStateUpdate (vNewTicket, 'FIXING'); + CALL ticket_setState(vNewTicket, 'FIXING'); ELSE CALL ticketCalculateClon(vNewTicket, vTicketFk); END IF; @@ -197,6 +213,6 @@ BEGIN END; END LOOP; CLOSE rsTicket; - DROP TEMPORARY TABLE IF EXISTS tmp.time; + DROP TEMPORARY TABLE IF EXISTS tmp.time, tmp.zoneGetLanded; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_close.sql b/db/routines/vn/procedures/ticket_close.sql index 47d748ddf..7f52e81a7 100644 --- a/db/routines/vn/procedures/ticket_close.sql +++ b/db/routines/vn/procedures/ticket_close.sql @@ -44,14 +44,14 @@ BEGIN t.shipped, IFNULL(a.hasDailyInvoice, co.hasDailyInvoice), w.isManaged, - c.hasToInvoice + c.hasToInvoice INTO vClientFk, vIsTaxDataChecked, vCompanyFk, vShipped, vHasDailyInvoice, vWithPackage, - vHasToInvoice + vHasToInvoice FROM ticket t JOIN `client` c ON c.id = t.clientFk JOIN province p ON p.id = c.provinceFk @@ -64,8 +64,12 @@ BEGIN (SELECT vCurTicketFk, p.id, COUNT(*) FROM expedition e JOIN packaging p ON p.id = e.packagingFk + JOIN ticket t ON t.id = e.ticketFk + LEFT JOIN agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN deliveryMethod dm ON dm.id = am.deliveryMethodFk WHERE e.ticketFk = vCurTicketFk AND p.isPackageReturnable AND vWithPackage + AND NOT dm.`code`= 'PICKUP' GROUP BY p.itemFk); -- No retornables o no catalogados diff --git a/db/routines/vn/procedures/ticket_getFromFloramondo.sql b/db/routines/vn/procedures/ticket_getFromFloramondo.sql index 4d83d6dda..5f2bedbb1 100644 --- a/db/routines/vn/procedures/ticket_getFromFloramondo.sql +++ b/db/routines/vn/procedures/ticket_getFromFloramondo.sql @@ -66,7 +66,7 @@ BEGIN JOIN vn.componentType ct ON ct.id = c.typeFk JOIN vn.sale s ON s.id = sc.saleFk JOIN tmp.ticket t ON t.ticketFk = s.ticketFk - WHERE ct.code = 'FREIGHT' + WHERE ct.code = 'freight' GROUP BY t.ticketFk) sb ON sb.ticketFk = tf.ticketFk SET tf.freight = sb.freight; @@ -88,7 +88,7 @@ BEGIN -- Margin UPDATE tmp.ticketFloramondo tf - JOIN (SELECT SUM(IF(ct.code = 'COST',sc.value, 0)) cost, + JOIN (SELECT SUM(IF(ct.code = 'cost',sc.value, 0)) cost, SUM(IF(ct.isMargin, sc.value, 0)) margin, t.ticketFk FROM vn.saleComponent sc diff --git a/db/routines/vn/procedures/ticket_setNextState.sql b/db/routines/vn/procedures/ticket_setNextState.sql index d13cd53f0..b09309a47 100644 --- a/db/routines/vn/procedures/ticket_setNextState.sql +++ b/db/routines/vn/procedures/ticket_setNextState.sql @@ -1,14 +1,21 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`(vSelf INT) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setNextState`( + vSelf INT +) BEGIN /** - * Cambia el estado del ticket al siguiente estado según la tabla state + * Cambia el estado del ticket al siguiente estado según la tabla state. * - * @param vSelf id dle ticket + * @param vSelf Id ticket */ DECLARE vStateFk INT; DECLARE vNewStateFk INT; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + SELECT stateFk INTO vStateFk FROM ticketState WHERE ticketFk = vSelf; @@ -17,6 +24,10 @@ BEGIN FROM state WHERE id = vStateFk; + IF vNewStateFk IS NULL THEN + CALL util.throw('The ticket not have next state'); + END IF; + INSERT INTO ticketTracking(stateFk, ticketFk, userFk) VALUES (vNewStateFk, vSelf, account.myUser_getId()); END$$ diff --git a/db/routines/vn/procedures/ticket_setParking.sql b/db/routines/vn/procedures/ticket_setParking.sql index 54c64daea..7935e0d60 100644 --- a/db/routines/vn/procedures/ticket_setParking.sql +++ b/db/routines/vn/procedures/ticket_setParking.sql @@ -1,11 +1,14 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`(IN `vTicketFk` VARCHAR(8), IN `vParkingFk` INT) -proc: BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setParking`( + vSelf INT, + vParkingFk INT +) +BEGIN /** - * Aparca un ticket en un parking + * Aparca un ticket en un parking. * - * @param vTicketFk id del ticket - * @param vParkingFk id del parking + * @param vSelf Id ticket + * @param vParkingFk Id parking */ DECLARE vDone INT DEFAULT FALSE; DECLARE vCollectionTicketFk INT; @@ -14,16 +17,21 @@ proc: BEGIN FROM ticket t LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk - WHERE t.id = vTicketFk; + WHERE t.id = vSelf; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + RESIGNAL; + END; + INSERT INTO vn.ticketParking(ticketFk, parkingFk) SELECT IFNULL(tc2.ticketFk, t.id), vParkingFk FROM ticket t LEFT JOIN ticketCollection tc1 ON tc1.ticketFk = t.id LEFT JOIN ticketCollection tc2 ON tc2.collectionFk = tc1.collectionFk - WHERE t.id = vTicketFk + WHERE t.id = vSelf ON DUPLICATE KEY UPDATE parkingFk = vParkingFk; OPEN vCursor; diff --git a/db/routines/vn/procedures/ticket_setProblem.sql b/db/routines/vn/procedures/ticket_setProblem.sql index bab8f1f52..66d244d5a 100644 --- a/db/routines/vn/procedures/ticket_setProblem.sql +++ b/db/routines/vn/procedures/ticket_setProblem.sql @@ -4,16 +4,34 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_setProblem`( ) BEGIN /** - * Update column ticket.problem with a problem code + * Update column ticket.problem with a problem code and SET NULL when + * the problem is not requiered * * @param vProblemCode Code to set or unset - * @table tmp.ticket(ticketFk, hasProblem) + * @table tmp.ticket(ticketFk, hasProblem, isProblemCalcNeeded) */ - UPDATE ticket t - JOIN tmp.ticket tt ON tt.ticketFk = t.id - SET t.problem = CONCAT( - IF(tt.hasProblem, - CONCAT(problem, ',', vProblemCode), - REPLACE(problem, vProblemCode , ''))); + DECLARE vTicketFk INT; + DECLARE vHasProblem INT; + DECLARE vDone BOOL; + DECLARE vTicketList CURSOR FOR SELECT ticketFk, hasProblem FROM tmp.ticket; + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + OPEN vTicketList; + l: LOOP + SET vDone = FALSE; + FETCH vTicketList INTO vTicketFk, vHasProblem; + + IF vDone THEN + LEAVE l; + END IF; + + UPDATE ticket + SET problem = CONCAT( + IF(vHasProblem, + CONCAT(problem, ',', vProblemCode), + REPLACE(problem, vProblemCode , ''))) + WHERE id = vTicketFk; + END LOOP; + CLOSE vTicketList; END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticket_setProblemFreeze.sql b/db/routines/vn/procedures/ticket_setProblemFreeze.sql index 560bce612..1de939ba7 100644 --- a/db/routines/vn/procedures/ticket_setProblemFreeze.sql +++ b/db/routines/vn/procedures/ticket_setProblemFreeze.sql @@ -9,9 +9,11 @@ BEGIN * @param vClientFk Id Cliente, if NULL all clients */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, FALSE hasProblem + SELECT t.id ticketFk, + FALSE hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t WHERE t.shipped >= util.VN_CURDATE() AND (vClientFk IS NULL OR t.clientFk = vClientFk); @@ -21,7 +23,7 @@ BEGIN JOIN client c ON c.id = ti.clientFk SET t.hasProblem = TRUE WHERE c.isFreezed; - + CALL ticket_setProblem('isFreezed'); DROP TEMPORARY TABLE tmp.ticket; diff --git a/db/routines/vn/procedures/ticket_setProblemRequest.sql b/db/routines/vn/procedures/ticket_setProblemRequest.sql index 19bba5b76..687facfc7 100644 --- a/db/routines/vn/procedures/ticket_setProblemRequest.sql +++ b/db/routines/vn/procedures/ticket_setProblemRequest.sql @@ -9,9 +9,11 @@ BEGIN * @param vSelf Id ticket, if NULL ALL tickets */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, FALSE hasProblem + SELECT t.id ticketFk, + FALSE hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t WHERE t.shipped >= util.VN_CURDATE() AND (vSelf IS NULL OR t.id = vSelf); diff --git a/db/routines/vn/procedures/ticket_setProblemRisk.sql b/db/routines/vn/procedures/ticket_setProblemRisk.sql index 5f73ee838..efa5b10e2 100644 --- a/db/routines/vn/procedures/ticket_setProblemRisk.sql +++ b/db/routines/vn/procedures/ticket_setProblemRisk.sql @@ -10,21 +10,30 @@ BEGIN */ DECLARE vHasRisk BOOL; DECLARE vHasHighRisk BOOL; + DECLARE vIsProblemCalcNeeded BOOL; - SELECT t.risk > (c.credit + 10), ((t.risk - cc.riskTolerance) > (c.credit + 10)) - INTO vHasRisk, vHasHighRisk + SELECT t.risk > (c.credit + 10), + (t.risk - cc.riskTolerance) > (c.credit + 10), + ticket_isProblemCalcNeeded(t.id) + INTO vHasRisk, vHasHighRisk, vIsProblemCalcNeeded FROM client c JOIN ticket t ON t.clientFk = c.id JOIN clientConfig cc WHERE t.id = vSelf; CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vHasRisk hasProblem; + ENGINE = MEMORY + SELECT vSelf ticketFk, + vHasRisk hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded; CALL ticket_setProblem('hasRisk'); CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - SELECT vSelf ticketFk, vHasHighRisk hasProblem; + ENGINE = MEMORY + SELECT vSelf ticketFk, + vHasHighRisk hasProblem, + vIsProblemCalcNeeded isProblemCalcNeeded; CALL ticket_setProblem('hasHighRisk'); diff --git a/db/routines/vn/procedures/ticket_setProblemRounding.sql b/db/routines/vn/procedures/ticket_setProblemRounding.sql index 81294325c..fb580eacf 100644 --- a/db/routines/vn/procedures/ticket_setProblemRounding.sql +++ b/db/routines/vn/procedures/ticket_setProblemRounding.sql @@ -18,8 +18,11 @@ BEGIN CALL buyUltimate(vWarehouseFk, vDated); - CREATE OR REPLACE TEMPORARY TABLE tmp.sale - SELECT s.id saleFk , MOD(s.quantity, b.`grouping`) hasProblem + CREATE OR REPLACE TEMPORARY TABLE tmp.sale + (INDEX(saleFk, isProblemCalcNeeded)) + SELECT s.id saleFk , + MOD(s.quantity, b.`grouping`) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t JOIN sale s ON s.ticketFk = t.id JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk diff --git a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql index 00918426b..9877b5acc 100644 --- a/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql +++ b/db/routines/vn/procedures/ticket_setProblemTaxDataChecked.sql @@ -9,9 +9,11 @@ BEGIN * @param vClientFk Id cliente, if NULL all clients */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT t.id ticketFk, IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem + SELECT t.id ticketFk, + IF(c.isTaxDataChecked, FALSE, TRUE) hasProblem, + ticket_isProblemCalcNeeded(t.id) isProblemCalcNeeded FROM ticket t JOIN client c ON c.id = t.clientFk WHERE t.shipped >= util.VN_CURDATE() diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittle.sql b/db/routines/vn/procedures/ticket_setProblemTooLittle.sql index 98a0787af..48cc47809 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittle.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittle.sql @@ -8,13 +8,17 @@ BEGIN * * @param vSelf Id del ticket */ + CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY - SELECT vSelf ticketFk, ticket_isTooLittle(vSelf) hasProblem; + SELECT vSelf ticketFk, + ticket_isTooLittle(vSelf) hasProblem, + ticket_isProblemCalcNeeded(vSelf) isProblemCalcNeeded; CALL ticket_setProblem('isTooLittle'); DROP TEMPORARY TABLE tmp.ticket; + END$$ DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql index cd1f42783..ac3814c07 100644 --- a/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql +++ b/db/routines/vn/procedures/ticket_setProblemTooLittleItemCost.sql @@ -10,7 +10,7 @@ BEGIN * @param vItemFk Id del item, NULL ALL items */ CREATE OR REPLACE TEMPORARY TABLE tmp.ticket - (INDEX(ticketFk)) + (INDEX(ticketFk, isProblemCalcNeeded)) ENGINE = MEMORY WITH tickets AS( SELECT t.id ticketFk @@ -19,7 +19,9 @@ BEGIN WHERE t.shipped >= util.VN_CURDATE() AND (s.itemFk = vItemFk OR vItemFk IS NULL) GROUP BY t.id - )SELECT ticketFk, ticket_isTooLittle(ticketFk) hasProblem + )SELECT ticketFk, + ticket_isTooLittle(ticketFk) hasProblem, + ticket_isProblemCalcNeeded(ticketFk) isProblemCalcNeeded FROM tickets; CALL ticket_setProblem('isTooLittle'); diff --git a/db/routines/vn/procedures/ticket_setRisk.sql b/db/routines/vn/procedures/ticket_setRisk.sql index f5e6cb5a0..bd5d1e9f9 100644 --- a/db/routines/vn/procedures/ticket_setRisk.sql +++ b/db/routines/vn/procedures/ticket_setRisk.sql @@ -8,6 +8,7 @@ BEGIN * @param vClientFk Id cliente */ DECLARE vHasDebt BOOL; + DECLARE vStarted DATETIME; SELECT COUNT(*) INTO vHasDebt FROM `client` @@ -16,22 +17,24 @@ BEGIN IF vHasDebt THEN + SELECT util.VN_CURDATE() - INTERVAL riskScope MONTH INTO vStarted + FROM clientConfig; + CREATE OR REPLACE TEMPORARY TABLE tTicketRisk (KEY (ticketFk)) ENGINE = MEMORY WITH ticket AS( - SELECT id ticketFk, companyFk, DATE(shipped) dated - FROM vn.ticket t + SELECT id ticketFk, + companyFk, + DATE(shipped) dated, + totalWithVat, + ticket_isProblemCalcNeeded(id) isProblemCalcNeeded + FROM vn.ticket WHERE clientFk = vClientFk AND refFk IS NULL AND NOT isDeleted - AND totalWithoutVat <> 0 - ), dated AS( - SELECT t.companyFk, MIN(DATE(t.dated) - INTERVAL cc.riskScope MONTH) started, - MAX(DATE(t.dated)) ended - FROM ticket t - JOIN vn.clientConfig cc - GROUP BY t.companyFk + AND IFNULL(totalWithVat, 0) <> 0 + AND shipped > vStarted ), balance AS( SELECT SUM(amount)amount, companyFk FROM ( @@ -49,15 +52,11 @@ BEGIN WHERE companyFk GROUP BY companyFk ), uninvoiced AS( - SELECT t.companyFk, DATE(t.shipped) dated, SUM(IFNULL(t.totalWithVat, 0)) amount - FROM vn.ticket t - JOIN dated d - WHERE t.clientFk = vClientFk - AND t.refFk IS NULL - AND t.shipped BETWEEN d.started AND d.ended - GROUP BY t.companyFk, DATE(t.shipped) + SELECT companyFk, dated, SUM(totalWithVat) amount + FROM ticket + GROUP BY companyFk, dated ), receipt AS( - SELECT companyFk,DATE(payed) dated, SUM(amountPaid) amount + SELECT companyFk, DATE(payed) dated, SUM(amountPaid) amount FROM vn.receipt WHERE clientFk = vClientFk AND payed > util.VN_CURDATE() @@ -73,13 +72,21 @@ BEGIN LEFT JOIN receipt r ON r.dated > ui.dated AND r.companyFk = ui.companyFk GROUP BY b.companyFk, ui.dated ) - SELECT ti.ticketFk, r.amount + SELECT ti.ticketFk, r.amount, ti.isProblemCalcNeeded FROM ticket ti JOIN risk r ON r.dated = ti.dated AND r.companyFk = ti.companyFk; UPDATE ticket t JOIN tTicketRisk tr ON tr.ticketFk = t.id - SET t.risk = tr.amount; + SET t.risk = tr.amount + WHERE tr.isProblemCalcNeeded + ORDER BY t.id; + + UPDATE ticket t + JOIN tTicketRisk tr ON tr.ticketFk = t.id + SET t.risk = NULL + WHERE tr.isProblemCalcNeeded + ORDER BY t.id; DROP TEMPORARY TABLE tTicketRisk; END IF; diff --git a/db/routines/vn/procedures/ticket_split.sql b/db/routines/vn/procedures/ticket_split.sql index 172f6829a..9a359b83f 100644 --- a/db/routines/vn/procedures/ticket_split.sql +++ b/db/routines/vn/procedures/ticket_split.sql @@ -1,5 +1,9 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_split`(vTicketFk INT, vTicketFutureFk INT, vDated DATE) +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_split`( + vTicketFk INT, + vTicketFutureFk INT, + vDated DATE +) proc:BEGIN /** * Mueve las lineas con problemas a otro ticket existente o a uno nuevo. @@ -17,60 +21,56 @@ proc:BEGIN FROM tmp.salesToSplit WHERE ticketFk = vTicketFk; - SELECT count(*) INTO vTotalLines - FROM vn.sale s + SELECT COUNT(*) INTO vTotalLines + FROM sale s WHERE s.ticketFk = vTicketFk; SET vHasFullProblem = (vTotalLines = vProblemLines); -- Ticket completo IF vHasFullProblem THEN - - UPDATE vn.ticket - SET landed = vDated + INTERVAL 1 DAY, + UPDATE ticket + SET landed = vDated + INTERVAL 1 DAY, shipped = vDated, - nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname ) + nickname = CONCAT('(',DAY(util.VN_CURDATE()),') ', nickname) WHERE id = vTicketFk; - SELECT "moved" message, NULL ticketFuture; + SELECT 'moved' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket a futuro existe IF vTicketFutureFk THEN - - UPDATE vn.sale s - JOIN tmp.salesToSplit ss ON s.id = ss.saleFk + UPDATE 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 "future" message, NULL ticketFuture; + SELECT 'future' message, NULL ticketFuture; LEAVE proc; - END IF; -- Ticket nuevo - CALL vn.ticket_Clone(vTicketFk, vTicketFutureFk); + CALL ticket_Clone(vTicketFk, vTicketFutureFk); - UPDATE vn.ticket t - JOIN vn.productionConfig pc + UPDATE ticket t + JOIN productionConfig pc SET t.routeFk = IF(t.shipped = vDated , t.routeFk, NULL), - t.landed = vDated + INTERVAL 1 DAY, + t.landed = vDated + INTERVAL 1 DAY, t.shipped = vDated, t.agencyModeFk = pc.defautlAgencyMode, t.zoneFk = pc.defaultZone WHERE t.id = vTicketFutureFk; - - UPDATE vn.sale s - JOIN tmp.salesToSplit sts ON sts.saleFk = s.id + + UPDATE 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'); + CALL ticket_setState(vTicketFutureFk, 'FIXING'); - SELECT "new" message,vTicketFutureFk ticketFuture; + SELECT 'new' message, vTicketFutureFk ticketFuture; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/ticket_splitItemPackingType.sql b/db/routines/vn/procedures/ticket_splitItemPackingType.sql index d6424efad..c2ec50fd9 100644 --- a/db/routines/vn/procedures/ticket_splitItemPackingType.sql +++ b/db/routines/vn/procedures/ticket_splitItemPackingType.sql @@ -1,106 +1,143 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`(vTicketFk INT, vOriginalItemPackingTypeFk VARCHAR(1)) -proc:BEGIN +CREATE OR REPLACE DEFINER=`root`@`localhost` PROCEDURE `vn`.`ticket_splitItemPackingType`( + vSelf INT, + vItemPackingTypeFk VARCHAR(1) +) +BEGIN /** * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado. * Respeta el id inicial para el tipo propuesto. * - * @param vTicketFk Identificador de vn.ticket - * @param vOriginalItemPackingTypeFk Tipo para el que se reserva el número de ticket original + * @param vSelf Id ticket + * @param vItemPackingTypeFk Tipo para el que se reserva el número de ticket original * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) */ DECLARE vItemPackingTypeFk VARCHAR(1) DEFAULT 'H'; DECLARE vNewTicketFk INT; DECLARE vPackingTypesToSplit INT; DECLARE vDone INT DEFAULT FALSE; + DECLARE vErrorNumber INT; + DECLARE vErrorMsg TEXT; - DECLARE cur1 CURSOR FOR + DECLARE vSaleGroup CURSOR FOR SELECT itemPackingTypeFk - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL - ORDER BY (itemPackingTypeFk = vOriginalItemPackingTypeFk) DESC; + ORDER BY (itemPackingTypeFk = vItemPackingTypeFk) DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DELETE FROM vn.sale - WHERE quantity = 0 - AND ticketFk = vTicketFk; + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + GET DIAGNOSTICS CONDITION 1 + vErrorNumber = MYSQL_ERRNO, + vErrorMsg = MESSAGE_TEXT; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale + CALL util.debugAdd('ticket_splitItemPackingType', JSON_OBJECT( + 'errorNumber', vErrorNumber, + 'errorMsg', vErrorMsg, + 'ticketFk', vSelf + )); -- Tmp + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + SELECT id + FROM sale + WHERE ticketFk = vSelf + AND NOT quantity + FOR UPDATE; + + DELETE FROM sale + WHERE NOT quantity + AND ticketFk = vSelf; + + CREATE OR REPLACE TEMPORARY TABLE tSale (PRIMARY KEY (id)) - SELECT s.id, i.itemPackingTypeFk , IFNULL(sv.litros, 0) litros - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vTicketFk; + ENGINE = MEMORY + SELECT s.id, i.itemPackingTypeFk, IFNULL(sv.litros, 0) litros + FROM sale s + JOIN item i ON i.id = s.itemFk + LEFT JOIN saleVolume sv ON sv.saleFk = s.id + WHERE s.ticketFk = vSelf; - DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup; - CREATE TEMPORARY TABLE tmp.saleGroup - SELECT itemPackingTypeFk , sum(litros) AS totalLitros - FROM tmp.sale + CREATE OR REPLACE TEMPORARY TABLE tSaleGroup + ENGINE = MEMORY + SELECT itemPackingTypeFk, SUM(litros) totalLitros + FROM tSale GROUP BY itemPackingTypeFk; SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tmp.saleGroup + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - (ticketFk INT, - itemPackingTypeFk VARCHAR(1)); + CREATE OR REPLACE TEMPORARY TABLE tmp.ticketIPT( + ticketFk INT, + itemPackingTypeFk VARCHAR(1) + ) ENGINE = MEMORY; CASE vPackingTypesToSplit WHEN 0 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); WHEN 1 THEN INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vTicketFk, itemPackingTypeFk - FROM tmp.saleGroup + SELECT vSelf, itemPackingTypeFk + FROM tSaleGroup WHERE itemPackingTypeFk IS NOT NULL; ELSE - OPEN cur1; - - FETCH cur1 INTO vItemPackingTypeFk; + OPEN vSaleGroup; + FETCH vSaleGroup INTO vItemPackingTypeFk; INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); + VALUES(vSelf, vItemPackingTypeFk); - read_loop: LOOP - FETCH cur1 INTO vItemPackingTypeFk; + l: LOOP + SET vDone = FALSE; + FETCH vSaleGroup INTO vItemPackingTypeFk; IF vDone THEN - LEAVE read_loop; + LEAVE l; END IF; - CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); + CALL ticket_Clone(vSelf, vNewTicketFk); INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) VALUES(vNewTicketFk, vItemPackingTypeFk); END LOOP; - CLOSE cur1; + CLOSE vSaleGroup; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + SELECT s.id + FROM sale s + JOIN tSale ts ON ts.id = s.id + JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk + FOR UPDATE; + + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk SET s.ticketFk = t.ticketFk; SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tmp.saleGroup sg - WHERE NOT ISNULL(sg.itemPackingTypeFk) + FROM tSaleGroup sg + WHERE sg.itemPackingTypeFk IS NOT NULL ORDER BY sg.itemPackingTypeFk LIMIT 1; - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id + UPDATE sale s + JOIN tSale ts ON ts.id = s.id JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk SET s.ticketFk = t.ticketFk WHERE ts.itemPackingTypeFk IS NULL; END CASE; - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE tmp.saleGroup; + COMMIT; + + DROP TEMPORARY TABLE + tSale, + tSaleGroup; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/workerTimeControl_direction.sql b/db/routines/vn/procedures/workerTimeControl_direction.sql index f7a68e1e4..8e807084c 100644 --- a/db/routines/vn/procedures/workerTimeControl_direction.sql +++ b/db/routines/vn/procedures/workerTimeControl_direction.sql @@ -9,6 +9,8 @@ BEGIN */ DECLARE vLastIn DATETIME ; DECLARE vIsMiddleOdd BOOLEAN ; + DECLARE vMailTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; IF (vTimed IS NULL) THEN SET vTimed = util.VN_NOW(); @@ -57,5 +59,18 @@ BEGIN VALUES('in', NULL); END IF; + IF (SELECT option1 IS NULL AND option2 IS NULL FROM tmp.workerTimeControlDirection) THEN + 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; + + CALL mail_insert( + vMailTo, + vMailTo, + 'Error al fichar', + CONCAT(vUserName, ' tiene problemas para fichar')); + END IF; END$$ DELIMITER ; diff --git a/db/routines/vn/procedures/zone_getCollisions.sql b/db/routines/vn/procedures/zone_getCollisions.sql index 023b9aac2..e28b2b341 100644 --- a/db/routines/vn/procedures/zone_getCollisions.sql +++ b/db/routines/vn/procedures/zone_getCollisions.sql @@ -103,6 +103,7 @@ BEGIN DROP TEMPORARY TABLE geoCollision, tmp.zone, - tmp.zoneNodes; + tmp.zoneNodes, + tmp.zoneOption; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/business_beforeUpdate.sql b/db/routines/vn/triggers/business_beforeUpdate.sql index 4b7a10041..7dc69bc75 100644 --- a/db/routines/vn/triggers/business_beforeUpdate.sql +++ b/db/routines/vn/triggers/business_beforeUpdate.sql @@ -12,23 +12,21 @@ BEGIN 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, - 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; + SELECT util.hasDateOverlapped( + started, + ended, + NEW.started, + IFNULL(NEW.ended, b.started) + ) isOverlapped INTO isOverlapping + FROM vn.business b + WHERE workerFk = NEW.workerFK + AND b.id <> NEW.id + ORDER BY isOverlapped DESC + LIMIT 1; IF isOverlapping THEN CALL util.throw ('IS_OVERLAPPING'); END IF; - END IF; - END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/delivery_beforeInsert.sql b/db/routines/vn/triggers/delivery_beforeInsert.sql index 89431c30f..eb4a6f21a 100644 --- a/db/routines/vn/triggers/delivery_beforeInsert.sql +++ b/db/routines/vn/triggers/delivery_beforeInsert.sql @@ -3,18 +3,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeInsert BEFORE INSERT ON `delivery` FOR EACH ROW BEGIN - - IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) + IF (NEW.longitude IS NOT NULL + AND NEW.latitude IS NOT NULL + AND NEW.ticketFK IS NOT NULL) THEN - UPDATE address - SET longitude = NEW.longitude, - latitude = NEW.latitude - WHERE id IN ( - SELECT addressFK - FROM ticket - WHERE id = NEW.ticketFk - ); + CALL address_updateCoordinates(NEW.ticketFk, NEW.longitude, NEW.latitude); END IF; - END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/delivery_beforeUpdate.sql b/db/routines/vn/triggers/delivery_beforeUpdate.sql index 7e6aa7d4c..6206d4722 100644 --- a/db/routines/vn/triggers/delivery_beforeUpdate.sql +++ b/db/routines/vn/triggers/delivery_beforeUpdate.sql @@ -3,18 +3,11 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`delivery_beforeUpdate BEFORE UPDATE ON `delivery` FOR EACH ROW BEGIN - -IF (NEW.longitude IS NOT NULL AND NEW.latitude IS NOT NULL AND NEW.ticketFK IS NOT NULL) + IF (NEW.longitude IS NOT NULL + AND NEW.latitude IS NOT NULL + AND NEW.ticketFK IS NOT NULL) THEN - UPDATE address - SET longitude = NEW.longitude, - latitude = NEW.latitude - WHERE id IN ( - SELECT addressFK - FROM ticket - WHERE id = NEW.ticketFk - ); + CALL address_updateCoordinates(NEW.ticketFk, NEW.longitude, NEW.latitude); END IF; - END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/entry_beforeUpdate.sql b/db/routines/vn/triggers/entry_beforeUpdate.sql index 31c6f9bd6..0a161853b 100644 --- a/db/routines/vn/triggers/entry_beforeUpdate.sql +++ b/db/routines/vn/triggers/entry_beforeUpdate.sql @@ -11,11 +11,9 @@ BEGIN IF NEW.isBooked = OLD.isBooked AND ( NOT (NEW.supplierFk <=> OLD.supplierFk) OR NOT (NEW.dated <=> OLD.dated) OR - NOT (NEW.invoiceNumber <=> OLD.invoiceNumber) OR NOT (NEW.travelFk <=> OLD.travelFk) OR NOT (NEW.companyFk <=> OLD.companyFk) OR NOT (NEW.invoiceInFk <=> OLD.invoiceInFk) OR - NOT (NEW.invoiceAmount <=> OLD.invoiceAmount) OR NOT (NEW.typeFk <=> OLD.typeFk) ) THEN diff --git a/db/routines/vn/triggers/itemMinimumQuantity_afterDelete.sql b/db/routines/vn/triggers/itemMinimumQuantity_afterDelete.sql new file mode 100644 index 000000000..1da5a5942 --- /dev/null +++ b/db/routines/vn/triggers/itemMinimumQuantity_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemMinimumQuantity_afterDelete` + AFTER DELETE ON `itemMinimumQuantity` + FOR EACH ROW +BEGIN + INSERT INTO itemLog + SET `action` = 'delete', + `changedModel` = 'ItemMinimumQuantity', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/itemMinimumQuantity_beforeInsert.sql b/db/routines/vn/triggers/itemMinimumQuantity_beforeInsert.sql new file mode 100644 index 000000000..8833ac968 --- /dev/null +++ b/db/routines/vn/triggers/itemMinimumQuantity_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemMinimumQuantity_beforeInsert` + BEFORE INSERT ON `itemMinimumQuantity` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/itemMinimumQuantity_beforeUpdate.sql b/db/routines/vn/triggers/itemMinimumQuantity_beforeUpdate.sql new file mode 100644 index 000000000..ef030f9f9 --- /dev/null +++ b/db/routines/vn/triggers/itemMinimumQuantity_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemMinimumQuantity_beforeUpdate` + BEFORE UPDATE ON `itemMinimumQuantity` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving _afterDelete.sql b/db/routines/vn/triggers/itemShelving _afterDelete.sql index 7c0d54358..9a1759eff 100644 --- a/db/routines/vn/triggers/itemShelving _afterDelete.sql +++ b/db/routines/vn/triggers/itemShelving _afterDelete.sql @@ -1,5 +1,5 @@ DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving _afterDelete` +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterDelete` AFTER DELETE ON `itemShelving` FOR EACH ROW BEGIN diff --git a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql index 63ca893bd..ef0048b34 100644 --- a/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql +++ b/db/routines/vn/triggers/itemShelvingSale_afterInsert.sql @@ -2,11 +2,11 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelvingSale_afterInsert` AFTER INSERT ON `itemShelvingSale` FOR EACH ROW -BEGIN - - UPDATE vn.sale - SET isPicked = TRUE - WHERE id = NEW.saleFk; - +BEGIN + + UPDATE sale s + JOIN operator o ON o.workerFk = account.myUser_getId() + SET s.isPicked = IF(o.isOnReservationMode, s.isPicked, TRUE) + WHERE id = NEW.saleFk; END$$ -DELIMITER ; +DELIMITER ; \ No newline at end of file diff --git a/db/routines/vn/triggers/itemShelving_afterInsert.sql b/db/routines/vn/triggers/itemShelving_afterInsert.sql deleted file mode 100644 index 5c0cb3853..000000000 --- a/db/routines/vn/triggers/itemShelving_afterInsert.sql +++ /dev/null @@ -1,22 +0,0 @@ -DELIMITER $$ -CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterInsert` - AFTER INSERT ON `itemShelving` - FOR EACH ROW -INSERT INTO vn.itemShelvingLog( itemShelvingFk, - workerFk, - accion, - itemFk, - shelvingFk, - visible, - `grouping`, - packing) - VALUES( NEW.id, - NEW.userFk, - 'CREA REGISTRO', - NEW.itemFk, - NEW.shelvingFk, - NEW.visible, - NEW.`grouping`, - NEW.packing - )$$ -DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_afterUpdate.sql b/db/routines/vn/triggers/itemShelving_afterUpdate.sql index 107e8ecdc..1ad57961a 100644 --- a/db/routines/vn/triggers/itemShelving_afterUpdate.sql +++ b/db/routines/vn/triggers/itemShelving_afterUpdate.sql @@ -2,7 +2,8 @@ DELIMITER $$ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_afterUpdate` AFTER UPDATE ON `itemShelving` FOR EACH ROW -INSERT INTO itemShelvingLog +BEGIN + INSERT INTO itemShelvingLog SET itemShelvingFk = NEW.id, workerFk = account.myUser_getId(), accion = 'CAMBIO', @@ -10,5 +11,8 @@ INSERT INTO itemShelvingLog shelvingFk = NEW.shelvingFk, visible = NEW.visible, `grouping` = NEW.`grouping`, - packing = NEW.packing$$ + packing = NEW.packing, + available = NEW.available; + +END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_beforeInsert.sql b/db/routines/vn/triggers/itemShelving_beforeInsert.sql index 011cf3701..e9fe17cf2 100644 --- a/db/routines/vn/triggers/itemShelving_beforeInsert.sql +++ b/db/routines/vn/triggers/itemShelving_beforeInsert.sql @@ -5,6 +5,7 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_beforeIn BEGIN SET NEW.editorFk = account.myUser_getId(); SET NEW.userFk = account.myUser_getId(); + SET NEW.available = NEW.visible; END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql index 6fd919d2e..214c64b45 100644 --- a/db/routines/vn/triggers/itemShelving_beforeUpdate.sql +++ b/db/routines/vn/triggers/itemShelving_beforeUpdate.sql @@ -3,9 +3,15 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`itemShelving_beforeUp BEFORE UPDATE ON `itemShelving` FOR EACH ROW BEGIN + SET NEW.editorFk = account.myUser_getId(); IF NEW.userFk IS NULL THEN SET NEW.userFk = account.myUser_getId(); END IF; + + IF (NEW.visible <> OLD.visible) THEN + SET NEW.available = GREATEST(NEW.available + NEW.visible - OLD.visible, 0); + END IF; + END$$ DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_afterDelete.sql b/db/routines/vn/triggers/productionConfig_afterDelete.sql new file mode 100644 index 000000000..384bf681e --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_afterDelete.sql @@ -0,0 +1,12 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_afterDelete` + AFTER DELETE ON `productionConfig` + FOR EACH ROW +BEGIN + INSERT INTO productionConfig + SET `action` = 'delete', + `changedModel` = 'ProductionConfig', + `changedModelId` = OLD.id, + `userFk` = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_beforeInsert.sql b/db/routines/vn/triggers/productionConfig_beforeInsert.sql new file mode 100644 index 000000000..99b217be4 --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_beforeInsert.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_beforeInsert` + BEFORE INSERT ON `productionConfig` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/triggers/productionConfig_beforeUpdate.sql b/db/routines/vn/triggers/productionConfig_beforeUpdate.sql new file mode 100644 index 000000000..f1ceaa471 --- /dev/null +++ b/db/routines/vn/triggers/productionConfig_beforeUpdate.sql @@ -0,0 +1,8 @@ +DELIMITER $$ +CREATE OR REPLACE DEFINER=`root`@`localhost` TRIGGER `vn`.`productionConfig_beforeUpdate` + BEFORE UPDATE ON `productionConfig` + FOR EACH ROW +BEGIN + SET NEW.editorFk = account.myUser_getId(); +END$$ +DELIMITER ; diff --git a/db/routines/vn/views/expeditionTruck.sql b/db/routines/vn/views/expeditionTruck.sql new file mode 100644 index 000000000..065869de0 --- /dev/null +++ b/db/routines/vn/views/expeditionTruck.sql @@ -0,0 +1,11 @@ +CREATE OR REPLACE DEFINER=`root`@`localhost` + SQL SECURITY DEFINER + VIEW `vn`.`expeditionTruck` +AS SELECT `rs`.`id` AS `id`, + `rs`.`roadmapFk` AS `roadmapFk`, + `rs`.`eta` AS `eta`, + `rs`.`description` AS `description`, + `rs`.`bufferFk` AS `bufferFk`, + `rs`.`created` AS `created`, + `rs`.`userFk` AS `userFk` +FROM `vn`.`roadmapStop` `rs`; diff --git a/db/routines/vn/views/saleCost.sql b/db/routines/vn/views/saleCost.sql index 27265aa93..304b9e3a3 100644 --- a/db/routines/vn/views/saleCost.sql +++ b/db/routines/vn/views/saleCost.sql @@ -19,4 +19,4 @@ FROM ( ) JOIN `vn`.`componentType` `ct` ON(`ct`.`id` = `c`.`typeFk`) ) -WHERE `ct`.`type` = 'coste' +WHERE `ct`.`code` = 'cost' diff --git a/db/routines/vn/views/sale_freightComponent.sql b/db/routines/vn/views/sale_freightComponent.sql index 7a329e0ee..269a8cca1 100644 --- a/db/routines/vn/views/sale_freightComponent.sql +++ b/db/routines/vn/views/sale_freightComponent.sql @@ -16,6 +16,6 @@ FROM ( ) JOIN `vn`.`componentType` `ct` ON( `ct`.`id` = `c`.`typeFk` - AND `ct`.`type` = 'agencia' + AND `ct`.`code` = 'freight' ) ) diff --git a/db/routines/vn2008/views/Tipos.sql b/db/routines/vn2008/views/Tipos.sql index 4cde954f1..5b96c1766 100644 --- a/db/routines/vn2008/views/Tipos.sql +++ b/db/routines/vn2008/views/Tipos.sql @@ -9,14 +9,9 @@ AS SELECT `it`.`id` AS `tipo_id`, `it`.`workerFk` AS `Id_Trabajador`, `it`.`life` AS `life`, `it`.`isPackaging` AS `isPackaging`, - `it`.`density` AS `density`, `it`.`isInventory` AS `inventory`, `it`.`created` AS `odbc_date`, `it`.`making` AS `confeccion`, `it`.`temperatureFk` AS `Temperatura`, - `it`.`promo` AS `promo`, - `it`.`maneuver` AS `maneuver`, - `it`.`target` AS `target`, - `it`.`topMargin` AS `top_margin`, - `it`.`profit` AS `profit` + `it`.`promo` AS `promo` FROM `vn`.`itemType` `it` diff --git a/db/routines/vn2008/views/buySource.sql b/db/routines/vn2008/views/buySource.sql index 33226a1dc..850483833 100644 --- a/db/routines/vn2008/views/buySource.sql +++ b/db/routines/vn2008/views/buySource.sql @@ -54,8 +54,7 @@ AS SELECT `b`.`entryFk` AS `Id_Entrada`, `i`.`packingOut` AS `packingOut`, `b`.`itemOriginalFk` AS `itemOriginalFk`, `io`.`longName` AS `itemOriginalName`, - `it`.`gramsMax` AS `gramsMax`, - `i`.`minQuantity` AS `minQuantity` + `it`.`gramsMax` AS `gramsMax` FROM ( ( ( diff --git a/db/routines/vn2008/views/buy_edi.sql b/db/routines/vn2008/views/buy_edi.sql index 0d194c89e..d00196e95 100644 --- a/db/routines/vn2008/views/buy_edi.sql +++ b/db/routines/vn2008/views/buy_edi.sql @@ -2,7 +2,6 @@ CREATE OR REPLACE DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `vn2008`.`buy_edi` AS SELECT `t`.`id` AS `id`, - `t`.`barcode` AS `barcode`, `t`.`entryYear` AS `entry_year`, `t`.`deliveryNumber` AS `delivery_number`, `t`.`fec` AS `fec`, diff --git a/db/versions/10852-pinkOak/00-firstScript.sql b/db/versions/10852-pinkOak/00-firstScript.sql new file mode 100644 index 000000000..41b75c7e1 --- /dev/null +++ b/db/versions/10852-pinkOak/00-firstScript.sql @@ -0,0 +1,32 @@ +ALTER TABLE vn.itemShelvingSale DROP COLUMN IF EXISTS isPicked; + +ALTER TABLE vn.itemShelvingSale + ADD isPicked TINYINT(1) DEFAULT FALSE NOT NULL; + +UPDATE vn.itemShelvingSale SET isPicked = TRUE; + +ALTER TABLE vn.productionConfig DROP COLUMN IF EXISTS orderMode; + +ALTER TABLE vn.productionConfig + ADD orderMode ENUM('Location', 'Age') NOT NULL DEFAULT 'Location'; + +ALTER TABLE vn.itemShelving DROP COLUMN IF EXISTS available; + +ALTER TABLE vn.itemShelving ADD available INT NULL; + +UPDATE vn.itemShelving SET available = visible; + +CREATE TABLE vn.itemShelvingSaleReserve ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `saleFk` int(11) NOT NULL, + PRIMARY KEY (`id`), + KEY `itemShelvingSaleReserve_ibfk_1` (`saleFk`) +) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci + COMMENT='Queue of changed itemShelvingSale to reserve'; + +INSERT INTO `salix`.`ACL` (model, property, accessType, permission, principalType, principalId) + VALUES + + ('Collection', 'assignCollection', 'WRITE', 'ALLOW', 'ROLE', 'production'); + +ALTER TABLE vn.operator ADD IF NOT EXISTS isOnReservationMode TINYINT(1) NOT NULL DEFAULT FALSE; \ No newline at end of file diff --git a/db/versions/10960-silverRoebelini/00-firstScript.sql b/db/versions/10960-silverRoebelini/00-firstScript.sql new file mode 100644 index 000000000..c53a09549 --- /dev/null +++ b/db/versions/10960-silverRoebelini/00-firstScript.sql @@ -0,0 +1,23 @@ +-- Place your SQL code here +CREATE TABLE IF NOT EXISTS `vn`.`agencyIncoming` ( + `agencyModeFk` int(11) NOT NULL, + PRIMARY KEY (`agencyModeFk`) +) +ENGINE=InnoDB +DEFAULT CHARSET=utf8mb3 +COLLATE=utf8mb3_unicode_ci COMMENT='Agencias de entrada de mercancias'; + +INSERT IGNORE INTO vn.agencyIncoming (agencyModeFk) VALUES +(1343), (1002), (1282), (841), (1303), (714), (556), (1786), (1785), (1784), +(1780), (1783), (1758), (1782), (1772), (1789), (1776), (1791), (1778), (1792), +(1779), (1362), (681), (1765), (15), (1594), (1706), (1707), (907), (1260), +(1715), (1371), (1372), (53), (689), (1375), (738), (742), (1307), (1700), (608), +(1311), (1315), (1339), (1433), (1338), (1332), (1844), (842), (1382), (1466), +(1719), (1723), (1725), (1720), (1732), (1736), (1728), (1724), (1726), (1727), +(1767), (1734), (1730), (1845), (1729), (1746), (1699), (2), (671), (1379), (614), +(1718), (1697), (62), (1529), (1392), (1378), (1438), (1796), (1688), (686), +(1326), (1691), (1), (1560), (1695), (1696), (1558), (1648), (1649), (1598), +(1680), (1694), (1600), (1601), (1602), (1712), (1603), (1604), (1641), (1692), +(1693), (1650), (1683), (1682), (1681), (1713), (1826), (1768), (1769), (1770), +(1593), (1443), (1244), (1679), (1006), (1361), (1102), (1655), (1744), (1225), +(1007); diff --git a/db/versions/10983-chocolateDracena/00-firstScript.sql b/db/versions/10983-chocolateDracena/00-firstScript.sql new file mode 100644 index 000000000..2baf1b21f --- /dev/null +++ b/db/versions/10983-chocolateDracena/00-firstScript.sql @@ -0,0 +1,5 @@ +-- Place your SQL code here +USE vn; + +DROP TRIGGER IF EXISTS itemShelving_AFTER_UPDATE; +DROP TRIGGER IF EXISTS itemShelving_AFTER_INSERT; diff --git a/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql new file mode 100644 index 000000000..288785191 --- /dev/null +++ b/db/versions/10986-pinkChrysanthemum/00-addSummaryId.sql @@ -0,0 +1,22 @@ +ALTER TABLE vn.claimLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.clientLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.deviceProductionLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.entryLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.invoiceInLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.itemLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.packingSiteDeviceLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.parkingLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.rateLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.routeLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.shelvingLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.supplierLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.ticketLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.travelLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.userLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.workerLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE vn.zoneLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); + +ALTER TABLE account.userLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.signInLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.roleLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); +ALTER TABLE account.accountLog ADD COLUMN IF NOT EXISTS summaryId varchar(30); \ No newline at end of file diff --git a/db/versions/11073-crimsonBirch/00-firstScript.sql b/db/versions/11073-crimsonBirch/00-firstScript.sql new file mode 100644 index 000000000..e82d342c9 --- /dev/null +++ b/db/versions/11073-crimsonBirch/00-firstScript.sql @@ -0,0 +1,9 @@ +-- 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 salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('TrainingCourse','*','*','ALLOW','ROLE','hr'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('TrainingCourseType','*','*','ALLOW','ROLE','hr'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('TrainingCenter','*','*','ALLOW','ROLE','hr'); +INSERT INTO salix.ACL (model,property,accessType,permission,principalType,principalId) + VALUES ('Worker','__get__trainingCourse','*','ALLOW','ROLE','hr'); diff --git a/db/versions/11081-wheatRaphis/00-firstScript.sql b/db/versions/11081-wheatRaphis/00-firstScript.sql new file mode 100644 index 000000000..70bbaabdb --- /dev/null +++ b/db/versions/11081-wheatRaphis/00-firstScript.sql @@ -0,0 +1,8 @@ +-- Place your SQL code here + +USE vn; + +ALTER TABLE vn.roadmap ADD kmStart mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD kmEnd mediumint(9) DEFAULT NULL NULL; +ALTER TABLE vn.roadmap ADD started DATETIME NULL; +ALTER TABLE vn.roadmap ADD finished DATETIME NULL; diff --git a/db/versions/11086-grayCataractarum/00-firstScript.sql b/db/versions/11086-grayCataractarum/00-firstScript.sql new file mode 100644 index 000000000..86107b159 --- /dev/null +++ b/db/versions/11086-grayCataractarum/00-firstScript.sql @@ -0,0 +1,12 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS notified TIMESTAMP NULL +COMMENT 'Date when it was notified that the web service deadline was exceeded'; + +INSERT IGNORE INTO util.notification + SET name = 'mrw-deadline', + description = 'The MRW deadline has passed'; + +INSERT IGNORE INTO util.notificationAcl (notificationFk, roleFK) + SELECT LAST_INSERT_ID(), r.id + FROM account.role r + WHERE r.name = 'delivery' \ No newline at end of file diff --git a/db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql b/db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql new file mode 100644 index 000000000..473441a7e --- /dev/null +++ b/db/versions/11100-silverGerbera/00-modifyTimeControlAcls.sql @@ -0,0 +1,18 @@ +UPDATE salix.ACL + SET principalId = 'teamBoss' + WHERE property IN ('addTimeEntry', 'deleteTimeEntry', 'updateTimeEntry', 'weeklyHourRecordEmail'); + +UPDATE salix.ACL SET principalId = 'developer' WHERE property = 'sendMail'; + +UPDATE salix.ACL + SET property = 'updateMailState' + WHERE property = 'updateWorkerTimeControlMail'; + +INSERT INTO salix.ACL(model, property, accessType, permission, principalType, principalId) + VALUES + ('WorkerTimeControl', 'addTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'deleteTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'updateTimeEntry', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'weeklyHourRecordEmail', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'sendMail', 'WRITE', 'ALLOW', 'ROLE', 'hr'), + ('WorkerTimeControl', 'updateMailState', 'WRITE', 'ALLOW', 'ROLE', 'hr'); \ No newline at end of file diff --git a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql index 6c8bb4784..3abcd0074 100644 --- a/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql +++ b/db/versions/11102-wheatCarnation/00-createTravelKgPercentage.sql @@ -3,7 +3,7 @@ CREATE TABLE IF NOT EXISTS vn.travelKgPercentage ( className VARCHAR(50) ); -INSERT INTO vn.travelKgPercentage (value, className) +INSERT IGNORE INTO vn.travelKgPercentage (value, className) VALUES (80, 'primary'), (100, 'alert'); diff --git a/db/versions/11103-limeBirch/00-firstScript.sql b/db/versions/11103-limeBirch/00-firstScript.sql new file mode 100644 index 000000000..2c0a396ce --- /dev/null +++ b/db/versions/11103-limeBirch/00-firstScript.sql @@ -0,0 +1,6 @@ +-- Place your SQL code here +INSERT INTO salix.ACL (model, property, accessType, permission, principalType, principalId) + VALUES + ('WorkerIncome', '*', '*', 'ALLOW', 'ROLE', 'hr'), + ('PayrollComponent', '*', '*', 'ALLOW', 'ROLE', 'hr'), + ('Worker', '__get__incomes', '*', 'ALLOW', 'ROLE', 'hr'); diff --git a/db/versions/11111-tealAralia/00-firstScript.sql b/db/versions/11111-tealAralia/00-firstScript.sql new file mode 100644 index 000000000..4ef10d5f2 --- /dev/null +++ b/db/versions/11111-tealAralia/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE account.`user` DROP COLUMN password__; diff --git a/db/versions/11116-tealRuscus/00-firstScript.sql b/db/versions/11116-tealRuscus/00-firstScript.sql new file mode 100644 index 000000000..dc577a36b --- /dev/null +++ b/db/versions/11116-tealRuscus/00-firstScript.sql @@ -0,0 +1,8 @@ +-- Place your SQL code here +USE vn; +INSERT INTO salix.ACL ( model, property, accessType, permission, principalType, principalId) VALUES('ItemShelvingLog', '*', 'READ', 'ALLOW', 'ROLE', 'production'); + +-- redmine regularitzar parking per a que no tinguen espais +ALTER TABLE parking DROP CONSTRAINT chkParkingCodeFormat; +ALTER TABLE parking +ADD CONSTRAINT chkParkingCodeFormat CHECK (CHAR_LENGTH(code) > 4 AND code REGEXP ('^[^ ]+-[^ ]+$')); \ No newline at end of file diff --git a/db/versions/11117-blueGalax/00-firstScript.sql b/db/versions/11117-blueGalax/00-firstScript.sql new file mode 100644 index 000000000..63ea40cd2 --- /dev/null +++ b/db/versions/11117-blueGalax/00-firstScript.sql @@ -0,0 +1,2 @@ +-- Place your SQL code here +ALTER TABLE vn.routesMonitor DROP COLUMN expeditionTruckFk; \ No newline at end of file diff --git a/db/versions/11118-limeCymbidium/00-firstScript.sql b/db/versions/11118-limeCymbidium/00-firstScript.sql new file mode 100644 index 000000000..3921a8a13 --- /dev/null +++ b/db/versions/11118-limeCymbidium/00-firstScript.sql @@ -0,0 +1,21 @@ + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','filter','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','getBuys','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO salix.ACL (`model`,`property`,`accessType`,`permission`,`principalType`,`principalId`) + VALUES ('Entry','buyLabel','READ','ALLOW','ROLE','supplier'); + +INSERT IGNORE INTO `account`.`role` (`name`,`description`,`hasLogin`,`created`,`modified`) + VALUES ('supplier','Proveedores',1,'2017-10-10 14:58:58.000','2017-10-10 14:59:20.000'); +SET @supplierFk =LAST_INSERT_ID(); +INSERT IGNORE INTO account.roleInherit (`role`,`inheritsFrom`) + VALUES (@supplierFk,2); + +UPDATE salix.ACL + SET principalId='$authenticated' + WHERE id=264; + + diff --git a/db/versions/11119-tealGerbera/00-firstScript.sql b/db/versions/11119-tealGerbera/00-firstScript.sql new file mode 100644 index 000000000..40b3b0424 --- /dev/null +++ b/db/versions/11119-tealGerbera/00-firstScript.sql @@ -0,0 +1,9 @@ +ALTER TABLE vn.componentType + CHANGE code code varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT NULL NULL AFTER id; +ALTER TABLE vn.componentType + CHANGE `type` name varchar(45) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL; +UPDATE IGNORE vn.componentType + SET code = LOWER(code); +UPDATE IGNORE vn.componentType + SET code = 'other' + WHERE id = 12; \ No newline at end of file diff --git a/db/versions/11120-brownTulip/00-firstScript.sql b/db/versions/11120-brownTulip/00-firstScript.sql new file mode 100644 index 000000000..c4ded80bb --- /dev/null +++ b/db/versions/11120-brownTulip/00-firstScript.sql @@ -0,0 +1,6 @@ +ALTER TABLE vn.itemType + CHANGE maneuver maneuver__ double DEFAULT 0.21 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE target target__ double DEFAULT 0.15 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE topMargin topMargin__ double DEFAULT 0.3 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE profit profit__ double DEFAULT 0.02 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418', + CHANGE density density__ double DEFAULT 167 NOT NULL COMMENT '@deprecated 2024-07-01 refs #7418 Almacena el valor por defecto de la densidad en kg/m3 para el calculo de los portes aereos, en articulos se guarda la correcta'; \ No newline at end of file diff --git a/db/versions/11121-silverAralia/00-firstScript.sql b/db/versions/11121-silverAralia/00-firstScript.sql new file mode 100644 index 000000000..20b0e8195 --- /dev/null +++ b/db/versions/11121-silverAralia/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE account.mailAliasAccount + ADD editorFk INT(10) UNSIGNED DEFAULT NULL, + ADD CONSTRAINT mailAliasAccount_editorFk FOREIGN KEY (editorFk) + REFERENCES account.`user`(id); \ No newline at end of file diff --git a/db/versions/11126-blueCamellia/00-firstScript.sql b/db/versions/11126-blueCamellia/00-firstScript.sql new file mode 100644 index 000000000..40c5e2b37 --- /dev/null +++ b/db/versions/11126-blueCamellia/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE `vn`.`client` +ADD COLUMN `hasDailyInvoice` TINYINT(1) NOT NULL DEFAULT 0 COMMENT 'Indica si el cliente requiere facturación diaria por defecto se copiará lo que tenga country.hasDailyInvoice'; diff --git a/db/versions/11128-turquoiseCymbidium/00-firstScript.sql b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql new file mode 100644 index 000000000..4f6cafcf8 --- /dev/null +++ b/db/versions/11128-turquoiseCymbidium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.calendar ADD created timestamp DEFAULT current_timestamp() NOT NULL AFTER dated; diff --git a/db/versions/11129-limeHydrangea/00-firstScript.sql b/db/versions/11129-limeHydrangea/00-firstScript.sql new file mode 100644 index 000000000..eb2320ee1 --- /dev/null +++ b/db/versions/11129-limeHydrangea/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.greuge CHANGE Id id int(10) unsigned auto_increment NOT NULL; diff --git a/db/versions/11130-crimsonIvy/00-firstScript.sql b/db/versions/11130-crimsonIvy/00-firstScript.sql new file mode 100644 index 000000000..c93f2f6b7 --- /dev/null +++ b/db/versions/11130-crimsonIvy/00-firstScript.sql @@ -0,0 +1,23 @@ +ALTER TABLE vn.productionConfig + ADD editorFk int(10) unsigned DEFAULT NULL NULL; +ALTER TABLE vn.productionConfig + ADD CONSTRAINT productionConfig_user_FK FOREIGN KEY (editorFk) REFERENCES account.`user`(id); + +CREATE OR REPLACE TABLE `vn`.`productionConfigLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(11) DEFAULT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete','select') NOT NULL, + `creationDate` timestamp NULL DEFAULT current_timestamp(), + `description` text CHARACTER SET utf8mb3 COLLATE utf8mb3_general_ci DEFAULT NULL, + `changedModel` enum('ProductionConfig') NOT NULL DEFAULT 'ProductionConfig', + `oldInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`oldInstance`)), + `newInstance` longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL CHECK (json_valid(`newInstance`)), + `changedModelId` int(11) NOT NULL, + `changedModelValue` varchar(45) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `productionConfigLog_userFk` (`userFk`), + KEY `productionConfigLog_changedModel` (`changedModel`,`changedModelId`,`creationDate`), + KEY `productionConfigLog_originFk` (`originFk`,`creationDate`), + CONSTRAINT `productionConfigUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; diff --git a/db/versions/11131-brownPhormium/00-firstScript.sql b/db/versions/11131-brownPhormium/00-firstScript.sql new file mode 100644 index 000000000..341c9f1a3 --- /dev/null +++ b/db/versions/11131-brownPhormium/00-firstScript.sql @@ -0,0 +1 @@ +ALTER TABLE vn.itemShelving ADD isSplit tinyint(1) NULL COMMENT 'Este valor cambia al splitar un carro que se ha quedado en holanda'; \ No newline at end of file diff --git a/db/versions/11132-aquaDracena/00-firstScript.vn.sql b/db/versions/11132-aquaDracena/00-firstScript.vn.sql new file mode 100644 index 000000000..64f8442b4 --- /dev/null +++ b/db/versions/11132-aquaDracena/00-firstScript.vn.sql @@ -0,0 +1,2 @@ +INSERT IGNORE INTO vn.observationType (`description`,code) + VALUES ('Sustitución','substitution'); diff --git a/db/versions/11134-silverRaphis/00-firstScript.sql b/db/versions/11134-silverRaphis/00-firstScript.sql new file mode 100644 index 000000000..0836abe4e --- /dev/null +++ b/db/versions/11134-silverRaphis/00-firstScript.sql @@ -0,0 +1,42 @@ +USE `vn`; + +CREATE TABLE IF NOT EXISTS vn.`tillSerial` ( + `code` varchar(2) COLLATE utf8mb3_unicode_ci NOT NULL, + `description` varchar(30) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + `account` varchar(10) COLLATE utf8mb3_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES(' S', 'Saldos final / inicial', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('A', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('B', 'Factura cliente', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('C', 'Facturas Contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CC', 'Cuadre caja', '6780000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CD', 'Cuenta Director Comercial', '5510000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CH', 'Cheques', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CM', 'Cambio', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CR', 'Ingreso/Reintegro Caja Rural', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('CT', 'Correos y telégrafos', '6290000005'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DC', 'Dietas conductores', '6290000010'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DH', 'Deudas Holland', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('DT', 'Dietas', '6290000011'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('E', 'Entrada mercancia', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('EN', 'Enric Martinez', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GC', 'Cuenta con dto. Comercial', '5510000003'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GP', 'Gastos de personal', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GR', 'Gastos RRPP dpto comercial', '6290001002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GS', 'Gasoil', '6280000002'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('GV', 'Gastos viaje', '6290001000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('JV', 'Juanvi', '6290000553'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MB', 'Movimiento bancario', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('MP', 'Materias Primas', '6000000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('OG', 'Otros gastos', '6290000000'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('PM', 'Pequeño material', '6290000007'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('R', 'Factura proveedor', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RC', 'Ingreso/Reintegro Ruralcaja', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('RN', 'Reparación nave', '6220000004'); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('SS', 'Gastos Silla', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('T', 'Ticket', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TA', 'Factura rapida', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TC', 'Ticket contado', NULL); +INSERT IGNORE vn.tillSerial (code, `description`, account) VALUES('TR', 'Traspaso', NULL); \ No newline at end of file diff --git a/db/versions/11135-whiteErica/00-firstScript.sql b/db/versions/11135-whiteErica/00-firstScript.sql new file mode 100644 index 000000000..902608a3e --- /dev/null +++ b/db/versions/11135-whiteErica/00-firstScript.sql @@ -0,0 +1 @@ +CREATE INDEX travel_landed_IDX USING BTREE ON vn.travel (landed DESC,warehouseInFk,warehouseOutFk); diff --git a/db/versions/11136-maroonMedeola/00-firstScript.sql b/db/versions/11136-maroonMedeola/00-firstScript.sql new file mode 100644 index 000000000..b0b92c7e9 --- /dev/null +++ b/db/versions/11136-maroonMedeola/00-firstScript.sql @@ -0,0 +1,6 @@ +RENAME TABLE vn.addressShortage TO vn.addressWaste; +ALTER TABLE vn.addressWaste ADD `type` ENUM('internal', 'external') NOT NULL; +INSERT IGNORE INTO vn.addressWaste (addressFk,`type`) VALUES + (2230,'external'), + (5986,'external'), + (7475,'external'); diff --git a/db/versions/11137-salmonRoebelini/00-firstScript.sql b/db/versions/11137-salmonRoebelini/00-firstScript.sql new file mode 100644 index 000000000..69d20ac6d --- /dev/null +++ b/db/versions/11137-salmonRoebelini/00-firstScript.sql @@ -0,0 +1,4 @@ +ALTER TABLE vn.expeditionState + MODIFY COLUMN userFk INT(10) UNSIGNED, + ADD CONSTRAINT expeditionState_userFk FOREIGN KEY (userFk) + REFERENCES account.`user`(id); \ No newline at end of file diff --git a/db/versions/11138-aquaGalax/00-firstScript.sql b/db/versions/11138-aquaGalax/00-firstScript.sql new file mode 100644 index 000000000..d492e6470 --- /dev/null +++ b/db/versions/11138-aquaGalax/00-firstScript.sql @@ -0,0 +1,8 @@ +ALTER TABLE `vn`.`claimDestination` +ADD COLUMN `code` varchar(45) DEFAULT NULL; + +UPDATE IGNORE vn.claimDestination SET code='Good' WHERE description= 'Bueno'; +UPDATE IGNORE vn.claimDestination SET code='Garbage/Loss' WHERE description = 'Basura/Perd.'; +UPDATE IGNORE vn.claimDestination SET code='Manufacturing' WHERE description = 'Confeccion'; +UPDATE IGNORE vn.claimDestination SET code='Claim' WHERE description = 'Reclam.PRAG'; +UPDATE IGNORE vn.claimDestination SET code='Corrected' WHERE description = 'Corregido'; \ No newline at end of file diff --git a/db/versions/11139-bronzeCataractarum/00-firstScript.sql b/db/versions/11139-bronzeCataractarum/00-firstScript.sql new file mode 100644 index 000000000..2816fab86 --- /dev/null +++ b/db/versions/11139-bronzeCataractarum/00-firstScript.sql @@ -0,0 +1,6 @@ +-- Place your SQL code here +ALTER TABLE vn.mrwConfig ADD IF NOT EXISTS clientTypeWidth int(10) unsigned NULL + COMMENT 'If it does not reach the required value, it will be padded with zeros on the left to meet the specified length.'; + +UPDATE vn.mrwConfig + SET clientTypeWidth = 6; \ No newline at end of file diff --git a/db/versions/11140-azurePhormium/00-firstScript.sql b/db/versions/11140-azurePhormium/00-firstScript.sql new file mode 100644 index 000000000..7c89110bb --- /dev/null +++ b/db/versions/11140-azurePhormium/00-firstScript.sql @@ -0,0 +1,3 @@ +ALTER TABLE vn.vehicle DROP FOREIGN KEY provinceFk; +ALTER TABLE vn.vehicle + ADD CONSTRAINT vehicle_warehouse_FK FOREIGN KEY (warehouseFk) REFERENCES vn.warehouse(id) ON DELETE RESTRICT ON UPDATE CASCADE; diff --git a/db/versions/11145-pinkLaurel/00-firstScript.sql b/db/versions/11145-pinkLaurel/00-firstScript.sql new file mode 100644 index 000000000..ba1946d3b --- /dev/null +++ b/db/versions/11145-pinkLaurel/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.payrollWorker CHANGE grupotarifa__ grupotarifa int(10) NOT NULL; +ALTER TABLE vn.payrollWorker MODIFY COLUMN grupotarifa int(10) NOT NULL; \ No newline at end of file diff --git a/db/versions/11146-maroonCordyline/00-firstScript.sql b/db/versions/11146-maroonCordyline/00-firstScript.sql new file mode 100644 index 000000000..1b41422f0 --- /dev/null +++ b/db/versions/11146-maroonCordyline/00-firstScript.sql @@ -0,0 +1,11 @@ +RENAME TABLE hedera.shelfConfig TO hedera.shelfMultiConfig ; +RENAME TABLE pbx.queueConfig TO pbx.queueMultiConfig ; +RENAME TABLE salix.defaultViewConfig TO salix.defaultViewMultiConfig; +RENAME TABLE edi.fileConfig TO edi.fileMultiConfig; +RENAME TABLE edi.imapConfig TO edi.imapMultiConfig; +RENAME TABLE edi.tableConfig TO edi.tableMultiConfig; +RENAME TABLE vn.invoiceOutTaxConfig TO vn.invoiceOutTaxMultiConfig; +RENAME TABLE vn.userConfig TO vn.userMultiConfig; +RENAME TABLE vn.conveyorConfig TO vn.conveyorMultiConfig; + +GRANT SELECT ON TABLE hedera.shelfMultiConfig TO employee; diff --git a/db/versions/11149-silverSalal/00-firstScript.sql b/db/versions/11149-silverSalal/00-firstScript.sql new file mode 100644 index 000000000..e642dd2e4 --- /dev/null +++ b/db/versions/11149-silverSalal/00-firstScript.sql @@ -0,0 +1,30 @@ +ALTER TABLE vn.item CHANGE minQuantity minQuantity__ int(10) unsigned DEFAULT + NULL NULL COMMENT '@deprecated 2024-07-11 refs #7704 Cantidad mínima para una línea de venta'; + +CREATE TABLE `vn`.`itemMinimumQuantity` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `itemFk` int(10) NOT NULL, + `quantity` int(10) NOT NULL, + `started` date NOT NULL, + `ended` date DEFAULT NULL, + `warehouseFk` smallint(5) unsigned DEFAULT NULL, + `created` timestamp NOT NULL DEFAULT current_timestamp(), + `editorFk` int(10) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `itemMinimumQuantity_UNIQUE` (`itemFk`, `started`, `ended`, `warehouseFk`), + KEY `itemFk` (`itemFk`), + KEY `started` (`started`), + KEY `ended` (`ended`), + KEY `warehouseFk` (`warehouseFk`), + KEY `editorFk` (`editorFk`), + CONSTRAINT `itemMinimumQuantity_ibfk_1` FOREIGN KEY (`itemFk`) REFERENCES `item` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `itemMinimumQuantity_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `itemMinimumQuantity_ibfk_3` FOREIGN KEY (`editorFk`) REFERENCES `account`.`user` (`id`), + CONSTRAINT `itemMinimumQuantity_check_1` CHECK (`started` <= `ended`) +) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8mb3 COLLATE=utf8mb3_unicode_ci; + +GRANT SELECT, UPDATE, DELETE, INSERT ON TABLE vn.itemMinimumQuantity TO buyer; +GRANT EXECUTE ON PROCEDURE vn.ticketCalculatePurge TO guest; + +ALTER TABLE vn.itemLog MODIFY COLUMN changedModel enum('Item','ItemBarcode','ItemBotanical','ItemNiche','ItemTag','ItemTaxCountry','ItemMinimumQuantity') + CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci DEFAULT 'Item' NOT NULL; diff --git a/db/versions/11150-bronzeEucalyptus/00-firstScript.sql b/db/versions/11150-bronzeEucalyptus/00-firstScript.sql new file mode 100644 index 000000000..c9a619618 --- /dev/null +++ b/db/versions/11150-bronzeEucalyptus/00-firstScript.sql @@ -0,0 +1,2 @@ +ALTER TABLE vn.itemMinimumQuantity + ADD CONSTRAINT itemMinimumQuantity_check CHECK (quantity > 0); diff --git a/db/versions/11154-greenBamboo/00-firstScript.sql b/db/versions/11154-greenBamboo/00-firstScript.sql new file mode 100644 index 000000000..72a9389ec --- /dev/null +++ b/db/versions/11154-greenBamboo/00-firstScript.sql @@ -0,0 +1,2 @@ + +ALTER TABLE vn.ticketLastState MODIFY COLUMN name varchar(20) CHARACTER SET utf8mb3 COLLATE utf8mb3_unicode_ci NOT NULL; \ No newline at end of file diff --git a/db/versions/11154-greenBamboo/00-firstScript.vn.sql b/db/versions/11154-greenBamboo/00-firstScript.vn.sql new file mode 100644 index 000000000..374c9a031 --- /dev/null +++ b/db/versions/11154-greenBamboo/00-firstScript.vn.sql @@ -0,0 +1,2 @@ + +INSERT INTO vn.state ( name, `order`, alertLevel, code, sectorProdPriority, nextStateFk, isPreviousPreparable, isPicked, isPreparable, semaphore, isPrintable, isOK, graphCategory, isNotValidated, classColor) VALUES('Entregado en parte', 13, 3, 'PARTIAL_DELIVERED', NULL, 16, 0, 1, 0, 0, 0, 0, 0, 0, NULL); \ No newline at end of file diff --git a/db/versions/11156-tealCordyline/00-firstScript.sql b/db/versions/11156-tealCordyline/00-firstScript.sql new file mode 100644 index 000000000..18c004b03 --- /dev/null +++ b/db/versions/11156-tealCordyline/00-firstScript.sql @@ -0,0 +1,8 @@ +ALTER TABLE vn.item ADD IF NOT EXISTS tag11 varchar(20) DEFAULT NULL NULL; +ALTER TABLE vn.item ADD IF NOT EXISTS value11 varchar(50) DEFAULT NULL NULL; + +ALTER TABLE vn.item ADD IF NOT EXISTS tag12 varchar(20) DEFAULT NULL NULL; +ALTER TABLE vn.item ADD IF NOT EXISTS value12 varchar(50) DEFAULT NULL NULL; + +ALTER TABLE vn.item ADD IF NOT EXISTS tag13 varchar(20) DEFAULT NULL NULL; +ALTER TABLE vn.item ADD IF NOT EXISTS value13 varchar(50) DEFAULT NULL NULL; \ No newline at end of file diff --git a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js index 5c8eba571..ad0975889 100644 --- a/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js +++ b/e2e/paths/05-ticket/01-sale/01_list_sales.spec.js @@ -57,7 +57,7 @@ describe('Ticket List sale path', () => { let searchValue = 'Melee weapon heavy shield 100cm'; await page.autocompleteSearch(selectors.ticketSales.secondSaleIdAutocomplete, searchValue); await page.waitToClick(selectors.ticketSales.secondSaleQuantityCell); - await page.type(selectors.ticketSales.secondSaleQuantity, '1'); + await page.type(selectors.ticketSales.secondSaleQuantity, '8'); await page.keyboard.press('Enter'); const message = await page.waitForSnackbar(); diff --git a/front/salix/components/bank-entity/index.html b/front/salix/components/bank-entity/index.html index 6ce073f1a..915294671 100644 --- a/front/salix/components/bank-entity/index.html +++ b/front/salix/components/bank-entity/index.html @@ -27,7 +27,7 @@ vn-id="country" ng-model="$ctrl.data.countryFk" url="Countries" - fields="['id', 'country', 'code']" + fields="['id', 'name', 'code']" show-field="name" value-field="id" label="Country"> diff --git a/loopback/common/methods/application/spec/execute.spec.js b/loopback/common/methods/application/spec/execute.spec.js index 1a0a8ace9..ca4efd9cc 100644 --- a/loopback/common/methods/application/spec/execute.spec.js +++ b/loopback/common/methods/application/spec/execute.spec.js @@ -2,18 +2,9 @@ const models = require('vn-loopback/server/server').models; describe('Application execute()/executeProc()/executeFunc()', () => { const userWithoutPrivileges = 1; - const userWithPrivileges = 9; const userWithInheritedPrivileges = 120; let tx; - - function getCtx(userId) { - return { - req: { - accessToken: {userId}, - headers: {origin: 'http://localhost'} - } - }; - } + const ctx = beforeAll.getCtx(); beforeEach(async() => { tx = await models.Application.beginTransaction({}); @@ -42,7 +33,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should throw error when execute procedure and not have privileges', async() => { - const ctx = getCtx(userWithoutPrivileges); + const ctx = {req: {accessToken: {userId: userWithoutPrivileges}}}; let error; try { @@ -66,7 +57,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should execute procedure and get data', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -90,7 +80,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { describe('Application executeProc()', () => { it('should execute procedure and get data (executeProc)', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -115,7 +104,6 @@ describe('Application execute()/executeProc()/executeFunc()', () => { describe('Application executeFunc()', () => { it('should execute function and get data', async() => { - const ctx = getCtx(userWithPrivileges); try { const options = {transaction: tx}; @@ -137,7 +125,7 @@ describe('Application execute()/executeProc()/executeFunc()', () => { }); it('should execute function and get data with user with inherited privileges', async() => { - const ctx = getCtx(userWithInheritedPrivileges); + const ctx = {req: {accessToken: {userId: userWithInheritedPrivileges}}}; try { const options = {transaction: tx}; diff --git a/loopback/common/methods/schema/model-info.js b/loopback/common/methods/schema/model-info.js index 0648deb80..74d764475 100644 --- a/loopback/common/methods/schema/model-info.js +++ b/loopback/common/methods/schema/model-info.js @@ -92,6 +92,7 @@ module.exports = Self => { const locale = modelLocale && modelLocale.get(lang); json[modelName] = { + http: model.sharedClass.http.path, properties: model.definition.rawProperties, validations: jsonValidations, locale diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js index 56af72bd9..28b256ad8 100644 --- a/loopback/common/methods/vn-model/specs/crud.spec.js +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -1,20 +1,7 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('Model crud()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); let insertId; const barcodeModel = app.models.ItemBarcode; diff --git a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js index a3dba14d7..84c0784c9 100644 --- a/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js +++ b/loopback/common/methods/vn-model/specs/rewriteDbError.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Model rewriteDbError()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should extend rewriteDbError properties to any model passed', () => { const exampleModel = models.ItemTag; diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 1e5733442..382a2824c 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -234,4 +234,4 @@ "It has been invoiced but the PDF of refund not be generated": "It has been invoiced but the PDF of refund not be generated", "Cannot add holidays on this day": "Cannot add holidays on this day", "Cannot send mail": "Cannot send mail" -} +} \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index 5b5928993..e2be5d013 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -366,5 +366,6 @@ "It has been invoiced but the PDF could not be generated": "Se ha facturado pero no se ha podido generar el PDF", "It has been invoiced but the PDF of refund not be generated": "Se ha facturado pero no se ha podido generar el PDF del abono", "Payment method is required": "El método de pago es obligatorio", - "Cannot send mail": "Não é possível enviar o email" + "Cannot send mail": "Não é possível enviar o email", + "CONSTRAINT `supplierAccountTooShort` failed for `vn`.`supplier`": "La cuenta debe tener exactamente 10 dígitos" } diff --git a/loopback/server/middleware/error-handler.js b/loopback/server/middleware/error-handler.js index cc7b81618..beeff95ae 100644 --- a/loopback/server/middleware/error-handler.js +++ b/loopback/server/middleware/error-handler.js @@ -22,7 +22,7 @@ module.exports = function() { } // MySQL user-defined exceptions - if (err.sqlState == '45000') + if (err.sqlState == '45000' || err?.errno == 4025) return next(new UserError(req.__(err.sqlMessage))); // Logs error to console diff --git a/modules/account/back/models/mail-alias-account.json b/modules/account/back/models/mail-alias-account.json index 54e986ef7..46d4793e6 100644 --- a/modules/account/back/models/mail-alias-account.json +++ b/modules/account/back/models/mail-alias-account.json @@ -6,6 +6,9 @@ "table": "account.mailAliasAccount" } }, + "mixins": { + "Loggable": true + }, "properties": { "id": { "type": "number", diff --git a/modules/claim/back/methods/claim/specs/filter.spec.js b/modules/claim/back/methods/claim/specs/filter.spec.js index 872f49aa3..1ef808e9d 100644 --- a/modules/claim/back/methods/claim/specs/filter.spec.js +++ b/modules/claim/back/methods/claim/specs/filter.spec.js @@ -2,15 +2,7 @@ const app = require('vn-loopback/server/server'); const models = require('vn-loopback/server/server').models; describe('claim filter()', () => { - let ctx; - beforeEach(() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - } - }; - }); + const ctx = beforeAll.getCtx(); it('should return 1 result filtering by id', async() => { const tx = await app.models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 95c356374..55d76ed7a 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -1,18 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('claim regularizeClaim()', () => { const userId = 18; - const ctx = { - req: { - accessToken: {userId: userId}, - headers: {origin: 'http://localhost'} - } - }; + const ctx = beforeAll.mockLoopBackContext(userId); ctx.req.__ = (value, params) => { return params.nickname; }; - const chatModel = models.Chat; const claimId = 1; const ticketId = 1; @@ -40,20 +33,6 @@ describe('claim regularizeClaim()', () => { return await models.ClaimEnd.create(claimEnds, options); } - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { const tx = await models.Claim.beginTransaction({}); diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index b7725e7f8..e1eec59d1 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -1,22 +1,10 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); const i18n = require('i18n'); describe('Update Claim', () => { let url; let claimStatesMap = {}; + beforeAll.mockLoopBackContext(); beforeAll(async() => { - url = await app.models.Url.getUrl(); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); const claimStates = await app.models.ClaimState.find(); claimStatesMap = claimStates.reduce((acc, state) => ({...acc, [state.code]: state.id}), {}); }); diff --git a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js index 99436fed6..bc081ed08 100644 --- a/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaimAction.spec.js @@ -1,20 +1,7 @@ const app = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('Update Claim', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); const newDate = Date.vnNew(); const original = { ticketFk: 3, diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 10e6f7adf..c15c260bc 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -50,7 +50,7 @@ module.exports = function(Self) { { relation: 'country', scope: { - fields: ['id', 'country'] + fields: ['id', 'name'] } }, { diff --git a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js index 74d80b964..1a186f93c 100644 --- a/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js +++ b/modules/client/back/methods/client/specs/addressesPropagateRe.spec.js @@ -1,23 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Client addressesPropagateRe', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; + beforeAll.mockLoopBackContext(); - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); - - it('should propagate the isEqualizated on both addresses of Mr Wayne and set hasToInvoiceByAddress to false', async() => { + it('should propagate the isEqualizated on both addresses of Mr Wayne' + + ' and set hasToInvoiceByAddress to false', async() => { const tx = await models.Client.beginTransaction({}); try { diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index ae179cf6c..f4901ff93 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Address createAddress', () => { const clientFk = 1101; @@ -7,20 +6,7 @@ describe('Address createAddress', () => { const incotermsFk = 'FAS'; const customAgentOneId = 1; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should throw a non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 04fc51a26..5b1ff5da9 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -1,6 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - describe('Client Create', () => { const newAccount = { userName: 'deadpool', @@ -16,20 +14,7 @@ describe('Client Create', () => { const newAccountWithoutEmail = JSON.parse(JSON.stringify(newAccount)); delete newAccountWithoutEmail.email; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it(`should not find deadpool as he's not created yet`, async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/getCard.spec.js b/modules/client/back/methods/client/specs/getCard.spec.js index 962e0a2d4..49e5ed5a4 100644 --- a/modules/client/back/methods/client/specs/getCard.spec.js +++ b/modules/client/back/methods/client/specs/getCard.spec.js @@ -1,11 +1,11 @@ const models = require('vn-loopback/server/server').models; describe('Client getCard()', () => { + const ctx = beforeAll.getCtx(); it('should receive a formated card of Bruce Wayne', async() => { const tx = await models.Client.beginTransaction({}); try { - const ctx = {req: {accessToken: {userId: 9}}}; const options = {transaction: tx}; const id = 1101; diff --git a/modules/client/back/methods/client/specs/getDebt.spec.js b/modules/client/back/methods/client/specs/getDebt.spec.js index b3b5286c0..d89d671a3 100644 --- a/modules/client/back/methods/client/specs/getDebt.spec.js +++ b/modules/client/back/methods/client/specs/getDebt.spec.js @@ -1,9 +1,9 @@ const models = require('vn-loopback/server/server').models; describe('client getDebt()', () => { + const ctx = beforeAll.getCtx(); it('should return the client debt', async() => { const tx = await models.Client.beginTransaction({}); - const ctx = {req: {accessToken: {userId: 9}}}; try { const options = {transaction: tx}; diff --git a/modules/client/back/methods/client/specs/sendSms.spec.js b/modules/client/back/methods/client/specs/sendSms.spec.js index df680c55f..bba9f83ce 100644 --- a/modules/client/back/methods/client/specs/sendSms.spec.js +++ b/modules/client/back/methods/client/specs/sendSms.spec.js @@ -1,12 +1,12 @@ const models = require('vn-loopback/server/server').models; describe('client sendSms()', () => { + const ctx = beforeAll.getCtx(); it('should now send a message and log it', async() => { const tx = await models.Client.beginTransaction({}); try { const options = {transaction: tx}; - const ctx = {req: {accessToken: {userId: 9}}}; const id = 1101; const destination = 222222222; const message = 'this is the message created in a test'; diff --git a/modules/client/back/methods/client/specs/summary.spec.js b/modules/client/back/methods/client/specs/summary.spec.js index 227f4c398..fe2af8028 100644 --- a/modules/client/back/methods/client/specs/summary.spec.js +++ b/modules/client/back/methods/client/specs/summary.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('client summary()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should return a summary object containing data', async() => { const clientId = 1101; const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index 6f02323c5..68981f8b7 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -1,6 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); - describe('Address updateAddress', () => { const clientId = 1101; const addressId = 1; @@ -14,20 +12,7 @@ describe('Address updateAddress', () => { } }; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should throw the non uee member error if no incoterms is defined', async() => { const tx = await models.Client.beginTransaction({}); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 8de887b47..8162096f0 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -54,7 +54,7 @@ module.exports = Self => { { relation: 'country', scope: { - fields: ['country'] + fields: ['name'] } }, { diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 851648658..8ed55b856 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -99,6 +99,10 @@ module.exports = Self => { { arg: 'hasElectronicInvoice', type: 'boolean' + }, + { + arg: 'hasDailyInvoice', + type: 'boolean' } ], returns: { @@ -117,8 +121,6 @@ module.exports = Self => { const myOptions = {}; const models = Self.app.models; const args = ctx.args; - const userId = ctx.req.accessToken.userId; - const $t = ctx.req.__; if (typeof options == 'object') Object.assign(myOptions, options); diff --git a/modules/client/back/methods/defaulter/filter.js b/modules/client/back/methods/defaulter/filter.js index ac9504ec2..0bfa7659b 100644 --- a/modules/client/back/methods/defaulter/filter.js +++ b/modules/client/back/methods/defaulter/filter.js @@ -60,7 +60,7 @@ module.exports = Self => { DISTINCT c.id clientFk, c.name clientName, c.salesPersonFk, - c.businessTypeFk, + c.businessTypeFk = 'worker' isWorker, u.name salesPersonName, d.amount, co.created, @@ -71,14 +71,23 @@ module.exports = Self => { d.defaulterSinced, cn.name country, c.countryFk, - pm.name payMethod - FROM vn.defaulter d - JOIN vn.client c ON c.id = d.clientFk - JOIN vn.country cn ON cn.id = c.countryFk - JOIN vn.payMethod pm ON pm.id = c.payMethodFk - LEFT JOIN vn.clientObservation co ON co.clientFk = c.id + pm.name payMethod, + r.finished IS NULL hasRecovery, + dp.id departmentFk, + dp.name departmentName + FROM defaulter d + JOIN client c ON c.id = d.clientFk + JOIN country cn ON cn.id = c.countryFk + JOIN payMethod pm ON pm.id = c.payMethodFk + LEFT JOIN clientObservation co ON co.clientFk = c.id LEFT JOIN account.user u ON u.id = c.salesPersonFk LEFT JOIN account.user uw ON uw.id = co.workerFk + LEFT JOIN ( + SELECT MAX(started), clientFk, finished + FROM recovery + ) r ON r.clientFk = c.id + LEFT JOIN workerDepartment wd ON wd.workerFk = u.id + JOIN department dp ON dp.id = wd.departmentFk WHERE d.created = ? AND d.amount > 0 diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index fc1254dd8..e6690ee5f 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -5,7 +5,7 @@ "AddressObservation": { "dataSource": "vn" }, - "AddressShortage": { + "AddressWaste": { "dataSource": "vn" }, "BankEntity": { diff --git a/modules/client/back/models/addressShortage.json b/modules/client/back/models/address-waste.json similarity index 70% rename from modules/client/back/models/addressShortage.json rename to modules/client/back/models/address-waste.json index 1ae8d986c..2d7126eae 100644 --- a/modules/client/back/models/addressShortage.json +++ b/modules/client/back/models/address-waste.json @@ -1,15 +1,19 @@ { - "name": "AddressShortage", + "name": "AddressWaste", "base": "VnModel", "options": { "mysql": { - "table": "addressShortage" + "table": "addressWaste" } }, "properties": { "addressFk": { "type": "number", "id": true + }, + "type": { + "type": "string", + "id": true } }, "relations": { diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index f3eb9919b..f24f69ae7 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -144,6 +144,9 @@ }, "recommendedCredit": { "type": "number" + }, + "hasDailyInvoice": { + "type": "boolean" } }, diff --git a/modules/client/back/models/specs/address.spec.js b/modules/client/back/models/specs/address.spec.js index f0b421d35..3eae1b1bf 100644 --- a/modules/client/back/models/specs/address.spec.js +++ b/modules/client/back/models/specs/address.spec.js @@ -1,24 +1,10 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('loopback model address', () => { let createdAddressId; const clientId = 1101; - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - beforeAll(() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); afterAll(async() => { const client = await models.Client.findById(clientId); diff --git a/modules/client/front/address/index/index.js b/modules/client/front/address/index/index.js index 4bad9d4c8..f47d079b2 100644 --- a/modules/client/front/address/index/index.js +++ b/modules/client/front/address/index/index.js @@ -37,7 +37,7 @@ class Controller extends Section { include: { relation: 'country', scope: { - fields: ['id', 'country'] + fields: ['id', 'name'] } } } diff --git a/modules/client/front/extended-list/index.js b/modules/client/front/extended-list/index.js index 8eed48d01..208d77539 100644 --- a/modules/client/front/extended-list/index.js +++ b/modules/client/front/extended-list/index.js @@ -28,7 +28,7 @@ class Controller extends Section { field: 'countryFk', autocomplete: { url: 'Countries', - showField: 'country', + showField: 'name', } }, { diff --git a/modules/client/front/postcode/index.html b/modules/client/front/postcode/index.html index b3dbb74d8..fa0b7870f 100644 --- a/modules/client/front/postcode/index.html +++ b/modules/client/front/postcode/index.html @@ -53,7 +53,7 @@ diff --git a/modules/entry/back/methods/entry/buyLabel.js b/modules/entry/back/methods/entry/buyLabel.js new file mode 100644 index 000000000..d9b0ebf1d --- /dev/null +++ b/modules/entry/back/methods/entry/buyLabel.js @@ -0,0 +1,37 @@ +module.exports = Self => { + Self.remoteMethodCtx('buyLabel', { + description: 'Returns the entry buys labels', + accessType: 'READ', + accepts: [ + { + arg: 'id', + type: 'number', + required: true, + description: 'The entry id', + http: {source: 'path'} + } + ], + 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: '/:id/buy-label', + verb: 'GET' + }, + accessScopes: ['DEFAULT', 'read:multimedia'] + }); + + Self.buyLabel = (ctx, id) => Self.printReport(ctx, id, 'buy-label'); +}; diff --git a/modules/entry/back/methods/entry/filter.js b/modules/entry/back/methods/entry/filter.js index 1cd12b737..5963e9c72 100644 --- a/modules/entry/back/methods/entry/filter.js +++ b/modules/entry/back/methods/entry/filter.js @@ -1,4 +1,3 @@ - const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; const buildFilter = require('vn-loopback/util/filter').buildFilter; const mergeFilters = require('vn-loopback/util/filter').mergeFilters; @@ -95,6 +94,11 @@ module.exports = Self => { arg: 'to', type: 'date', description: `The to date filter` + }, + { + arg: 'days', + type: 'number', + description: `N days interval` } ], returns: { @@ -112,7 +116,6 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const conn = Self.dataSource.connector; const where = buildFilter(ctx.args, (param, value) => { switch (param) { @@ -146,7 +149,13 @@ module.exports = Self => { } }); filter = mergeFilters(ctx.args.filter, {where}); - + const userId = ctx.req.accessToken.userId; + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + if (!filter.where) filter.where = {}; + filter.where[`e.supplierFk`] = supplier.id; + } const stmts = []; let stmt; stmt = new ParameterizedSQL( @@ -158,7 +167,7 @@ module.exports = Self => { e.invoiceNumber, e.isBooked, e.isExcludedFromAvailable, - e.evaNotes AS observation, + e.evaNotes observation, e.isConfirmed, e.isOrdered, e.isRaid, @@ -170,17 +179,32 @@ module.exports = Self => { e.gestDocFk, e.invoiceInFk, t.landed, - s.name AS supplierName, - s.nickname AS supplierAlias, - co.code AS companyCode, - cu.code AS currencyCode + s.name supplierName, + s.nickname supplierAlias, + co.code companyCode, + cu.code currencyCode, + t.shipped, + t.landed, + t.ref AS travelRef, + t.warehouseInFk, + w.name warehouseInName FROM vn.entry e JOIN vn.supplier s ON s.id = e.supplierFk JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse w ON w.id = t.warehouseInFk JOIN vn.company co ON co.id = e.companyFk JOIN vn.currency cu ON cu.id = e.currencyFk` ); + if (ctx.args.days) { + stmt.merge({ + sql: ` + AND t.shipped <= util.VN_CURDATE() + INTERVAL ? DAY + AND t.shipped >= util.VN_CURDATE() + `, + params: [ctx.args.days] + }); + } stmt.merge(conn.makeSuffix(filter)); const itemsIndex = stmts.push(stmt) - 1; diff --git a/modules/entry/back/methods/entry/getBuys.js b/modules/entry/back/methods/entry/getBuys.js index 0ed77e8d1..b6809c8c5 100644 --- a/modules/entry/back/methods/entry/getBuys.js +++ b/modules/entry/back/methods/entry/getBuys.js @@ -1,7 +1,9 @@ +const UserError = require('vn-loopback/util/user-error'); + const mergeFilters = require('vn-loopback/util/filter').mergeFilters; module.exports = Self => { - Self.remoteMethod('getBuys', { + Self.remoteMethodCtx('getBuys', { description: 'Returns buys for one entry', accessType: 'READ', accepts: [{ @@ -27,13 +29,20 @@ module.exports = Self => { } }); - Self.getBuys = async(id, filter, options) => { + Self.getBuys = async(ctx, id, filter, options) => { + const userId = ctx.req.accessToken.userId; const models = Self.app.models; const myOptions = {}; if (typeof options == 'object') Object.assign(myOptions, options); + const client = await Self.app.models.Client.findById(userId, myOptions); + const supplier = await Self.app.models.Supplier.findOne({where: {nif: client.fi}}, myOptions); + if (supplier) { + const isEntryOwner = (await Self.findById(id)).supplierFk === supplier.id; + if (!isEntryOwner) throw new UserError('Access Denied'); + } let defaultFilter = { where: {entryFk: id}, fields: [ @@ -42,6 +51,7 @@ module.exports = Self => { 'stickers', 'packing', 'grouping', + 'packing', 'groupingMode', 'quantity', 'packagingFk', @@ -49,15 +59,31 @@ module.exports = Self => { 'buyingValue', 'price2', 'price3', - 'printedStickers' + 'printedStickers', + 'entryFk' ], - include: { + include: [{ + relation: 'entry', + scope: { + fields: [ + 'id', 'supplierFk' + ], + include: { + relation: 'supplier', scope: { + fields: ['id'] + } + } + } + }, + { relation: 'item', scope: { fields: [ 'id', 'typeFk', + 'stems', 'name', + 'category', 'subName', 'size', 'minPrice', @@ -73,18 +99,34 @@ module.exports = Self => { 'value9', 'tag10', 'value10', - 'groupingMode' + 'groupingMode', + 'inkFk', + 'originFk', + 'producerFk' ], - include: { - relation: 'itemType', - scope: { - fields: ['code', 'description'] + include: [ + { + relation: 'itemType', + scope: { + fields: ['code', 'description'] + } + }, + { + relation: 'origin', + scope: { + fields: ['code'] + } + }, + { + relation: 'producer', + scope: { + fields: ['name'] + } } - } + ] } - } + }] }; - defaultFilter = mergeFilters(defaultFilter, filter); return models.Buy.find(defaultFilter, myOptions); diff --git a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js index 1b0d4656f..0c8d2729b 100644 --- a/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js +++ b/modules/entry/back/methods/entry/specs/addFromPackaging.spec.js @@ -1,5 +1,4 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('entry addFromPackaging()', () => { const supplier = 442; @@ -7,22 +6,10 @@ describe('entry addFromPackaging()', () => { const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1); - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 49}, - http: { - req: { - headers: {origin: 'http://localhost'}, - }, - }, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx, - }); - }); + beforeAll.mockLoopBackContext(); it('should create an incoming travel', async() => { - const ctx = {args: {isTravelReception: true, supplier}}; + const ctx = {accessToken: {userId: 49}, args: {isTravelReception: true, supplier}}; const tx = await models.Entry.beginTransaction({}); const options = {transaction: tx}; diff --git a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js index 885171ed5..f319c112a 100644 --- a/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/editLatestBuys.spec.js @@ -1,21 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('Buy editLatestsBuys()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should change the value of a given column for the selected buys', async() => { const tx = await models.Buy.beginTransaction({}); diff --git a/modules/entry/back/methods/entry/specs/filter.spec.js b/modules/entry/back/methods/entry/specs/filter.spec.js index 28763bc81..c7156062a 100644 --- a/modules/entry/back/methods/entry/specs/filter.spec.js +++ b/modules/entry/back/methods/entry/specs/filter.spec.js @@ -9,7 +9,8 @@ describe('Entry filter()', () => { const ctx = { args: { search: 1 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -32,12 +33,13 @@ describe('Entry filter()', () => { const ctx = { args: { currencyFk: 1 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(9); + expect(result.length).toEqual(11); await tx.rollback(); } catch (e) { @@ -46,26 +48,73 @@ describe('Entry filter()', () => { } }); - it('should return the entry matching the supplier', async() => { - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; + describe('should return the entry matching the supplier', () => { + it('when userId is supplier ', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; - try { - const ctx = { - args: { - supplierFk: 2 - } - }; + try { + const ctx = { + args: {days: 6}, + req: {accessToken: {userId: 1102}} + }; - const result = await models.Entry.filter(ctx, options); + const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(6); + expect(result.length).toEqual(2); - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when userId is supplier fetching other supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + supplierFk: 1 + }, + req: {accessToken: {userId: 1102}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(8); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when userId is not supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + supplierFk: 2 + }, + req: {accessToken: {userId: 9}} + }; + + const result = await models.Entry.filter(ctx, options); + + expect(result.length).toEqual(8); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); it('should return the entry matching the company', async() => { @@ -76,12 +125,13 @@ describe('Entry filter()', () => { const ctx = { args: { companyFk: 442 - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); - expect(result.length).toEqual(8); + expect(result.length).toEqual(10); await tx.rollback(); } catch (e) { @@ -98,7 +148,8 @@ describe('Entry filter()', () => { const ctx = { args: { isBooked: true, - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); @@ -121,7 +172,8 @@ describe('Entry filter()', () => { args: { reference: 'movement', travelFk: '2' - } + }, + req: {accessToken: {userId: 9}} }; const result = await models.Entry.filter(ctx, options); diff --git a/modules/entry/back/methods/entry/specs/getBuys.spec.js b/modules/entry/back/methods/entry/specs/getBuys.spec.js index cf4462e48..2d3531249 100644 --- a/modules/entry/back/methods/entry/specs/getBuys.spec.js +++ b/modules/entry/back/methods/entry/specs/getBuys.spec.js @@ -1,24 +1,82 @@ +const UserError = require('vn-loopback/util/user-error'); const models = require('vn-loopback/server/server').models; describe('entry getBuys()', () => { const entryId = 4; - it('should get the buys and items of an entry', async() => { - const tx = await models.Entry.beginTransaction({}); - const options = {transaction: tx}; + describe('should get the buys and items of an entry ', () => { + it('when is supplier and entry owner', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; - try { - const result = await models.Entry.getBuys(entryId, options); + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 2}} + }; - const length = result.length; - const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + const result = await models.Entry.getBuys(ctx, entryId, options); - expect(result.length).toEqual(4); - expect(anyResult.item).toBeDefined(); + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - await tx.rollback(); - } catch (e) { - await tx.rollback(); - throw e; - } + expect(result.length).toEqual(4); + expect(anyResult.item).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); + + it('when is supplier but not entry owner', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + const entryId = 1; + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 1102}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); + + expect(result).toBeUndefined(); + } catch (error) { + expect(error).toBeInstanceOf(UserError); + expect(error.message).toBe('Access Denied'); + } + }); + + it('when is not supplier', async() => { + const tx = await models.Entry.beginTransaction({}); + const options = {transaction: tx}; + + try { + const ctx = { + args: { + search: 1 + }, + req: {accessToken: {userId: 9}} + }; + + const result = await models.Entry.getBuys(ctx, entryId, options); + + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; + + expect(result.length).toEqual(4); + expect(anyResult.item).toBeDefined(); + + await tx.rollback(); + } catch (e) { + await tx.rollback(); + throw e; + } + }); }); }); diff --git a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js index c860e228e..fb3268901 100644 --- a/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js +++ b/modules/entry/back/methods/entry/specs/importBuysPreview.spec.js @@ -1,14 +1,8 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); -const activeCtx = {accessToken: {userId: 9}}; describe('entry importBuysPreview()', () => { const entryId = 1; - beforeAll(async() => { - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should return the buys with the calculated packagingFk', async() => { const tx = await models.Entry.beginTransaction({}); diff --git a/modules/entry/back/models/entry.js b/modules/entry/back/models/entry.js index 6148ae559..6e27e1ece 100644 --- a/modules/entry/back/models/entry.js +++ b/modules/entry/back/models/entry.js @@ -9,6 +9,7 @@ module.exports = Self => { require('../methods/entry/entryOrderPdf')(Self); require('../methods/entry/addFromPackaging')(Self); require('../methods/entry/addFromBuy')(Self); + require('../methods/entry/buyLabel')(Self); Self.observe('before save', async function(ctx, options) { if (ctx.isNewInstance) return; diff --git a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js index f21dad9f2..2105cd9c0 100644 --- a/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in-due-day/specs/new.spec.js @@ -1,15 +1,7 @@ -const LoopBackContext = require('loopback-context'); const models = require('vn-loopback/server/server').models; describe('invoiceInDueDay new()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should correctly create a new due day', async() => { const userId = 9; diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js index 436306aab..cf1e0ac2d 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/clone.spec.js @@ -1,24 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('invoiceIn clone()', () => { - let ctx; + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 1}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; @@ -28,7 +15,8 @@ describe('invoiceIn clone()', () => { await tx.rollback(); }); - it('should return the cloned invoiceIn and also clone invoiceInDueDays and invoiceInTaxes if there are any referencing the invoiceIn', async() => { + it('should return the cloned invoiceIn and also clone invoiceInDueDays ' + + 'and invoiceInTaxes if there are any referencing the invoiceIn', async() => { const clone = await models.InvoiceIn.clone(ctx, 1, false, options); expect(clone.supplierRef).toEqual('1234(2)'); @@ -51,7 +39,8 @@ describe('invoiceIn clone()', () => { expect(invoiceInDueDay.length).toEqual(2); }); - it('should return the cloned invoiceIn and also clone invoiceInIntrastat and invoiceInTaxes if it is rectificative', async() => { + it('should return the cloned invoiceIn and also clone invoiceInIntrastat ' + + 'and invoiceInTaxes if it is rectificative', async() => { const clone = await models.InvoiceIn.clone(ctx, 1, true, options); expect(clone.supplierRef).toEqual('1234(2)'); diff --git a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js index 1047cd028..c63f02439 100644 --- a/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js +++ b/modules/invoiceIn/back/methods/invoice-in/specs/corrective.spec.js @@ -1,24 +1,11 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('invoiceIn corrective()', () => { - let ctx; + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.Sale.beginTransaction({}); options.transaction = tx; diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 3af7542ca..bebc9a8e4 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('invoiceOut book()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); const invoiceOutId = 5; it('should update the booked property', async() => { diff --git a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js index 823406500..335159de5 100644 --- a/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js +++ b/modules/item/back/methods/fixed-price/specs/upsertFixedPrice.spec.js @@ -1,24 +1,13 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('upsertFixedPrice()', () => { const now = Date.vnNew(); const fixedPriceId = 1; let originalFixedPrice; + beforeAll.mockLoopBackContext(); beforeAll(async() => { originalFixedPrice = await models.FixedPrice.findById(fixedPriceId); - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); }); it(`should toggle the hasMinPrice boolean if there's a minPrice and update the rest of the data`, async() => { diff --git a/modules/item/back/methods/item-shelving/getListItemNewer.js b/modules/item/back/methods/item-shelving/getListItemNewer.js index 1702bb05b..dafefe712 100644 --- a/modules/item/back/methods/item-shelving/getListItemNewer.js +++ b/modules/item/back/methods/item-shelving/getListItemNewer.js @@ -63,7 +63,7 @@ module.exports = Self => { FROM tItemShelving ti JOIN tItemInSector tis ON tis.itemFk = ti.itemFk JOIN vn.productionConfig pc - WHERE ti.created > tis.created + INTERVAL pc.itemOlderReviewHours HOUR;`, + WHERE ti.created + INTERVAL pc.itemOlderReviewHours HOUR < tis.created ;`, [shelvingFk, shelvingFk], myOptions); return result; }; diff --git a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js index 3f4917477..3b0a65e61 100644 --- a/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getAlternative.spec.js @@ -1,13 +1,7 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getAlternative()', () => { - beforeAll(async() => { - ctx = { - req: { - headers: {origin: 'http://localhost'}, - } - }; - }); + beforeAll.mockLoopBackContext(); it('should return a list of items without alternatives', async() => { const shelvingFk = 'HEJ'; diff --git a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js index 15c480992..962863095 100644 --- a/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js +++ b/modules/item/back/methods/item-shelving/specs/getListItemNewer.spec.js @@ -3,29 +3,16 @@ const {models} = require('vn-loopback/server/server'); describe('itemShelving getListItemNewer()', () => { it('should return true because there is an older item', async() => { - const shelving = 'NCC'; - const parking = 'A-47-1'; + const shelving = 'NBB'; + const parking = '700-01'; - const sectorCamHighCode = 'CAMARA SECTOR D'; - const sectorCamCode = 'NAVE ALGEMESI'; - - const sectorCamCodeHighId = 1; - const sectorCamCodeId = 9991; + const sectorCamHighCode = 'FIRST'; + const sectorCamCode = 'NS'; const tx = await models.Sector.beginTransaction({}); const myOptions = {transaction: tx}; try { - const sectorHighCam = await models.Sector.findById(sectorCamCodeHighId, null, myOptions); - await sectorHighCam.updateAttributes({ - code: sectorCamHighCode - }); - - const sectorCam = await models.Sector.findById(sectorCamCodeId, null, myOptions); - await sectorCam.updateAttributes({ - code: sectorCamCode - }); - const config = await models.ProductionConfig.findOne(); await config.updateAttributes({ @@ -35,7 +22,7 @@ describe('itemShelving getListItemNewer()', () => { const result = await models.ItemShelving.getListItemNewer(shelving, parking, myOptions); - expect(result.length).toEqual(2); + expect(result.length).toEqual(3); await tx.rollback(); } catch (e) { await tx.rollback(); diff --git a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js index 2dd43224c..f01cb985d 100644 --- a/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js +++ b/modules/item/back/methods/item-shelving/specs/upsertItem.spec.js @@ -1,25 +1,13 @@ const {models} = require('vn-loopback/server/server'); -const LoopBackContext = require('loopback-context'); describe('ItemShelving upsertItem()', () => { const warehouseFk = 1; - let ctx; + + const ctx = beforeAll.getCtx(); let options; let tx; beforeEach(async() => { - ctx = { - req: { - accessToken: {userId: 9}, - headers: {origin: 'http://localhost'} - }, - args: {} - }; - - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: ctx.req - }); - options = {transaction: tx}; tx = await models.ItemShelving.beginTransaction({}); options.transaction = tx; diff --git a/modules/item/back/methods/item/getSummary.js b/modules/item/back/methods/item/getSummary.js index 17a38cf07..55222f133 100644 --- a/modules/item/back/methods/item/getSummary.js +++ b/modules/item/back/methods/item/getSummary.js @@ -59,7 +59,7 @@ module.exports = Self => { include: [{ relation: 'country', scope: { - fields: ['id', 'country'] + fields: ['id', 'name'] } }, { relation: 'taxClass', diff --git a/modules/item/back/methods/item/specs/clone.spec.js b/modules/item/back/methods/item/specs/clone.spec.js index 01210677e..5bb5fe560 100644 --- a/modules/item/back/methods/item/specs/clone.spec.js +++ b/modules/item/back/methods/item/specs/clone.spec.js @@ -1,21 +1,8 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('item clone()', () => { let nextItemId; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); beforeEach(async() => { let query = `SELECT i1.id + 1 as id FROM vn.item i1 diff --git a/modules/item/back/methods/item/specs/getBalance.spec.js b/modules/item/back/methods/item/specs/getBalance.spec.js index 728b5f33e..95de3cc50 100644 --- a/modules/item/back/methods/item/specs/getBalance.spec.js +++ b/modules/item/back/methods/item/specs/getBalance.spec.js @@ -2,17 +2,14 @@ const models = require('vn-loopback/server/server').models; const LoopBackContext = require('loopback-context'); describe('item getBalance()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should return the balance lines of a client type loses in which one has highlighted true', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const activeCtx = { - accessToken: {userId: 9}, - }; spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx + active: ctx }); const losesClientId = 1111; const ticket = await models.Ticket.findById(7, null, options); @@ -64,7 +61,7 @@ describe('item getBalance()', () => { const secondItemBalance = await models.Item.getBalance(ctx, secondFilter, options); expect(firstItemBalance[9].claimFk).toEqual(null); - expect(secondItemBalance[7].claimFk).toEqual(2); + expect(secondItemBalance[7].claimFk).toEqual(1); await tx.rollback(); } catch (e) { diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index 2ffaf87a5..11570ffb9 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -1,21 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('item new()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.getCtx(); it('should create a new item, adding the name as a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/item/specs/regularize.spec.js b/modules/item/back/methods/item/specs/regularize.spec.js index e7df9a003..4e94d5d6d 100644 --- a/modules/item/back/methods/item/specs/regularize.spec.js +++ b/modules/item/back/methods/item/specs/regularize.spec.js @@ -1,27 +1,13 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('regularize()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 18}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + const ctx = beforeAll.mockLoopBackContext(18); it('should create a new ticket and add a line', async() => { const tx = await models.Item.beginTransaction({}); const options = {transaction: tx}; try { - const ctx = {req: {accessToken: {userId: 18}}}; const itemId = 1; const warehouseId = 1; const quantity = 11; diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index 793e43de8..828a5fec9 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('item updateTaxes()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should throw an error if the taxClassFk is blank', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/methods/tag/specs/onSubmit.spec.js b/modules/item/back/methods/tag/specs/onSubmit.spec.js index 1e96d9e81..e92a5fcdf 100644 --- a/modules/item/back/methods/tag/specs/onSubmit.spec.js +++ b/modules/item/back/methods/tag/specs/onSubmit.spec.js @@ -1,20 +1,7 @@ const models = require('vn-loopback/server/server').models; -const LoopBackContext = require('loopback-context'); describe('tag onSubmit()', () => { - beforeAll(async() => { - const activeCtx = { - accessToken: {userId: 9}, - http: { - req: { - headers: {origin: 'http://localhost'} - } - } - }; - spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ - active: activeCtx - }); - }); + beforeAll.mockLoopBackContext(); it('should delete a tag', async() => { const tx = await models.Item.beginTransaction({}); diff --git a/modules/item/back/model-config.json b/modules/item/back/model-config.json index 40d73f1a6..5dbe4d62a 100644 --- a/modules/item/back/model-config.json +++ b/modules/item/back/model-config.json @@ -32,6 +32,9 @@ "ItemLog": { "dataSource": "vn" }, + "ItemMinimumQuantity": { + "dataSource": "vn" + }, "ItemPackingType": { "dataSource": "vn" }, @@ -50,6 +53,9 @@ "ItemShelving": { "dataSource": "vn" }, + "ItemShelvingLog": { + "dataSource": "vn" + }, "ItemShelvingSale": { "dataSource": "vn" }, @@ -74,4 +80,4 @@ "FixedPrice": { "dataSource": "vn" } -} +} \ No newline at end of file diff --git a/modules/item/back/models/item-minimum-quantity.json b/modules/item/back/models/item-minimum-quantity.json new file mode 100644 index 000000000..74eac39fc --- /dev/null +++ b/modules/item/back/models/item-minimum-quantity.json @@ -0,0 +1,63 @@ +{ + "name": "ItemMinimumQuantity", + "base": "VnModel", + "options": { + "mysql": { + "table": "itemMinimumQuantity" + } + }, + "mixins": { + "Loggable": true + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Id" + }, + "itemFk": { + "type": "number", + "required": true + }, + "quantity": { + "type": "number", + "required": true + }, + "started": { + "type": "date", + "required": true + }, + "ended": { + "type": "date" + }, + "warehouseFk": { + "type": "number" + }, + "created": { + "type": "date" + }, + "editorFk": { + "type": "number" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "warehouse": { + "type": "belongsTo", + "model": "Warehouse", + "foreignKey": "warehouseFk" + } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "buyer", + "permission": "ALLOW" + } + ] +} \ No newline at end of file diff --git a/modules/item/back/models/item-shelving-log.json b/modules/item/back/models/item-shelving-log.json new file mode 100644 index 000000000..f976008f1 --- /dev/null +++ b/modules/item/back/models/item-shelving-log.json @@ -0,0 +1,52 @@ +{ + "name": "ItemShelvingLog", + "base": "VnModel", + "mixins": { + "Loggable": true + }, + "options": { + "mysql": { + "table": "itemShelvingLog" + } + }, + "properties": { + "id": { + "type": "number", + "id": true, + "description": "Identifier" + }, + "created": { + "type": "date" + }, + "shelvingFk": { + "type": "string" + }, + "itemFk": { + "type": "number" + }, + "visible": { + "type": "number" + }, + "accion": { + "type": "string" + } + }, + "relations": { + "item": { + "type": "belongsTo", + "model": "Item", + "foreignKey": "itemFk" + }, + "worker": { + "type": "belongsTo", + "model": "Worker", + "foreignKey": "workerFk" + }, + "shelving": { + "type": "belongsTo", + "model": "Shelving", + "foreignKey": "shelvingFk", + "primaryKey": "code" + } + } +} \ No newline at end of file diff --git a/modules/item/back/models/item.json b/modules/item/back/models/item.json index 10cff3e04..eda56e938 100644 --- a/modules/item/back/models/item.json +++ b/modules/item/back/models/item.json @@ -152,10 +152,6 @@ "columnName": "doPhoto" } }, - "minQuantity": { - "type": "number", - "description": "Min quantity" - }, "photoMotivation": { "type": "string" } diff --git a/modules/item/back/models/specs/itemMinimumQuantity.spec.js b/modules/item/back/models/specs/itemMinimumQuantity.spec.js new file mode 100644 index 000000000..072a80f94 --- /dev/null +++ b/modules/item/back/models/specs/itemMinimumQuantity.spec.js @@ -0,0 +1,101 @@ +const {models} = require('vn-loopback/server/server'); + +describe('itemMinimumQuantity model', () => { + const itemFk = 5; + const warehouseFk = 60; + + beforeAll(async() => { + await models.ItemMinimumQuantity.destroyAll({where: {itemFk: itemFk}}); + }); + + describe('CRUD operations', () => { + it('should create a new itemMinimumQuantity record', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: new Date(Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 1)), + warehouseFk: warehouseFk + }; + + const createdRecord = await models.ItemMinimumQuantity.create(newRecord); + + expect(createdRecord).toBeDefined(); + expect(createdRecord.quantity).toEqual(newRecord.quantity); + }); + + it('should read an existing itemMinimumQuantity record', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: new Date(Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 2)), + warehouseFk: warehouseFk + }; + + await models.ItemMinimumQuantity.create(newRecord); + + const existingRecord = await models.ItemMinimumQuantity.findOne({where: {itemFk: itemFk}}); + + expect(existingRecord).toBeDefined(); + expect(existingRecord.itemFk).toEqual(itemFk); + }); + + it('should update an existing itemMinimumQuantity record', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: new Date(Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 3)), + warehouseFk: warehouseFk + }; + + await models.ItemMinimumQuantity.create(newRecord); + + const newQuantity = 150; + const existingRecord = await models.ItemMinimumQuantity.findOne({where: {itemFk: itemFk}}); + existingRecord.quantity = newQuantity; + + await existingRecord.save(); + const updatedRecord = await models.ItemMinimumQuantity.findOne({where: {itemFk: itemFk}}); + + expect(updatedRecord.quantity).toEqual(newQuantity); + }); + }); + + describe('validation and constraints', () => { + it('should enforce unique constraint on itemFk, started, ended, and warehouseFk', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: Date.vnNew().setFullYear(Date.vnNew().getFullYear() + 5), + warehouseFk: warehouseFk + }; + + try { + await models.ItemMinimumQuantity.create(newRecord); + await models.ItemMinimumQuantity.create(newRecord); + } catch (e) { + expect(e).toBeDefined(); + expect(e.code).toContain('ER_DUP_ENTRY'); + } + }); + + it('should allow null values for ended and warehouseFk', async() => { + const newRecord = { + itemFk: itemFk, + quantity: 100, + started: Date.vnNew(), + ended: null, + warehouseFk: null + }; + + const createdRecord = await models.ItemMinimumQuantity.create(newRecord); + + expect(createdRecord).toBeDefined(); + expect(createdRecord.ended).toBeNull(); + expect(createdRecord.warehouseFk).toBeNull(); + }); + }); +}); diff --git a/modules/item/front/summary/index.html b/modules/item/front/summary/index.html index 13c671d29..0e4cfc955 100644 --- a/modules/item/front/summary/index.html +++ b/modules/item/front/summary/index.html @@ -128,9 +128,6 @@ - -

diff --git a/modules/monitor/back/methods/sales-monitor/salesFilter.js b/modules/monitor/back/methods/sales-monitor/salesFilter.js index 301e4ac35..33b37d8a4 100644 --- a/modules/monitor/back/methods/sales-monitor/salesFilter.js +++ b/modules/monitor/back/methods/sales-monitor/salesFilter.js @@ -162,7 +162,7 @@ module.exports = Self => { const stmts = []; let stmt; - + stmts.push(`SET @_optimizer_search_depth = @@optimizer_search_depth`); stmts.push(`SET SESSION optimizer_search_depth = 0`); diff --git a/modules/order/back/methods/order-row/specs/addToOrder.spec.js b/modules/order/back/methods/order-row/specs/addToOrder.spec.js index 96544a1a9..2bc78ffef 100644 --- a/modules/order/back/methods/order-row/specs/addToOrder.spec.js +++ b/modules/order/back/methods/order-row/specs/addToOrder.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order addToOrder()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); const orderId = 8; it('should add a row to a given order', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/catalogFilter.js b/modules/order/back/methods/order/catalogFilter.js index ab1d7784e..27048457c 100644 --- a/modules/order/back/methods/order/catalogFilter.js +++ b/modules/order/back/methods/order/catalogFilter.js @@ -119,7 +119,7 @@ module.exports = Self => { w.firstName, tci.priceKg, ink.hex, - i.minQuantity + tci.minQuantity FROM tmp.ticketCalculateItem tci JOIN vn.item i ON i.id = tci.itemFk JOIN vn.itemType it ON it.id = i.typeFk @@ -158,21 +158,19 @@ module.exports = Self => { // Apply item prices const pricesIndex = stmts.push( - `SELECT - tcp.itemFk, + `SELECT tcp.itemFk, tcp.grouping, tcp.price, tcp.rate, tcp.warehouseFk, tcp.priceKg, - w.name AS warehouse + w.name warehouse FROM tmp.ticketComponentPrice tcp JOIN vn.warehouse w ON w.id = tcp.warehouseFk`) - 1; // Get tags from all items const itemTagsIndex = stmts.push( - `SELECT - t.id, + `SELECT t.id, t.name, t.isFree, t.sourceTable, diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index 68de7fe04..9e644bb2d 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -1,11 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order filter()', () => { - const ctx = { - req: {accessToken: {userId: 9}}, - args: {}, - params: {} - }; + const ctx = beforeAll.getCtx(); it('should call the filter method with a basic search', async() => { const myCtx = Object.assign({}, ctx); diff --git a/modules/order/back/methods/order/specs/new.spec.js b/modules/order/back/methods/order/specs/new.spec.js index c43527f66..779de6ada 100644 --- a/modules/order/back/methods/order/specs/new.spec.js +++ b/modules/order/back/methods/order/specs/new.spec.js @@ -2,7 +2,7 @@ const models = require('vn-loopback/server/server').models; const UserError = require('vn-loopback/util/user-error'); describe('order new()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should throw an error if the client isnt active', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/back/methods/order/specs/newFromTicket.spec.js b/modules/order/back/methods/order/specs/newFromTicket.spec.js index c509552fe..d927a0338 100644 --- a/modules/order/back/methods/order/specs/newFromTicket.spec.js +++ b/modules/order/back/methods/order/specs/newFromTicket.spec.js @@ -1,7 +1,7 @@ const models = require('vn-loopback/server/server').models; describe('order newFromTicket()', () => { - const ctx = {req: {accessToken: {userId: 9}}}; + const ctx = beforeAll.getCtx(); it('should create a new order from an existing ticket', async() => { const tx = await models.Order.beginTransaction({}); diff --git a/modules/order/front/catalog-view/index.html b/modules/order/front/catalog-view/index.html index 081ce05a0..b047e1e6a 100644 --- a/modules/order/front/catalog-view/index.html +++ b/modules/order/front/catalog-view/index.html @@ -37,18 +37,18 @@ value="{{::item.value7}}"> - - - - - - {{::item.minQuantity}} - + + + + + + {{::item.minQuantity}} +