From 47d689ae509db96842e0e646a27eb9636e07232c Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Mon, 21 Oct 2019 08:31:14 +0200 Subject: [PATCH 01/59] Uploadfile parameters are now required + fixed date filters --- back/methods/dms/uploadFile.js | 18 ++++++---- .../back/methods/claim/regularizeClaim.js | 11 +++--- .../claim/back/methods/claim/uploadFile.js | 34 +++++++++---------- .../client/back/methods/client/uploadFile.js | 34 +++++++++---------- modules/item/back/methods/item/regularize.js | 11 +++--- .../ticket/back/methods/ticket/uploadFile.js | 34 +++++++++---------- 6 files changed, 74 insertions(+), 68 deletions(-) diff --git a/back/methods/dms/uploadFile.js b/back/methods/dms/uploadFile.js index 41d551f2b..e077eea30 100644 --- a/back/methods/dms/uploadFile.js +++ b/back/methods/dms/uploadFile.js @@ -9,25 +9,31 @@ module.exports = Self => { { arg: 'warehouseId', type: 'Number', - description: 'The warehouse id' + description: 'The warehouse id', + required: true }, { arg: 'companyId', type: 'Number', - description: 'The company id' + description: 'The company id', + required: true }, { arg: 'dmsTypeId', type: 'Number', - description: 'The dms type id' + description: 'The dms type id', + required: true }, { arg: 'reference', - type: 'String' + type: 'String', + required: true }, { arg: 'description', - type: 'String' + type: 'String', + required: true }, { arg: 'hasFile', type: 'Boolean', - description: 'True if has an attached file' + description: 'True if has an attached file', + required: true }], returns: { type: 'Object', diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index a2896174e..136016b1e 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -120,16 +120,19 @@ module.exports = Self => { } async function getTicketId(params, options) { - const currentDate = new Date(); - currentDate.setHours(null, null, null); + const minDate = new Date(); + minDate.setHours(0, 0, 0, 0); + + const maxDate = new Date(); + maxDate.setHours(23, 59, 59, 59); let ticket = await Self.app.models.Ticket.findOne({ where: { addressFk: params.addressFk, companyFk: params.companyFk, warehouseFk: params.warehouseFk, - shipped: currentDate, - landed: currentDate + shipped: {between: [minDate, maxDate]}, + landed: {between: [minDate, maxDate]} } }, options); diff --git a/modules/claim/back/methods/claim/uploadFile.js b/modules/claim/back/methods/claim/uploadFile.js index f6dad3477..c7565701d 100644 --- a/modules/claim/back/methods/claim/uploadFile.js +++ b/modules/claim/back/methods/claim/uploadFile.js @@ -7,36 +7,34 @@ module.exports = Self => { type: 'Number', description: 'The claim id', http: {source: 'path'} - }, - { + }, { arg: 'warehouseId', type: 'Number', - description: '' - }, - { + description: 'The warehouse id', + required: true + }, { arg: 'companyId', type: 'Number', - description: '' - }, - { + description: 'The company id', + required: true + }, { arg: 'dmsTypeId', type: 'Number', - description: '' - }, - { + description: 'The dms type id', + required: true + }, { arg: 'reference', type: 'String', - description: '' - }, - { + required: true + }, { arg: 'description', type: 'String', - description: '' - }, - { + required: true + }, { arg: 'hasFile', type: 'Boolean', - description: '' + description: 'True if has an attached file', + required: true }], returns: { type: 'Object', diff --git a/modules/client/back/methods/client/uploadFile.js b/modules/client/back/methods/client/uploadFile.js index 6b7a49459..6ec96e301 100644 --- a/modules/client/back/methods/client/uploadFile.js +++ b/modules/client/back/methods/client/uploadFile.js @@ -7,36 +7,34 @@ module.exports = Self => { type: 'Number', description: 'The client id', http: {source: 'path'} - }, - { + }, { arg: 'warehouseId', type: 'Number', - description: '' - }, - { + description: 'The warehouse id', + required: true + }, { arg: 'companyId', type: 'Number', - description: '' - }, - { + description: 'The company id', + required: true + }, { arg: 'dmsTypeId', type: 'Number', - description: '' - }, - { + description: 'The dms type id', + required: true + }, { arg: 'reference', type: 'String', - description: '' - }, - { + required: true + }, { arg: 'description', type: 'String', - description: '' - }, - { + required: true + }, { arg: 'hasFile', type: 'Boolean', - description: '' + description: 'True if has an attached file', + required: true }], returns: { type: 'Object', diff --git a/modules/item/back/methods/item/regularize.js b/modules/item/back/methods/item/regularize.js index 17f1dbe1e..b9aa0d85f 100644 --- a/modules/item/back/methods/item/regularize.js +++ b/modules/item/back/methods/item/regularize.js @@ -105,15 +105,18 @@ module.exports = Self => { async function getTicketId(params, options) { - const currentDate = new Date(); - currentDate.setHours(null, null, null); + const minDate = new Date(); + minDate.setHours(0, 0, 0, 0); + + const maxDate = new Date(); + maxDate.setHours(23, 59, 59, 59); let ticket = await Self.app.models.Ticket.findOne({ where: { addressFk: params.addressFk, warehouseFk: params.warehouseFk, - shipped: currentDate, - landed: currentDate + shipped: {between: [minDate, maxDate]}, + landed: {between: [minDate, maxDate]} } }, options); diff --git a/modules/ticket/back/methods/ticket/uploadFile.js b/modules/ticket/back/methods/ticket/uploadFile.js index 7c968f5c9..e5ea465cb 100644 --- a/modules/ticket/back/methods/ticket/uploadFile.js +++ b/modules/ticket/back/methods/ticket/uploadFile.js @@ -7,36 +7,34 @@ module.exports = Self => { type: 'Number', description: 'The ticket id', http: {source: 'path'} - }, - { + }, { arg: 'warehouseId', type: 'Number', - description: '' - }, - { + description: 'The warehouse id', + required: true + }, { arg: 'companyId', type: 'Number', - description: '' - }, - { + description: 'The company id', + required: true + }, { arg: 'dmsTypeId', type: 'Number', - description: '' - }, - { + description: 'The dms type id', + required: true + }, { arg: 'reference', type: 'String', - description: '' - }, - { + required: true + }, { arg: 'description', type: 'String', - description: '' - }, - { + required: true + }, { arg: 'hasFile', type: 'Boolean', - description: '' + description: 'True if has an attached file', + required: true }], returns: { type: 'Object', From ff292baecff06ce22050780123289600fb64f4f4 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Mon, 21 Oct 2019 11:09:18 +0200 Subject: [PATCH 02/59] added item-label report and configurable report options --- print/config/print.json | 7 ++ print/config/routes.json | 1 + print/lib/reportEngine.js | 14 ++- print/package.json | 1 + .../report/rpt-item-label/assets/css/index.js | 8 ++ .../rpt-item-label/assets/css/style.css | 88 +++++++++++++++++++ print/report/rpt-item-label/index.html | 28 ++++++ print/report/rpt-item-label/index.js | 83 +++++++++++++++++ print/report/rpt-item-label/locale.js | 24 +++++ print/report/rpt-item-label/options.json | 10 +++ 10 files changed, 256 insertions(+), 8 deletions(-) create mode 100644 print/report/rpt-item-label/assets/css/index.js create mode 100644 print/report/rpt-item-label/assets/css/style.css create mode 100644 print/report/rpt-item-label/index.html create mode 100755 print/report/rpt-item-label/index.js create mode 100644 print/report/rpt-item-label/locale.js create mode 100644 print/report/rpt-item-label/options.json diff --git a/print/config/print.json b/print/config/print.json index cb98421fc..7ad2e1316 100755 --- a/print/config/print.json +++ b/print/config/print.json @@ -5,6 +5,13 @@ "senderMail": "nocontestar@verdnatura.es", "senderName": "Verdnatura" }, + "pdf": { + "format": "A4", + "border": "1.5cm", + "footer": { + "height": "55px" + } + }, "mysql": { "host": "localhost", "port": 3306, diff --git a/print/config/routes.json b/print/config/routes.json index e658f4cc4..58d46193c 100644 --- a/print/config/routes.json +++ b/print/config/routes.json @@ -17,6 +17,7 @@ {"type": "report", "name": "rpt-zone"}, {"type": "report", "name": "rpt-route"}, {"type": "report", "name": "rpt-lcr"}, + {"type": "report", "name": "rpt-item-label"}, {"type": "static", "name": "email-header"}, {"type": "static", "name": "email-footer"}, {"type": "static", "name": "report-header"}, diff --git a/print/lib/reportEngine.js b/print/lib/reportEngine.js index 8c771c449..0903c0f78 100644 --- a/print/lib/reportEngine.js +++ b/print/lib/reportEngine.js @@ -2,9 +2,9 @@ const Vue = require('vue'); const VueI18n = require('vue-i18n'); const renderer = require('vue-server-renderer').createRenderer(); const fs = require('fs-extra'); -// const pdf = require('phantom-html2pdf'); const pdf = require('html-pdf'); const juice = require('juice'); +const config = require('./config'); Vue.use(VueI18n); @@ -104,13 +104,11 @@ module.exports = { async toPdf(name, ctx) { const html = await this.render(name, ctx); - const options = { - format: 'A4', - border: '1.5cm', - footer: { - height: '55px', - } - }; + let options = config.pdf; + + const optionsPath = `${this.path}/${name}/options.json`; + if (fs.existsSync(optionsPath)) + options = Object.assign(options, require(optionsPath)); return new Promise(resolve => { pdf.create(html, options).toStream((err, stream) => { diff --git a/print/package.json b/print/package.json index bb7c32a3e..0332817c2 100755 --- a/print/package.json +++ b/print/package.json @@ -18,6 +18,7 @@ "juice": "^5.0.1", "mysql2": "^1.6.5", "nodemailer": "^4.7.0", + "qrcode": "^1.4.2", "strftime": "^0.10.0", "vue": "^2.6.7", "vue-i18n": "^8.8.2", diff --git a/print/report/rpt-item-label/assets/css/index.js b/print/report/rpt-item-label/assets/css/index.js new file mode 100644 index 000000000..515dea750 --- /dev/null +++ b/print/report/rpt-item-label/assets/css/index.js @@ -0,0 +1,8 @@ +const CssReader = require(`${appPath}/lib/cssReader`); + +module.exports = new CssReader([ + `${appPath}/common/css/layout.css`, + `${appPath}/common/css/report.css`, + `${appPath}/common/css/misc.css`, + `${__dirname}/style.css`]) + .mergeStyles(); diff --git a/print/report/rpt-item-label/assets/css/style.css b/print/report/rpt-item-label/assets/css/style.css new file mode 100644 index 000000000..98a3ec721 --- /dev/null +++ b/print/report/rpt-item-label/assets/css/style.css @@ -0,0 +1,88 @@ +* { + box-sizing: border-box; +} +.label { + font-size: 1.2em; +} + +.barcode { + float: left; + width: 40%; +} + +.barcode h1 { + text-align: center; + font-size: 1.8em; + margin: 0 +} + +.barcode .image { + text-align: center +} + +.barcode .image img { + width: 180px +} + +.data { + float: left; + width: 60%; +} + +.data .header { + background-color: #000; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + margin-bottom: 25px; + text-align: right; + font-size: 1.2em; + padding: 0.2em; + color: #FFF +} + +.data .color, +.data .producer { + text-transform: uppercase; + text-align: right; + font-size: 1.5em; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; +} + +.data .producer { + text-justify: inter-character; +} + +.data .details { + border-top: 4px solid #000; + padding-top: 2px; +} + +.data .details .package { + padding-right: 5px; + float: left; + width: 50%; +} + +.package .packing, +.package .dated, +.package .labelNumber { + text-align: right +} + +.package .packing { + font-size: 1.8em; + font-weight: 400 +} + +.data .details .size { + background-color: #000; + text-align: center; + font-size: 3em; + padding: 0.2em 0; + float: left; + width: 50%; + color: #FFF +} \ No newline at end of file diff --git a/print/report/rpt-item-label/index.html b/print/report/rpt-item-label/index.html new file mode 100644 index 000000000..0b46aee14 --- /dev/null +++ b/print/report/rpt-item-label/index.html @@ -0,0 +1,28 @@ + + + +
+
+
+

{{item.id}}

+
+ +
+
+
+
{{item.name}}
+
{{tags.color}}
+
{{tags.producer}}
+
+
+
{{packing()}}
+
{{dated}}
+
{{labelPage()}}
+
+
{{item.size}}
+
+
+
+
+ + \ No newline at end of file diff --git a/print/report/rpt-item-label/index.js b/print/report/rpt-item-label/index.js new file mode 100755 index 000000000..7e6a61351 --- /dev/null +++ b/print/report/rpt-item-label/index.js @@ -0,0 +1,83 @@ +const database = require(`${appPath}/lib/database`); +const UserException = require(`${appPath}/lib/exceptions/userException`); +const strftime = require('strftime'); +const qrcode = require('qrcode'); + +module.exports = { + name: 'rpt-item-label', + async asyncData(ctx, params) { + Object.assign(this, this.methods); + + if (!params.itemId) + throw new UserException('No item id specified'); + + if (!params.warehouseId) + throw new UserException('No warehouse id specified'); + + const data = { + item: await this.fetchItem(params.itemId, params.warehouseId), + tags: await this.fetchItemTags(params.itemId), + barcode: await this.getBarcodeBase64(params.itemId), + labelNumber: params.labelNumber, + totalLabels: params.totalLabels + }; + + return data; + }, + computed: { + dated() { + return strftime('%W/%d', new Date()); + } + }, + methods: { + fetchItem(id, warehouseId) { + return database.pool.query( + `SELECT + i.id, + i.name, + i.stems, + i.size, + b.packing + FROM vn.item i + JOIN cache.last_buy clb ON clb.item_id = i.id + JOIN vn.buy b ON b.id = clb.buy_id + JOIN vn.entry e ON e.id = b.entryFk + WHERE i.id = ? AND clb.warehouse_id = ?`, [id, warehouseId]) + .then(([rows]) => { + if (rows.length == 0) + throw new UserException(`Item #${id} not found on warehouse #${warehouseId}`); + return rows[0]; + }); + }, + fetchItemTags(itemId) { + return database.pool.query( + `SELECT t.code, t.name, it.value + FROM vn.itemTag it + JOIN vn.tag t ON t.id = it.tagFk + WHERE it.itemFk = ?`, [itemId]) + .then(([rows]) => { + const tags = {}; + rows.forEach(row => tags[row.code] = row.value); + + return tags; + }); + }, + getBarcodeBase64(itemId) { + return qrcode.toDataURL(itemId); + }, + packing() { + const stems = this.item.stems ? this.item.stems : 1; + return `${this.item.packing}x${stems}`; + }, + labelPage() { + const labelNumber = this.labelNumber ? this.labelNumber : 1; + const totalLabels = this.totalLabels ? this.totalLabels : 1; + + return `${labelNumber}/${totalLabels}`; + } + }, + components: { + 'report-header': require('../report-header'), + 'report-footer': require('../report-footer'), + }, +}; diff --git a/print/report/rpt-item-label/locale.js b/print/report/rpt-item-label/locale.js new file mode 100644 index 000000000..b8d524274 --- /dev/null +++ b/print/report/rpt-item-label/locale.js @@ -0,0 +1,24 @@ +module.exports = { + messages: { + es: { + title: 'Recibo', + date: 'Fecha', + payed: 'En {0}, a {1} de {2} de {3}', + client: 'Cliente {0}', + months: [ + 'Enero', + 'Febrero', + 'Marzo', + 'Abril', + 'Mayo', + 'Junio', + 'Julio', + 'Agosto', + 'Septiembre', + 'Octubre', + 'Noviembre', + 'Diciembre' + ] + }, + }, +}; diff --git a/print/report/rpt-item-label/options.json b/print/report/rpt-item-label/options.json new file mode 100644 index 000000000..6b00b0443 --- /dev/null +++ b/print/report/rpt-item-label/options.json @@ -0,0 +1,10 @@ +{ + "format": "A4", + "orientation": "landscape", + "width": "10.4cm", + "height": "4.8cm", + "border": "0cm", + "footer": { + "height": "0" + } +} \ No newline at end of file From f752404ebe79b4d986f5b70092220781defdcee0 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Mon, 21 Oct 2019 11:33:40 +0200 Subject: [PATCH 03/59] removed QR barcode margins --- print/report/rpt-item-label/assets/css/style.css | 4 ++-- print/report/rpt-item-label/index.js | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/print/report/rpt-item-label/assets/css/style.css b/print/report/rpt-item-label/assets/css/style.css index 98a3ec721..1101604b9 100644 --- a/print/report/rpt-item-label/assets/css/style.css +++ b/print/report/rpt-item-label/assets/css/style.css @@ -13,7 +13,7 @@ .barcode h1 { text-align: center; font-size: 1.8em; - margin: 0 + margin: 0 0 10px 0 } .barcode .image { @@ -21,7 +21,7 @@ } .barcode .image img { - width: 180px + width: 170px } .data { diff --git a/print/report/rpt-item-label/index.js b/print/report/rpt-item-label/index.js index 7e6a61351..922965eb0 100755 --- a/print/report/rpt-item-label/index.js +++ b/print/report/rpt-item-label/index.js @@ -63,7 +63,7 @@ module.exports = { }); }, getBarcodeBase64(itemId) { - return qrcode.toDataURL(itemId); + return qrcode.toDataURL(itemId, {margin: 0}); }, packing() { const stems = this.item.stems ? this.item.stems : 1; From dd17bb0386ec2a1473e6eccd5584cf5d1343ef3f Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 31 Oct 2019 13:18:29 +0100 Subject: [PATCH 04/59] Descuadre de meses componente calendar #1733 --- front/core/components/calendar/index.js | 7 +++---- modules/agency/front/location/calendar.js | 7 +++++-- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/front/core/components/calendar/index.js b/front/core/components/calendar/index.js index 23c0450fa..fd9252242 100644 --- a/front/core/components/calendar/index.js +++ b/front/core/components/calendar/index.js @@ -260,9 +260,9 @@ export default class Calendar extends Component { */ moveNext(skip = 1) { let next = this.defaultDate.getMonth() + skip; - this.defaultDate.setMonth(next); this.defaultDate.setHours(0, 0, 0, 0); this.defaultDate.setDate(1); + this.defaultDate.setMonth(next); this.repaint(); this.emit('moveNext'); @@ -275,11 +275,10 @@ export default class Calendar extends Component { */ movePrevious(skip = 1) { let previous = this.defaultDate.getMonth() - skip; - this.defaultDate.setMonth(previous); this.defaultDate.setHours(0, 0, 0, 0); + this.defaultDate.setDate(1); + this.defaultDate.setMonth(previous); - const lastDate = this.lastDay(this.defaultDate); - this.defaultDate.setDate(lastDate.getDate()); this.repaint(); this.emit('movePrevious'); diff --git a/modules/agency/front/location/calendar.js b/modules/agency/front/location/calendar.js index d9226c221..6867badaa 100644 --- a/modules/agency/front/location/calendar.js +++ b/modules/agency/front/location/calendar.js @@ -7,8 +7,11 @@ class Controller { this.$scope = $scope; this.$http = $http; this.stMonthDate = new Date(); - this.ndMonthDate = new Date(); - this.ndMonthDate.setMonth(this.ndMonthDate.getMonth() + 1); + const ndMonth = new Date(); + ndMonth.setDate(1); + ndMonth.setMonth(ndMonth.getMonth() + 1); + + this.ndMonthDate = ndMonth; } $postLink() { From e056184337de599be03ee8180135270518498a38 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 15 Nov 2019 10:44:11 +0100 Subject: [PATCH 05/59] holidays fix #1853 --- .../back/methods/worker-calendar/absences.js | 43 ++++++++++--------- .../worker-calendar/specs/absences.spec.js | 32 ++++++-------- 2 files changed, 35 insertions(+), 40 deletions(-) diff --git a/modules/worker/back/methods/worker-calendar/absences.js b/modules/worker/back/methods/worker-calendar/absences.js index e822291b7..541f95ff5 100644 --- a/modules/worker/back/methods/worker-calendar/absences.js +++ b/modules/worker/back/methods/worker-calendar/absences.js @@ -108,10 +108,18 @@ module.exports = Self => { } }); - // Get number of total holidays + // Get number of worked days + let workedDays = 0; contracts.forEach(contract => { - calendar.totalHolidays += getHolidaysByContract(contract, yearEnded); + const started = contract.started; + const ended = contract.ended; + const startedTime = started.getTime(); + const endedTime = ended && ended.getTime() || yearEnded; + const dayTimestamp = 1000 * 60 * 60 * 24; + workedDays += Math.floor((endedTime - startedTime) / dayTimestamp); + + // Workcenter holidays let holidayList = contract.workCenter().holidays(); for (let day of holidayList) { day.dated = new Date(day.dated); @@ -120,26 +128,19 @@ module.exports = Self => { holidays.push(day); } }); + const currentContract = contracts.find(contract => { + return contract.started <= new Date() + && (contract.ended >= new Date() || contract.ended == null); + }); + + if (currentContract) { + const maxDays = currentContract.holidays().days; + calendar.totalHolidays = maxDays; + + if (workedDays < 365) + calendar.totalHolidays = Math.round(2 * maxDays * (workedDays + 1) / 365) / 2; + } return [calendar, absences, holidays]; }; - - function getHolidaysByContract(contract, endOfYear) { - const dayTimestamp = 1000 * 60 * 60 * 24; - - const started = contract.started; - const ended = contract.ended; - const startedTime = started.getTime(); - const endedTime = ended && ended.getTime() || endOfYear; - - const contractDays = Math.floor((endedTime - startedTime) / dayTimestamp); - - if (contractDays < 365) { - let holidays = Math.round(2 * contract.holidays().days * (contractDays + 1) / 365) / 2; - - return holidays; - } - - return contract.holidays().days; - } }; diff --git a/modules/worker/back/methods/worker-calendar/specs/absences.spec.js b/modules/worker/back/methods/worker-calendar/specs/absences.spec.js index ccafa683d..0a5e92e1f 100644 --- a/modules/worker/back/methods/worker-calendar/specs/absences.spec.js +++ b/modules/worker/back/methods/worker-calendar/specs/absences.spec.js @@ -43,13 +43,13 @@ describe('Worker absences()', () => { expect(sixthType).toEqual('Holidays'); }); - it(`should fire the worker 106 on Juny and see he/she has 14`, async() => { + it(`should see he/she has 26.5`, async() => { let workerFk = 106; const firedWorker = await app.models.WorkerLabour.findById(workerFk); const endedDate = new Date(); - endedDate.setDate(30); - endedDate.setMonth(5); + endedDate.setDate(endedDate.getDate() + 1); + endedDate.setMonth(endedDate.getMonth() + 1); endedDate.setHours(0, 0, 0, 0); await firedWorker.updateAttributes({ended: endedDate}); @@ -71,7 +71,7 @@ describe('Worker absences()', () => { let calendar = result[0]; let absences = result[1]; - expect(calendar.totalHolidays).toEqual(13.5); + expect(calendar.totalHolidays).toEqual(26.5); expect(calendar.holidaysEnjoyed).toEqual(5); let firstType = absences[0].absenceType().name; @@ -81,13 +81,13 @@ describe('Worker absences()', () => { expect(sixthType).toEqual('Holidays'); }); - it(`should fire the worker 106 on March and see he/she has 7`, async() => { + it(`should see he/she has 26.5`, async() => { const firedWorker = await app.models.WorkerLabour.findById(106); const endedDate = new Date(); + endedDate.setDate(endedDate.getDate() + 1); + endedDate.setMonth(endedDate.getMonth() + 1); endedDate.setHours(0, 0, 0, 0); - endedDate.setMonth(2); - endedDate.setDate(31); await firedWorker.updateAttributes({ended: endedDate}); @@ -109,7 +109,7 @@ describe('Worker absences()', () => { let calendar = result[0]; let absences = result[1]; - expect(calendar.totalHolidays).toEqual(7); + expect(calendar.totalHolidays).toEqual(26.5); expect(calendar.holidaysEnjoyed).toEqual(5); let firstType = absences[0].absenceType().name; @@ -119,19 +119,13 @@ describe('Worker absences()', () => { expect(sixthType).toEqual('Holidays'); }); - it(`should fire the worker 106 on january and see he/she has x`, async() => { - const firedWorker = await app.models.WorkerLabour.findById(106); - - const endedDate = new Date(); - endedDate.setHours(0, 0, 0, 0); - endedDate.setMonth(0); - endedDate.setDate(28); - - await firedWorker.updateAttributes({ended: endedDate}); - + it(`should see he/she has 27.5`, async() => { let ctx = {req: {accessToken: {userId: 106}}}; let workerFk = 106; + const firedWorker = await app.models.WorkerLabour.findById(106); + await firedWorker.updateAttributes({ended: null}); + const started = new Date(); started.setHours(0, 0, 0, 0); started.setMonth(0); @@ -147,7 +141,7 @@ describe('Worker absences()', () => { let calendar = result[0]; let absences = result[1]; - expect(calendar.totalHolidays).toEqual(2); + expect(calendar.totalHolidays).toEqual(27.5); expect(calendar.holidaysEnjoyed).toEqual(5); let firstType = absences[0].absenceType().name; From 1ac422a963bb5ab2b53c1d906fe7813f9e6a1ba9 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Sun, 8 Dec 2019 14:11:02 +0100 Subject: [PATCH 06/59] Back autoheal & health-check --- Dockerfile | 2 +- Jenkinsfile | 22 +++++++++++++--------- back/process.yml | 6 ++++++ docker-compose.yml | 4 +++- front/nginx.conf | 15 --------------- loopback/common/models/vn-model.js | 2 +- 6 files changed, 24 insertions(+), 27 deletions(-) create mode 100644 back/process.yml diff --git a/Dockerfile b/Dockerfile index 79831cf06..65c2aa0b1 100644 --- a/Dockerfile +++ b/Dockerfile @@ -33,4 +33,4 @@ COPY \ README.md \ ./ -CMD ["pm2-docker", "./loopback/server/server.js"] +CMD ["pm2-runtime", "./back/process.yml"] diff --git a/Jenkinsfile b/Jenkinsfile index a5ef853d5..d2fc2ab6d 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -6,13 +6,15 @@ pipeline { disableConcurrentBuilds() } environment { - PROJECT_NAME = 'salix' - REGISTRY = 'registry.verdnatura.es' - DOCKER_HOST_1 = 'vch1.verdnatura.es' - DOCKER_HOST_2 = 'vch2.verdnatura.es' - PORT_MASTER = '5002' - PORT_TEST = '5001' - TAG = "${env.BRANCH_NAME}" + PROJECT_NAME = 'salix' + REGISTRY = 'registry.verdnatura.es' + DOCKER_HOST_1 = 'vch1.verdnatura.es' + DOCKER_HOST_2 = 'vch2.verdnatura.es' + PORT_MASTER_FRONT = '5002' + PORT_MASTER_BACK = '3001-3005' + PORT_TEST_FRONT = '5001' + PORT_TEST_BACK = '4001-4005' + TAG = "${env.BRANCH_NAME}" } stages { stage('Checkout') { @@ -31,10 +33,12 @@ pipeline { switch (env.BRANCH_NAME) { case 'master': - env.PORT = PORT_MASTER + env.PORT_FRONT = PORT_MASTER_FRONT + env.PORT_BACK = PORT_MASTER_BACK break case 'test': - env.PORT = PORT_TEST + env.PORT_FRONT = PORT_TEST_FRONT + env.PORT_BACK = PORT_TEST_BACK break } switch (env.BRANCH_NAME) { diff --git a/back/process.yml b/back/process.yml new file mode 100644 index 000000000..c35876898 --- /dev/null +++ b/back/process.yml @@ -0,0 +1,6 @@ +apps: + - script: ./loopback/server/server.js + name: salix-back + cron_restart: '*/30 * * * *' + instances: 1 + max_restarts: 10 diff --git a/docker-compose.yml b/docker-compose.yml index 7fcf95a79..cd08ac0e1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -7,13 +7,15 @@ services: context: . dockerfile: front/Dockerfile ports: - - ${PORT}:80 + - ${PORT_FRONT}:80 links: - back back: image: registry.verdnatura.es/salix-back:${TAG} restart: unless-stopped build: . + ports: + - ${PORT_BACK}:3000 environment: - NODE_ENV volumes: diff --git a/front/nginx.conf b/front/nginx.conf index bbba60ab2..64f9436f3 100644 --- a/front/nginx.conf +++ b/front/nginx.conf @@ -1,16 +1,4 @@ -set_real_ip_from 0.0.0.0/0; -real_ip_header X-Forwarded-For; -log_format upstreamlog - '[$time_local] $remote_addr -> $proxy_host:$upstream_addr ' - '"$request" $status $body_bytes_sent ' - '"$http_referer" "$http_user_agent"'; -access_log /var/log/nginx/access.log upstreamlog; - -upstream back { - server back_1:3000; - server back_2:3000; -} server { listen 80 default_server; listen [::]:80 default_server; @@ -24,9 +12,6 @@ server { location @notfound { return 302 /; } - location ~ ^(/[a-zA-Z0-9_-]+)?/(?api(/.*)?)$ { - proxy_pass http://back/$path$is_args$args; - } location / { autoindex on; } diff --git a/loopback/common/models/vn-model.js b/loopback/common/models/vn-model.js index d03d52ae8..0191967b1 100644 --- a/loopback/common/models/vn-model.js +++ b/loopback/common/models/vn-model.js @@ -20,7 +20,7 @@ module.exports = function(Self) { this.beginTransaction = function(options, cb) { options = options || {}; if (!options.timeout) - options.timeout = 30000; + options.timeout = 120000; return orgBeginTransaction.call(this, options, cb); }; }); From 34ff3048c94c4bac8102e1dfe9777d2f7f2da6ea Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Sun, 8 Dec 2019 14:18:52 +0100 Subject: [PATCH 07/59] Back port range fixes --- Jenkinsfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index d2fc2ab6d..f8e1d13e9 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -11,9 +11,9 @@ pipeline { DOCKER_HOST_1 = 'vch1.verdnatura.es' DOCKER_HOST_2 = 'vch2.verdnatura.es' PORT_MASTER_FRONT = '5002' - PORT_MASTER_BACK = '3001-3005' + PORT_MASTER_BACK = '3001-3002' PORT_TEST_FRONT = '5001' - PORT_TEST_BACK = '4001-4005' + PORT_TEST_BACK = '4001-4002' TAG = "${env.BRANCH_NAME}" } stages { From 982832d29b2a633840245c7fc47d7fff727e69d5 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Sun, 8 Dec 2019 14:42:59 +0100 Subject: [PATCH 08/59] module removed from api path --- front/core/lib/module-loader.js | 2 +- modules/agency/front/basic-data/index.html | 6 +++--- modules/agency/front/calendar/index.html | 2 +- modules/agency/front/card/index.js | 2 +- modules/agency/front/card/index.spec.js | 2 +- modules/agency/front/create/index.html | 6 +++--- modules/agency/front/descriptor/index.js | 2 +- modules/agency/front/edit/index.html | 6 +++--- modules/agency/front/index/index.js | 2 +- .../front/location-search-panel/index.html | 4 ++-- modules/agency/front/location/calendar.html | 2 +- modules/agency/front/location/calendar.js | 4 ++-- modules/agency/front/location/index.js | 2 +- modules/agency/front/search-panel/index.html | 4 ++-- modules/agency/front/summary/index.js | 2 +- modules/claim/front/action/index.html | 6 +++--- modules/claim/front/action/index.js | 16 ++++++++-------- modules/claim/front/action/index.spec.js | 16 ++++++++-------- modules/claim/front/basic-data/index.html | 4 ++-- modules/claim/front/card/index.js | 2 +- modules/claim/front/card/index.spec.js | 2 +- modules/claim/front/descriptor/index.js | 2 +- modules/claim/front/descriptor/index.spec.js | 4 ++-- modules/claim/front/detail/index.html | 2 +- modules/claim/front/detail/index.js | 6 +++--- modules/claim/front/detail/index.spec.js | 8 ++++---- modules/claim/front/development/index.html | 10 +++++----- modules/claim/front/index/index.html | 2 +- modules/claim/front/search-panel/index.html | 6 +++--- modules/claim/front/summary/index.js | 2 +- modules/claim/front/summary/index.spec.js | 4 ++-- modules/client/front/address/create/index.html | 4 ++-- modules/client/front/address/edit/index.html | 10 +++++----- modules/client/front/address/index/index.js | 2 +- modules/client/front/address/index/index.spec.js | 4 ++-- modules/client/front/balance/create/index.html | 2 +- modules/client/front/balance/create/index.js | 4 ++-- modules/client/front/balance/index/index.html | 6 +++--- modules/client/front/balance/index/index.js | 2 +- modules/client/front/balance/index/index.spec.js | 4 ++-- modules/client/front/basic-data/index.html | 6 +++--- modules/client/front/billing-data/index.html | 8 ++++---- modules/client/front/billing-data/index.js | 4 ++-- modules/client/front/billing-data/index.spec.js | 12 ++++++------ modules/client/front/card/index.js | 2 +- modules/client/front/contact/index.html | 2 +- modules/client/front/create/index.html | 4 ++-- .../front/credit-insurance/create/index.js | 2 +- .../front/credit-insurance/create/index.spec.js | 4 ++-- .../client/front/credit-insurance/index/index.js | 4 ++-- .../front/credit-insurance/index/index.spec.js | 6 +++--- .../credit-insurance/insurance/create/index.html | 2 +- .../credit-insurance/insurance/index/index.html | 2 +- .../credit-insurance/insurance/index/index.js | 2 +- .../insurance/index/index.spec.js | 2 +- modules/client/front/credit/create/index.html | 2 +- modules/client/front/credit/create/index.js | 2 +- modules/client/front/credit/create/index.spec.js | 12 ++++++------ modules/client/front/credit/index/index.html | 2 +- modules/client/front/descriptor-popover/index.js | 2 +- .../front/descriptor-popover/index.spec.js | 4 ++-- modules/client/front/dms/index/index.html | 2 +- modules/client/front/fiscal-data/index.html | 2 +- modules/client/front/fiscal-data/index.js | 2 +- modules/client/front/fiscal-data/index.spec.js | 4 ++-- modules/client/front/greuge/create/index.html | 4 ++-- modules/client/front/greuge/index/index.html | 4 ++-- modules/client/front/index/index.html | 2 +- modules/client/front/mandate/index.html | 2 +- modules/client/front/note/create/index.html | 2 +- modules/client/front/note/index/index.html | 2 +- modules/client/front/recovery/create/index.html | 2 +- modules/client/front/recovery/index/index.html | 2 +- modules/client/front/recovery/index/index.js | 2 +- modules/client/front/sample/create/index.html | 6 +++--- modules/client/front/sample/index/index.html | 2 +- modules/client/front/search-panel/index.html | 2 +- modules/client/front/sms/index.js | 2 +- modules/client/front/sms/index.spec.js | 4 ++-- modules/client/front/summary/index.js | 2 +- modules/client/front/summary/index.spec.js | 4 ++-- modules/client/front/web-access/index.html | 2 +- modules/client/front/web-access/index.js | 6 +++--- modules/client/front/web-access/index.spec.js | 12 ++++++------ modules/client/front/web-payment/index.html | 2 +- modules/client/front/web-payment/index.js | 2 +- modules/client/front/web-payment/index.spec.js | 2 +- modules/invoiceOut/front/descriptor/index.js | 4 ++-- modules/item/front/barcode/index.html | 2 +- modules/item/front/basic-data/index.html | 10 +++++----- modules/item/front/botanical/index.html | 6 +++--- modules/item/front/botanical/index.js | 2 +- modules/item/front/botanical/index.spec.js | 4 ++-- modules/item/front/card/index.js | 2 +- modules/item/front/card/index.spec.js | 4 ++-- modules/item/front/create/index.html | 8 ++++---- modules/item/front/descriptor-popover/index.js | 2 +- .../item/front/descriptor-popover/index.spec.js | 4 ++-- modules/item/front/descriptor/index.js | 4 ++-- modules/item/front/diary/index.html | 4 ++-- modules/item/front/index/index.html | 2 +- modules/item/front/index/index.js | 2 +- modules/item/front/index/index.spec.js | 4 ++-- modules/item/front/last-entries/index.html | 2 +- modules/item/front/niche/index.html | 4 ++-- .../item/front/request-search-panel/index.html | 2 +- modules/item/front/request/index.html | 2 +- modules/item/front/search-panel/index.html | 6 +++--- modules/item/front/search-panel/index.js | 4 ++-- modules/item/front/summary/index.js | 2 +- modules/item/front/summary/index.spec.js | 4 ++-- modules/item/front/tags/index.html | 4 ++-- modules/item/front/tax/index.html | 2 +- modules/item/front/tax/index.js | 4 ++-- modules/item/front/tax/index.spec.js | 10 +++++----- modules/order/front/basic-data/index.html | 2 +- modules/order/front/card/index.js | 4 ++-- modules/order/front/card/index.spec.js | 8 ++++---- modules/order/front/catalog/index.html | 2 +- modules/order/front/create/card.js | 2 +- modules/order/front/create/card.spec.js | 4 ++-- modules/order/front/filter/index.html | 2 +- modules/order/front/line/index.js | 6 +++--- modules/order/front/line/index.spec.js | 6 +++--- modules/order/front/prices-popover/index.js | 4 ++-- modules/order/front/search-panel/index.html | 6 +++--- modules/order/front/summary/index.js | 2 +- modules/order/front/summary/index.spec.js | 4 ++-- modules/order/front/volume/index.html | 4 ++-- modules/order/front/volume/index.js | 2 +- modules/order/front/volume/index.spec.js | 4 ++-- modules/route/front/card/index.js | 2 +- modules/route/front/descriptor/index.js | 2 +- modules/route/front/search-panel/index.html | 8 ++++---- modules/route/front/tickets/index.js | 2 +- .../front/basic-data/step-three/index.html | 2 +- modules/ticket/front/card/index.js | 4 ++-- modules/ticket/front/card/index.spec.js | 8 ++++---- modules/ticket/front/component/index.html | 2 +- modules/ticket/front/create/card.html | 2 +- modules/ticket/front/create/card.js | 2 +- modules/ticket/front/descriptor-popover/index.js | 2 +- .../front/descriptor-popover/index.spec.js | 4 ++-- modules/ticket/front/descriptor/index.js | 8 ++++---- modules/ticket/front/descriptor/index.spec.js | 14 +++++++------- modules/ticket/front/dms/index/index.html | 2 +- modules/ticket/front/expedition/index.html | 2 +- modules/ticket/front/expedition/index.js | 2 +- modules/ticket/front/expedition/index.spec.js | 4 ++-- modules/ticket/front/index/index.html | 2 +- modules/ticket/front/note/index.html | 4 ++-- modules/ticket/front/package/index.html | 2 +- modules/ticket/front/picture/index.html | 2 +- modules/ticket/front/request/create/index.html | 4 ++-- modules/ticket/front/request/index/index.html | 2 +- modules/ticket/front/sale-checked/index.html | 2 +- modules/ticket/front/sale-tracking/index.html | 2 +- modules/ticket/front/search-panel/index.html | 2 +- modules/ticket/front/services/index.html | 2 +- modules/ticket/front/summary/index.js | 4 ++-- modules/ticket/front/summary/index.spec.js | 4 ++-- modules/ticket/front/tracking/edit/index.html | 4 ++-- modules/ticket/front/tracking/index/index.html | 2 +- modules/ticket/front/volume/index.html | 6 +++--- modules/ticket/front/weekly/index/index.html | 2 +- modules/ticket/front/weekly/index/index.js | 4 ++-- modules/travel/front/index/index.html | 2 +- modules/travel/front/search-panel/index.html | 6 +++--- modules/worker/front/calendar/index.js | 2 +- modules/worker/front/calendar/index.spec.js | 4 ++-- modules/worker/front/department/index.html | 2 +- modules/worker/front/department/index.js | 4 ++-- modules/worker/front/index/index.html | 2 +- modules/worker/front/time-control/index.html | 2 +- 174 files changed, 331 insertions(+), 331 deletions(-) diff --git a/front/core/lib/module-loader.js b/front/core/lib/module-loader.js index 477b1c943..d42583b5a 100644 --- a/front/core/lib/module-loader.js +++ b/front/core/lib/module-loader.js @@ -42,7 +42,7 @@ export function factory($http, $window, $ocLazyLoad, $translatePartialLoader, $t if (validations) { promises.push(new Promise(resolve => { - $http.get(`/${moduleName}/api/modelInfo`).then( + $http.get(`api/modelInfo`).then( json => this.onValidationsReady(json, resolve), () => resolve() ); diff --git a/modules/agency/front/basic-data/index.html b/modules/agency/front/basic-data/index.html index 7f4ed91ef..a14bbaf5c 100644 --- a/modules/agency/front/basic-data/index.html +++ b/modules/agency/front/basic-data/index.html @@ -1,4 +1,4 @@ - + { if (res.data) this.zone = res.data; diff --git a/modules/agency/front/card/index.spec.js b/modules/agency/front/card/index.spec.js index 86d3ebaa4..0839d7f53 100644 --- a/modules/agency/front/card/index.spec.js +++ b/modules/agency/front/card/index.spec.js @@ -26,7 +26,7 @@ describe('Agency Component vnZoneCard', () => { ] }; let json = encodeURIComponent(JSON.stringify(filter)); - $httpBackend.expectGET(`/agency/api/Zones/1?filter=${json}`).respond({id: 1}); + $httpBackend.expectGET(`api/Zones/1?filter=${json}`).respond({id: 1}); controller.getCard(); $httpBackend.flush(); diff --git a/modules/agency/front/create/index.html b/modules/agency/front/create/index.html index 461829259..e287c8e7d 100644 --- a/modules/agency/front/create/index.html +++ b/modules/agency/front/create/index.html @@ -1,4 +1,4 @@ - + diff --git a/modules/agency/front/descriptor/index.js b/modules/agency/front/descriptor/index.js index c8d6bbc26..b599dfd40 100644 --- a/modules/agency/front/descriptor/index.js +++ b/modules/agency/front/descriptor/index.js @@ -20,7 +20,7 @@ class Controller { returnDialog(response) { if (response === 'ACCEPT') { - this.$http.delete(`/agency/api/Zones/${this.zone.id}`).then(() => { + this.$http.delete(`api/Zones/${this.zone.id}`).then(() => { this.$state.go('zone.index'); }); } diff --git a/modules/agency/front/edit/index.html b/modules/agency/front/edit/index.html index 452c54417..8143c5643 100644 --- a/modules/agency/front/edit/index.html +++ b/modules/agency/front/edit/index.html @@ -1,4 +1,4 @@ - + @@ -25,7 +25,7 @@ diff --git a/modules/agency/front/index/index.js b/modules/agency/front/index/index.js index a85be6e72..a95f5c949 100644 --- a/modules/agency/front/index/index.js +++ b/modules/agency/front/index/index.js @@ -42,7 +42,7 @@ export default class Controller { */ onCloneAccept(response) { if (!(response == 'ACCEPT' && this.selectedZone)) return; - const query = `/agency/api/Zones/${this.selectedZone.id}/clone`; + const query = `api/Zones/${this.selectedZone.id}/clone`; this.$http.post(query).then(res => { if (res && res.data) this.$state.go('zone.card.basicData', {id: res.data.id}); diff --git a/modules/agency/front/location-search-panel/index.html b/modules/agency/front/location-search-panel/index.html index 9621f8b56..39f2b2938 100644 --- a/modules/agency/front/location-search-panel/index.html +++ b/modules/agency/front/location-search-panel/index.html @@ -20,7 +20,7 @@ vn-one label="Agency" field="filter.agencyModeFk" - url="/agency/api/AgencyModes/isActive" + url="api/AgencyModes/isActive" show-field="name" value-field="id"> @@ -28,7 +28,7 @@ vn-one label="Warehouse" field="filter.warehouseFk" - url="/agency/api/Warehouses" + url="api/Warehouses" show-field="name" value-field="id"> diff --git a/modules/agency/front/location/calendar.html b/modules/agency/front/location/calendar.html index ad58aee1a..39b54133e 100644 --- a/modules/agency/front/location/calendar.html +++ b/modules/agency/front/location/calendar.html @@ -1,6 +1,6 @@ { if (!res.data) return; const events = []; @@ -128,7 +128,7 @@ class Controller { if (dates.length == 0) return; const params = {zoneFk: this.zone.id, dates}; - this.$http.post('/agency/api/zoneCalendars/removeByDate', params).then(() => { + this.$http.post('api/zoneCalendars/removeByDate', params).then(() => { this.events = calendar.events; }); } diff --git a/modules/agency/front/location/index.js b/modules/agency/front/location/index.js index 3e3decf23..da47fa299 100644 --- a/modules/agency/front/location/index.js +++ b/modules/agency/front/location/index.js @@ -24,7 +24,7 @@ class Controller { node.isIncluded = isIncluded; node.childs = []; // Data too large - const path = '/agency/api/ZoneIncludeds/toggleIsIncluded'; + const path = 'api/ZoneIncludeds/toggleIsIncluded'; const params = {zoneFk: this.zone.id, item: node}; this.$http.post(path, params); } diff --git a/modules/agency/front/search-panel/index.html b/modules/agency/front/search-panel/index.html index fd0a0158b..2ad89291d 100644 --- a/modules/agency/front/search-panel/index.html +++ b/modules/agency/front/search-panel/index.html @@ -21,7 +21,7 @@ vn-one label="Agency" field="filter.agencyModeFk" - url="/agency/api/AgencyModes/isActive" + url="api/AgencyModes/isActive" show-field="name" value-field="id"> @@ -29,7 +29,7 @@ vn-one label="Warehouse" field="filter.warehouseFk" - url="/agency/api/Warehouses" + url="api/Warehouses" show-field="name" value-field="id"> diff --git a/modules/agency/front/summary/index.js b/modules/agency/front/summary/index.js index 1c200edde..641d70b78 100644 --- a/modules/agency/front/summary/index.js +++ b/modules/agency/front/summary/index.js @@ -26,7 +26,7 @@ class Controller { where: {id: this.zone.id} }; filter = encodeURIComponent(JSON.stringify((filter))); - this.$http.get(`/agency/api/Zones/findOne?filter=${filter}`).then(res => { + this.$http.get(`api/Zones/findOne?filter=${filter}`).then(res => { if (res && res.data) this.summary = res.data; }); diff --git a/modules/claim/front/action/index.html b/modules/claim/front/action/index.html index 3875b9912..1867d330f 100644 --- a/modules/claim/front/action/index.html +++ b/modules/claim/front/action/index.html @@ -1,6 +1,6 @@ @@ -87,7 +87,7 @@ vn-one id="claimDestinationFk" field="saleClaimed.claimDestinationFk" - url="/claim/api/ClaimDestinations" + url="api/ClaimDestinations" fields="['id','description']" value-field="id" show-field="description" @@ -166,7 +166,7 @@ diff --git a/modules/claim/front/action/index.js b/modules/claim/front/action/index.js index 5193b5114..c09fd0e8b 100644 --- a/modules/claim/front/action/index.js +++ b/modules/claim/front/action/index.js @@ -34,7 +34,7 @@ class Controller { getClaimedSales() { let json = encodeURIComponent(JSON.stringify(this.claim.id)); - let query = `/claim/api/ClaimBeginnings/${json}`; + let query = `api/ClaimBeginnings/${json}`; this.$http.get(query).then(res => { if (res.data) this.claimedSales = res.data; @@ -43,7 +43,7 @@ class Controller { addClaimedSale(saleFk) { let saleToAdd = {saleFk: saleFk, claimFk: this.claim.id, workerFk: this.claim.workerFk, claimDestinationFk: 1}; - let query = `claim/api/ClaimEnds/`; + let query = `api/ClaimEnds/`; this.$http.post(query, saleToAdd).then(() => { this.$.model.refresh(); this.$.addSales.hide(); @@ -53,7 +53,7 @@ class Controller { deleteClaimedSale(id) { let json = encodeURIComponent(JSON.stringify(id)); - let query = `claim/api/ClaimEnds/${json}`; + let query = `api/ClaimEnds/${json}`; this.$http.delete(query).then(() => { this.$.model.refresh(); this.vnApp.showSuccess(this.$translate.instant('Data saved!')); @@ -61,7 +61,7 @@ class Controller { } importToNewRefundTicket() { - let query = `claim/api/ClaimBeginnings/${this.$stateParams.id}/importToNewRefundTicket`; + let query = `api/ClaimBeginnings/${this.$stateParams.id}/importToNewRefundTicket`; return this.$http.post(query).then(() => { this.$.model.refresh(); this.vnApp.showSuccess(this.$translate.instant('Data saved!')); @@ -85,7 +85,7 @@ class Controller { setClaimDestination(id, claimDestinationFk) { if (claimDestinationFk) { let params = {id: id, claimDestinationFk: claimDestinationFk}; - let query = `claim/api/ClaimEnds/`; + let query = `api/ClaimEnds/`; this.$http.patch(query, params).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); }); @@ -122,7 +122,7 @@ class Controller { importTicketLines(ticketFk) { let data = {claimFk: this.$stateParams.id, ticketFk: ticketFk}; - let query = `/claim/api/ClaimEnds/importTicketSales`; + let query = `api/ClaimEnds/importTicketSales`; this.$http.post(query, data).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.$.lastTicketsPopover.hide(); @@ -132,7 +132,7 @@ class Controller { regularize() { let data = {claimFk: this.$stateParams.id}; - let query = `/claim/api/Claims/regularizeClaim`; + let query = `api/Claims/regularizeClaim`; return this.$http.post(query, data).then(() => { this.card.reload(); this.vnApp.showSuccess(this.$translate.instant('Data saved!')); @@ -145,7 +145,7 @@ class Controller { if (response !== 'ACCEPT') return; let greugeTypeFreight = 7; - let query = `claim/api/Greuges/`; + let query = `api/Greuges/`; let data = { clientFk: this.claim.clientFk, description: `claim: ${this.claim.id}`, diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index d1f8f9766..59203aabe 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -46,7 +46,7 @@ describe('claim', () => { describe('getClaimedSales()', () => { it('should make a query and set salesToClaim', () => { controller.claim.id = 1; - $httpBackend.expectGET(`/claim/api/ClaimBeginnings/1`).respond(200, 1); + $httpBackend.expectGET(`api/ClaimBeginnings/1`).respond(200, 1); controller.getClaimedSales(); $httpBackend.flush(); @@ -59,7 +59,7 @@ describe('claim', () => { spyOn(controller.$.model, 'refresh'); spyOn(controller.$.addSales, 'hide'); spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectPOST(`claim/api/ClaimEnds/`).respond({}); + $httpBackend.expectPOST(`api/ClaimEnds/`).respond({}); controller.addClaimedSale(1); $httpBackend.flush(); @@ -73,7 +73,7 @@ describe('claim', () => { it('should make a delete and call refresh and showSuccess', () => { spyOn(controller.$.model, 'refresh'); spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectDELETE(`claim/api/ClaimEnds/1`).respond({}); + $httpBackend.expectDELETE(`api/ClaimEnds/1`).respond({}); controller.deleteClaimedSale(1); $httpBackend.flush(); @@ -85,7 +85,7 @@ describe('claim', () => { describe('setClaimDestination(id, claimDestinationFk)', () => { it('should make a patch and call refresh and showSuccess', () => { spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectPATCH(`claim/api/ClaimEnds/`).respond({}); + $httpBackend.expectPATCH(`api/ClaimEnds/`).respond({}); controller.setClaimDestination(1, 1); $httpBackend.flush(); @@ -110,7 +110,7 @@ describe('claim', () => { it('should perform a post query and add lines from a new ticket', () => { spyOn(controller.$.model, 'refresh'); spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expect('POST', `claim/api/ClaimBeginnings/1/importToNewRefundTicket`).respond({}); + $httpBackend.expect('POST', `api/ClaimBeginnings/1/importToNewRefundTicket`).respond({}); controller.importToNewRefundTicket(); $httpBackend.flush(); @@ -136,7 +136,7 @@ describe('claim', () => { spyOn(controller.vnApp, 'showSuccess'); spyOn(controller.$.lastTicketsPopover, 'hide'); let data = {claimFk: 1, ticketFk: 1}; - $httpBackend.expect('POST', `/claim/api/ClaimEnds/importTicketSales`, data).respond({}); + $httpBackend.expect('POST', `api/ClaimEnds/importTicketSales`, data).respond({}); controller.importTicketLines(1); $httpBackend.flush(); @@ -152,7 +152,7 @@ describe('claim', () => { spyOn(controller.vnApp, 'showSuccess'); let data = {claimFk: $state.params.id}; - $httpBackend.expect('POST', `/claim/api/Claims/regularizeClaim`, data).respond({}); + $httpBackend.expect('POST', `api/Claims/regularizeClaim`, data).respond({}); controller.regularize(); $httpBackend.flush(); @@ -186,7 +186,7 @@ describe('claim', () => { greugeTypeFk: 7, ticketFk: controller.claim.ticketFk }; - $httpBackend.expect('POST', `claim/api/Greuges/`, data).respond(); + $httpBackend.expect('POST', `api/Greuges/`, data).respond(); controller.onUpdateGreugeResponse('ACCEPT'); $httpBackend.flush(); diff --git a/modules/claim/front/basic-data/index.html b/modules/claim/front/basic-data/index.html index b626f57c7..87d04c603 100644 --- a/modules/claim/front/basic-data/index.html +++ b/modules/claim/front/basic-data/index.html @@ -12,7 +12,7 @@ vn-one disabled="true" field="$ctrl.claim.clientFk" - url="/client/api/Clients" + url="api/Clients" show-field="name" value-field="id" label="Client" @@ -41,7 +41,7 @@ { if (res.data) this.claim = res.data; diff --git a/modules/claim/front/card/index.spec.js b/modules/claim/front/card/index.spec.js index 3ac4c7e32..17d4e3174 100644 --- a/modules/claim/front/card/index.spec.js +++ b/modules/claim/front/card/index.spec.js @@ -21,7 +21,7 @@ describe('Claim', () => { describe('getCard()', () => { it(`should make a query and save the data in claim`, () => { let json = encodeURIComponent(JSON.stringify(controller.filter)); - $httpBackend.expectGET(`/claim/api/Claims/${controller.$state.params.id}?filter=${json}`).respond({id: 1}); + $httpBackend.expectGET(`api/Claims/${controller.$state.params.id}?filter=${json}`).respond({id: 1}); controller.getCard(); $httpBackend.flush(); diff --git a/modules/claim/front/descriptor/index.js b/modules/claim/front/descriptor/index.js index 8d6977ea6..fa39c3638 100644 --- a/modules/claim/front/descriptor/index.js +++ b/modules/claim/front/descriptor/index.js @@ -82,7 +82,7 @@ class Controller { deleteClaim(response) { if (response === 'ACCEPT') { - this.$http.delete(`/claim/api/Claims/${this.claim.id}`).then(() => { + this.$http.delete(`api/Claims/${this.claim.id}`).then(() => { this.vnApp.showSuccess(this.$translate.instant('Claim deleted!')); this.$state.go('claim.index'); }); diff --git a/modules/claim/front/descriptor/index.spec.js b/modules/claim/front/descriptor/index.spec.js index c6446a15b..6c10564b4 100644 --- a/modules/claim/front/descriptor/index.spec.js +++ b/modules/claim/front/descriptor/index.spec.js @@ -68,8 +68,8 @@ describe('Item Component vnClaimDescriptor', () => { spyOn(controller.vnApp, 'showSuccess'); spyOn(controller.$state, 'go'); - $httpBackend.when('DELETE', `/claim/api/Claims/2`).respond(200); - $httpBackend.expect('DELETE', `/claim/api/Claims/2`); + $httpBackend.when('DELETE', `api/Claims/2`).respond(200); + $httpBackend.expect('DELETE', `api/Claims/2`); controller.deleteClaim(response); $httpBackend.flush(); diff --git a/modules/claim/front/detail/index.html b/modules/claim/front/detail/index.html index 5fc032e33..6ade7a80f 100644 --- a/modules/claim/front/detail/index.html +++ b/modules/claim/front/detail/index.html @@ -1,7 +1,7 @@ diff --git a/modules/claim/front/detail/index.js b/modules/claim/front/detail/index.js index 137ad4d70..94d5cf76f 100644 --- a/modules/claim/front/detail/index.js +++ b/modules/claim/front/detail/index.js @@ -63,7 +63,7 @@ class Controller { addClaimedSale(index) { let sale = this.salesToClaim[index]; let saleToAdd = {saleFk: sale.saleFk, claimFk: this.claim.id, quantity: sale.quantity}; - let query = `claim/api/ClaimBeginnings/`; + let query = `api/ClaimBeginnings/`; this.$http.post(query, saleToAdd).then(() => { this.$.addSales.hide(); this.$.model.refresh(); @@ -76,7 +76,7 @@ class Controller { deleteClaimedSale(index) { let sale = this.salesClaimed[index]; - let query = `claim/api/ClaimBeginnings/${sale.id}`; + let query = `api/ClaimBeginnings/${sale.id}`; this.$http.delete(query).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.$.model.remove(index); @@ -86,7 +86,7 @@ class Controller { setClaimedQuantity(id, claimedQuantity) { let params = {id: id, quantity: claimedQuantity}; - let query = `claim/api/ClaimBeginnings/`; + let query = `api/ClaimBeginnings/`; this.$http.patch(query, params).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.calculateTotals(); diff --git a/modules/claim/front/detail/index.spec.js b/modules/claim/front/detail/index.spec.js index c25d6fe43..3550468fe 100644 --- a/modules/claim/front/detail/index.spec.js +++ b/modules/claim/front/detail/index.spec.js @@ -14,7 +14,7 @@ describe('claim', () => { beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { $httpBackend = _$httpBackend_; - $httpBackend.when('GET', 'claim/api/Claims/ClaimBeginnings').respond({}); + $httpBackend.when('GET', 'api/Claims/ClaimBeginnings').respond({}); $state = _$state_; aclService = {hasAny: () => true}; controller = $componentController('vnClaimDetail', {$state, aclService}); @@ -54,7 +54,7 @@ describe('claim', () => { it('should make a post and call refresh, hide and showSuccess', () => { spyOn(controller.$.addSales, 'hide'); spyOn(controller.$state, 'go'); - $httpBackend.expectPOST(`claim/api/ClaimBeginnings/`).respond({}); + $httpBackend.expectPOST(`api/ClaimBeginnings/`).respond({}); controller.addClaimedSale(1); $httpBackend.flush(); @@ -66,7 +66,7 @@ describe('claim', () => { describe('deleteClaimedSale(index)', () => { it('should make a delete and call refresh and showSuccess', () => { spyOn(controller.$.model, 'remove'); - $httpBackend.expectDELETE(`claim/api/ClaimBeginnings/1`).respond({}); + $httpBackend.expectDELETE(`api/ClaimBeginnings/1`).respond({}); controller.deleteClaimedSale(0); $httpBackend.flush(); @@ -77,7 +77,7 @@ describe('claim', () => { describe('setClaimedQuantity(id, claimedQuantity)', () => { it('should make a patch and call refresh and showSuccess', () => { spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.expectPATCH(`claim/api/ClaimBeginnings/`).respond({}); + $httpBackend.expectPATCH(`api/ClaimBeginnings/`).respond({}); controller.setClaimedQuantity(1, 1); $httpBackend.flush(); diff --git a/modules/claim/front/development/index.html b/modules/claim/front/development/index.html index e3f368451..a5035ec9f 100644 --- a/modules/claim/front/development/index.html +++ b/modules/claim/front/development/index.html @@ -1,6 +1,6 @@ diff --git a/modules/claim/front/index/index.html b/modules/claim/front/index/index.html index caeb756de..02c768245 100644 --- a/modules/claim/front/index/index.html +++ b/modules/claim/front/index/index.html @@ -1,6 +1,6 @@ diff --git a/modules/claim/front/search-panel/index.html b/modules/claim/front/search-panel/index.html index 5540c87c8..a62434c32 100644 --- a/modules/claim/front/search-panel/index.html +++ b/modules/claim/front/search-panel/index.html @@ -32,7 +32,7 @@ {{description}} diff --git a/modules/claim/front/summary/index.js b/modules/claim/front/summary/index.js index 5741f2c06..509d9fd4b 100644 --- a/modules/claim/front/summary/index.js +++ b/modules/claim/front/summary/index.js @@ -7,7 +7,7 @@ class Controller { } getSummary() { - this.$http.get(`/claim/api/Claims/${this.claim.id}/getSummary`).then(response => { + this.$http.get(`api/Claims/${this.claim.id}/getSummary`).then(response => { this.summary = response.data; }); } diff --git a/modules/claim/front/summary/index.spec.js b/modules/claim/front/summary/index.spec.js index c56b91251..b9583e81c 100644 --- a/modules/claim/front/summary/index.spec.js +++ b/modules/claim/front/summary/index.spec.js @@ -17,8 +17,8 @@ describe('Claim', () => { describe('getSummary()', () => { it('should perform a query to set summary', () => { - $httpBackend.when('GET', `/claim/api/Claims/1/getSummary`).respond(200, 24); - $httpBackend.expect('GET', `/claim/api/Claims/1/getSummary`); + $httpBackend.when('GET', `api/Claims/1/getSummary`).respond(200, 24); + $httpBackend.expect('GET', `api/Claims/1/getSummary`); controller.getSummary(); $httpBackend.flush(); diff --git a/modules/client/front/address/create/index.html b/modules/client/front/address/create/index.html index 0240aceb5..fc89c14a4 100644 --- a/modules/client/front/address/create/index.html +++ b/modules/client/front/address/create/index.html @@ -1,6 +1,6 @@ @@ -85,7 +85,7 @@ diff --git a/modules/client/front/address/index/index.js b/modules/client/front/address/index/index.js index 96859a0c0..8e1409abe 100644 --- a/modules/client/front/address/index/index.js +++ b/modules/client/front/address/index/index.js @@ -45,7 +45,7 @@ class Controller { } setDefault(address) { - let query = `/client/api/Clients/${this.$stateParams.id}`; + let query = `api/Clients/${this.$stateParams.id}`; let params = {defaultAddressFk: address.id}; this.$http.patch(query, params).then(res => { if (res.data) { diff --git a/modules/client/front/address/index/index.spec.js b/modules/client/front/address/index/index.spec.js index 5cb951745..16d58b910 100644 --- a/modules/client/front/address/index/index.spec.js +++ b/modules/client/front/address/index/index.spec.js @@ -29,8 +29,8 @@ describe('Client', () => { let data = {defaultAddressFk: address.id}; let expectedResult = {defaultAddressFk: address.id}; - $httpBackend.when('PATCH', `/client/api/Clients/1`, data).respond(200, expectedResult); - $httpBackend.expect('PATCH', `/client/api/Clients/1`, data); + $httpBackend.when('PATCH', `api/Clients/1`, data).respond(200, expectedResult); + $httpBackend.expect('PATCH', `api/Clients/1`, data); controller.setDefault(address); $httpBackend.flush(); diff --git a/modules/client/front/balance/create/index.html b/modules/client/front/balance/create/index.html index 4cf769d4f..1fc44c577 100644 --- a/modules/client/front/balance/create/index.html +++ b/modules/client/front/balance/create/index.html @@ -2,7 +2,7 @@ vn-id="dialog" class="modal-form"> - +
New payment
diff --git a/modules/client/front/balance/create/index.js b/modules/client/front/balance/create/index.js index 6d028e885..ea3ab3391 100644 --- a/modules/client/front/balance/create/index.js +++ b/modules/client/front/balance/create/index.js @@ -62,7 +62,7 @@ class Controller { } }; - let query = `/client/api/ClientRisks?filter=${JSON.stringify(filter)}`; + let query = `api/ClientRisks?filter=${JSON.stringify(filter)}`; this.$http.get(query).then(res => { this.receipt.amountPaid = (res.data.length && res.data[0].amount) || null; }); @@ -77,7 +77,7 @@ class Controller { } save() { - let query = `/client/api/receipts`; + let query = `api/receipts`; this.$http.post(query, this.receipt).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.hide(); diff --git a/modules/client/front/balance/index/index.html b/modules/client/front/balance/index/index.html index 045eb1f80..d98c14eb1 100644 --- a/modules/client/front/balance/index/index.html +++ b/modules/client/front/balance/index/index.html @@ -1,13 +1,13 @@ @@ -20,7 +20,7 @@ vn-id="company" field="$ctrl.companyFk" on-change="$ctrl.setOrder(value)" - url="/client/api/Companies" + url="api/Companies" show-field="code" value-field="id" label="Select company"> diff --git a/modules/client/front/balance/index/index.js b/modules/client/front/balance/index/index.js index 5611e9460..7de0dd2ef 100644 --- a/modules/client/front/balance/index/index.js +++ b/modules/client/front/balance/index/index.js @@ -45,7 +45,7 @@ class Controller { if (!value) return; const params = {filter: this.filter}; - this.$http.get(`/client/api/ClientRisks`, {params}).then(response => { + this.$http.get(`api/ClientRisks`, {params}).then(response => { if (response.data) { this.clientRisks = response.data; diff --git a/modules/client/front/balance/index/index.spec.js b/modules/client/front/balance/index/index.spec.js index 11a9766b4..7d5568107 100644 --- a/modules/client/front/balance/index/index.spec.js +++ b/modules/client/front/balance/index/index.spec.js @@ -31,8 +31,8 @@ describe('Client', () => { ]; const params = {filter: controller.filter}; let serializedParams = $httpParamSerializer(params); - $httpBackend.when('GET', `/client/api/ClientRisks?${serializedParams}`).respond(balances); - $httpBackend.expect('GET', `/client/api/ClientRisks?${serializedParams}`); + $httpBackend.when('GET', `api/ClientRisks?${serializedParams}`).respond(balances); + $httpBackend.expect('GET', `api/ClientRisks?${serializedParams}`); controller.balances = balances; $httpBackend.flush(); diff --git a/modules/client/front/basic-data/index.html b/modules/client/front/basic-data/index.html index f994d1905..d168e8b1f 100644 --- a/modules/client/front/basic-data/index.html +++ b/modules/client/front/basic-data/index.html @@ -1,4 +1,4 @@ - +
diff --git a/modules/client/front/billing-data/index.html b/modules/client/front/billing-data/index.html index d923123b7..9497ba6a7 100644 --- a/modules/client/front/billing-data/index.html +++ b/modules/client/front/billing-data/index.html @@ -1,4 +1,4 @@ - +
@@ -33,7 +33,7 @@ diff --git a/modules/client/front/billing-data/index.js b/modules/client/front/billing-data/index.js index edd6db654..13dc23eeb 100644 --- a/modules/client/front/billing-data/index.js +++ b/modules/client/front/billing-data/index.js @@ -62,7 +62,7 @@ export default class Controller { if (!this.newBankEntity.bic) throw new Error(`Swift / BIC can't be empty`); - this.$http.post(`/client/api/BankEntities`, this.newBankEntity).then(response => { + this.$http.post(`api/BankEntities`, this.newBankEntity).then(response => { if (response.data) this.client.bankEntityFk = response.data.id; }); @@ -91,7 +91,7 @@ export default class Controller { if (this.ibanCountry != 'ES') return; let json = encodeURIComponent(JSON.stringify(filter)); - this.$http.get(`/client/api/BankEntities?filter=${json}`).then(response => { + this.$http.get(`api/BankEntities?filter=${json}`).then(response => { const hasData = response.data && response.data[0]; if (hasData) diff --git a/modules/client/front/billing-data/index.spec.js b/modules/client/front/billing-data/index.spec.js index 4a53f9a06..689ddc882 100644 --- a/modules/client/front/billing-data/index.spec.js +++ b/modules/client/front/billing-data/index.spec.js @@ -80,8 +80,8 @@ describe('Client', () => { id: 999 }; controller.newBankEntity = newBankEntity; - $httpBackend.when('POST', '/client/api/BankEntities').respond('done'); - $httpBackend.expectPOST('/client/api/BankEntities', newBankEntity); + $httpBackend.when('POST', 'api/BankEntities').respond('done'); + $httpBackend.expectPOST('api/BankEntities', newBankEntity); controller.onBankEntityResponse('ACCEPT'); $httpBackend.flush(); }); @@ -94,8 +94,8 @@ describe('Client', () => { let expectedFilter = {where: {id: 2100}}; let json = encodeURIComponent(JSON.stringify(expectedFilter)); - $httpBackend.when('GET', `/client/api/BankEntities?filter=${json}`).respond('done'); - $httpBackend.expect('GET', `/client/api/BankEntities?filter=${json}`); + $httpBackend.when('GET', `api/BankEntities?filter=${json}`).respond('done'); + $httpBackend.expect('GET', `api/BankEntities?filter=${json}`); controller.autofillBic(); $httpBackend.flush(); @@ -108,8 +108,8 @@ describe('Client', () => { let expectedFilter = {where: {id: 128}}; let json = encodeURIComponent(JSON.stringify(expectedFilter)); - $httpBackend.when('GET', `/client/api/BankEntities?filter=${json}`).respond([{id: 128}]); - $httpBackend.expect('GET', `/client/api/BankEntities?filter=${json}`); + $httpBackend.when('GET', `api/BankEntities?filter=${json}`).respond([{id: 128}]); + $httpBackend.expect('GET', `api/BankEntities?filter=${json}`); controller.autofillBic(); $httpBackend.flush(); diff --git a/modules/client/front/card/index.js b/modules/client/front/card/index.js index a17a01883..33f51364c 100644 --- a/modules/client/front/card/index.js +++ b/modules/client/front/card/index.js @@ -13,7 +13,7 @@ export default class Controller { } getCard() { - this.$http.get(`/client/api/Clients/${this.$stateParams.id}/getCard`).then(response => { + this.$http.get(`api/Clients/${this.$stateParams.id}/getCard`).then(response => { this.client = response.data; }); } diff --git a/modules/client/front/contact/index.html b/modules/client/front/contact/index.html index b66eb782e..6ae1c0c03 100644 --- a/modules/client/front/contact/index.html +++ b/modules/client/front/contact/index.html @@ -1,6 +1,6 @@ + { clientFk: 101 }; - $httpBackend.whenPOST(`/client/api/creditClassifications/createWithInsurance`, newData).respond(200, true); - $httpBackend.expectPOST(`/client/api/creditClassifications/createWithInsurance`, newData); + $httpBackend.whenPOST(`api/creditClassifications/createWithInsurance`, newData).respond(200, true); + $httpBackend.expectPOST(`api/creditClassifications/createWithInsurance`, newData); controller.onSubmit(); $httpBackend.flush(); }); diff --git a/modules/client/front/credit-insurance/index/index.js b/modules/client/front/credit-insurance/index/index.js index 6d6994a9a..4d108428e 100644 --- a/modules/client/front/credit-insurance/index/index.js +++ b/modules/client/front/credit-insurance/index/index.js @@ -30,7 +30,7 @@ class Controller { }; filter = encodeURIComponent(JSON.stringify(filter)); - let query = `/client/api/CreditClassifications?filter=${filter}`; + let query = `api/CreditClassifications?filter=${filter}`; this.$http.get(query).then(res => { if (res.data) this.classifications = res.data; @@ -58,7 +58,7 @@ class Controller { returnDialog(response) { if (response === 'ACCEPT') { let params = {finished: Date.now()}; - this.$http.patch(`/client/api/CreditClassifications/${this.classificationId}`, params).then(() => { + this.$http.patch(`api/CreditClassifications/${this.classificationId}`, params).then(() => { this._getClassifications(this.client.id); }); } diff --git a/modules/client/front/credit-insurance/index/index.spec.js b/modules/client/front/credit-insurance/index/index.spec.js index 5bf33faca..9be3f0641 100644 --- a/modules/client/front/credit-insurance/index/index.spec.js +++ b/modules/client/front/credit-insurance/index/index.spec.js @@ -18,7 +18,7 @@ describe('Client', () => { describe('_getClassifications()', () => { it('should perform a GET query to define the classifications property in the controller', () => { let res = ['some classifications']; - let query = '/client/api/CreditClassifications?filter=%7B%22order%22%3A%22finished%20ASC%2C%20started%20DESC%22%2C%22include%22%3A%5B%7B%22relation%22%3A%22insurances%22%2C%22scope%22%3A%7B%22fields%22%3A%5B%22id%22%2C%22credit%22%2C%22created%22%2C%22grade%22%5D%2C%22order%22%3A%22created%20DESC%22%2C%22limit%22%3A2%7D%7D%5D%2C%22where%22%3A%7B%7D%7D'; + let query = 'api/CreditClassifications?filter=%7B%22order%22%3A%22finished%20ASC%2C%20started%20DESC%22%2C%22include%22%3A%5B%7B%22relation%22%3A%22insurances%22%2C%22scope%22%3A%7B%22fields%22%3A%5B%22id%22%2C%22credit%22%2C%22created%22%2C%22grade%22%5D%2C%22order%22%3A%22created%20DESC%22%2C%22limit%22%3A2%7D%7D%5D%2C%22where%22%3A%7B%7D%7D'; $httpBackend.whenGET(query).respond(res); $httpBackend.expectGET(query); @@ -76,8 +76,8 @@ describe('Client', () => { it('should call the returnDialog method and perform a PATCH query, then call _getClassifications method', () => { spyOn(controller, '_getClassifications'); controller.classificationId = 1; - $httpBackend.when('PATCH', `/client/api/CreditClassifications/1`).respond(200); - $httpBackend.expect('PATCH', `/client/api/CreditClassifications/1`); + $httpBackend.when('PATCH', `api/CreditClassifications/1`).respond(200); + $httpBackend.expect('PATCH', `api/CreditClassifications/1`); controller.returnDialog('ACCEPT'); $httpBackend.flush(); diff --git a/modules/client/front/credit-insurance/insurance/create/index.html b/modules/client/front/credit-insurance/insurance/create/index.html index f6770b29a..7e93eeabd 100644 --- a/modules/client/front/credit-insurance/insurance/create/index.html +++ b/modules/client/front/credit-insurance/insurance/create/index.html @@ -1,4 +1,4 @@ - + diff --git a/modules/client/front/credit-insurance/insurance/index/index.js b/modules/client/front/credit-insurance/insurance/index/index.js index cfb8a807c..558cbab3a 100644 --- a/modules/client/front/credit-insurance/insurance/index/index.js +++ b/modules/client/front/credit-insurance/insurance/index/index.js @@ -19,7 +19,7 @@ class Controller { }; filter = encodeURIComponent(JSON.stringify(filter)); - let query = `/client/api/CreditClassifications?filter=${filter}`; + let query = `api/CreditClassifications?filter=${filter}`; this.$http.get(query).then(res => { if (res.data) this.isClosed = res.data[0].finished != null; diff --git a/modules/client/front/credit-insurance/insurance/index/index.spec.js b/modules/client/front/credit-insurance/insurance/index/index.spec.js index cb1d3d4ff..b7539c1c9 100644 --- a/modules/client/front/credit-insurance/insurance/index/index.spec.js +++ b/modules/client/front/credit-insurance/insurance/index/index.spec.js @@ -18,7 +18,7 @@ describe('Client', () => { describe('$onInit()', () => { it('should perform a query to GET credit the credit classification', () => { let res = [{finished: 'some value'}]; - let query = '/client/api/CreditClassifications?filter=%7B%22fields%22%3A%5B%22finished%22%5D%2C%22where%22%3A%7B%22id%22%3A1%7D%7D'; + let query = 'api/CreditClassifications?filter=%7B%22fields%22%3A%5B%22finished%22%5D%2C%22where%22%3A%7B%22id%22%3A1%7D%7D'; $httpBackend.whenGET(query).respond(res); $httpBackend.expectGET(query); diff --git a/modules/client/front/credit/create/index.html b/modules/client/front/credit/create/index.html index 02a55a8b7..d9db46f3c 100644 --- a/modules/client/front/credit/create/index.html +++ b/modules/client/front/credit/create/index.html @@ -1,4 +1,4 @@ - + { + this.$http.get(`api/Recoveries/${this.$state.params.id}/hasActiveRecovery`).then(res => { let activeRecovery = res.data; if (activeRecovery) this.$scope.confirmation.show(); diff --git a/modules/client/front/credit/create/index.spec.js b/modules/client/front/credit/create/index.spec.js index 0ac97275e..39d1332b0 100644 --- a/modules/client/front/credit/create/index.spec.js +++ b/modules/client/front/credit/create/index.spec.js @@ -37,16 +37,16 @@ describe('Client', () => { describe('onSubmit()', () => { it('should perform a query to check (GET) if the client has an active recovery', () => { - $httpBackend.whenGET(`/client/api/Recoveries/101/hasActiveRecovery`).respond(true); - $httpBackend.expectGET(`/client/api/Recoveries/101/hasActiveRecovery`); + $httpBackend.whenGET(`api/Recoveries/101/hasActiveRecovery`).respond(true); + $httpBackend.expectGET(`api/Recoveries/101/hasActiveRecovery`); controller.onSubmit(); $httpBackend.flush(); }); it('should call show() method when the client have a recovery', () => { spyOn(controller.$scope.confirmation, 'show'); - $httpBackend.whenGET(`/client/api/Recoveries/101/hasActiveRecovery`).respond(true); - $httpBackend.expectGET(`/client/api/Recoveries/101/hasActiveRecovery`); + $httpBackend.whenGET(`api/Recoveries/101/hasActiveRecovery`).respond(true); + $httpBackend.expectGET(`api/Recoveries/101/hasActiveRecovery`); controller.onSubmit(); $httpBackend.flush(); @@ -55,8 +55,8 @@ describe('Client', () => { it('should call addCredit() method when the client doesnt have a recovery', () => { spyOn(controller, 'addCredit'); - $httpBackend.whenGET(`/client/api/Recoveries/101/hasActiveRecovery`).respond(false); - $httpBackend.expectGET(`/client/api/Recoveries/101/hasActiveRecovery`); + $httpBackend.whenGET(`api/Recoveries/101/hasActiveRecovery`).respond(false); + $httpBackend.expectGET(`api/Recoveries/101/hasActiveRecovery`); controller.onSubmit(); $httpBackend.flush(); diff --git a/modules/client/front/credit/index/index.html b/modules/client/front/credit/index/index.html index 9757f8045..cbf456ded 100644 --- a/modules/client/front/credit/index/index.html +++ b/modules/client/front/credit/index/index.html @@ -1,6 +1,6 @@ { this.client = response.data; this.canceler = null; diff --git a/modules/client/front/descriptor-popover/index.spec.js b/modules/client/front/descriptor-popover/index.spec.js index 6d8e771a6..2204e6bdb 100644 --- a/modules/client/front/descriptor-popover/index.spec.js +++ b/modules/client/front/descriptor-popover/index.spec.js @@ -70,8 +70,8 @@ describe('Client', () => { controller.clientFk = 1; controller.canceler = null; let response = {}; - $httpBackend.when('GET', `/client/api/Clients/${controller._clientFk}/getCard`).respond(response); - $httpBackend.expect('GET', `/client/api/Clients/${controller._clientFk}/getCard`); + $httpBackend.when('GET', `api/Clients/${controller._clientFk}/getCard`).respond(response); + $httpBackend.expect('GET', `api/Clients/${controller._clientFk}/getCard`); controller.getCard(); $httpBackend.flush(); diff --git a/modules/client/front/dms/index/index.html b/modules/client/front/dms/index/index.html index c147a74e0..21ee93386 100644 --- a/modules/client/front/dms/index/index.html +++ b/modules/client/front/dms/index/index.html @@ -1,6 +1,6 @@ + { if (res.data) this.vnApp.showMessage(this.translate.instant('Equivalent tax spreaded')); diff --git a/modules/client/front/fiscal-data/index.spec.js b/modules/client/front/fiscal-data/index.spec.js index 63834f1c8..cfdc17457 100644 --- a/modules/client/front/fiscal-data/index.spec.js +++ b/modules/client/front/fiscal-data/index.spec.js @@ -20,8 +20,8 @@ describe('Client', () => { describe('returnDialogEt()', () => { it('should request to patch the propagation of tax status', () => { controller.client = {id: 123, isEqualizated: false}; - $httpBackend.when('PATCH', `/client/api/Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}).respond('done'); - $httpBackend.expectPATCH(`/client/api/Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}); + $httpBackend.when('PATCH', `api/Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}).respond('done'); + $httpBackend.expectPATCH(`api/Clients/${controller.client.id}/addressesPropagateRe`, {isEqualizated: controller.client.isEqualizated}); controller.returnDialogEt('ACCEPT'); $httpBackend.flush(); }); diff --git a/modules/client/front/greuge/create/index.html b/modules/client/front/greuge/create/index.html index 7a6ea451b..897bbf3fd 100644 --- a/modules/client/front/greuge/create/index.html +++ b/modules/client/front/greuge/create/index.html @@ -1,4 +1,4 @@ - + diff --git a/modules/client/front/greuge/index/index.html b/modules/client/front/greuge/index/index.html index 537e67602..02532fa0b 100644 --- a/modules/client/front/greuge/index/index.html +++ b/modules/client/front/greuge/index/index.html @@ -1,13 +1,13 @@ diff --git a/modules/client/front/index/index.html b/modules/client/front/index/index.html index d4bbcd198..2409a1fc7 100644 --- a/modules/client/front/index/index.html +++ b/modules/client/front/index/index.html @@ -1,6 +1,6 @@ + this.$scope.model.refresh() ); } diff --git a/modules/client/front/sample/create/index.html b/modules/client/front/sample/create/index.html index e8e56ba6f..73992aa70 100644 --- a/modules/client/front/sample/create/index.html +++ b/modules/client/front/sample/create/index.html @@ -1,4 +1,4 @@ - + @@ -23,7 +23,7 @@ vn-one field="$ctrl.clientSample.companyFk" model="ClientSample.companyFk" - url="/client/api/Companies" + url="api/Companies" show-field="code" value-field="id" label="Company" diff --git a/modules/client/front/sample/index/index.html b/modules/client/front/sample/index/index.html index 48543d135..99f6adc22 100644 --- a/modules/client/front/sample/index/index.html +++ b/modules/client/front/sample/index/index.html @@ -1,6 +1,6 @@ { + this.$http.post(`api/Sms/send`, this.sms).then(res => { this.vnApp.showMessage(this.$translate.instant('SMS sent!')); if (res.data) this.emit('send', {response: res.data}); diff --git a/modules/client/front/sms/index.spec.js b/modules/client/front/sms/index.spec.js index 3cb37093f..5a343a4a6 100644 --- a/modules/client/front/sms/index.spec.js +++ b/modules/client/front/sms/index.spec.js @@ -23,8 +23,8 @@ describe('Client', () => { controller.sms = {destinationFk: 101, destination: 111111111, message: 'My SMS'}; spyOn(controller.vnApp, 'showMessage'); - $httpBackend.when('POST', `/client/api/Sms/send`, params).respond(200, params); - $httpBackend.expect('POST', `/client/api/Sms/send`, params).respond(params); + $httpBackend.when('POST', `api/Sms/send`, params).respond(200, params); + $httpBackend.expect('POST', `api/Sms/send`, params).respond(params); controller.onResponse('ACCEPT'); $httpBackend.flush(); diff --git a/modules/client/front/summary/index.js b/modules/client/front/summary/index.js index a35f330f1..6263234d8 100644 --- a/modules/client/front/summary/index.js +++ b/modules/client/front/summary/index.js @@ -10,7 +10,7 @@ class Controller { if (!this.client) return; - this.$http.get(`/client/api/Clients/${this.client.id}/summary`).then(res => { + this.$http.get(`api/Clients/${this.client.id}/summary`).then(res => { if (res && res.data) { this.summary = res.data; diff --git a/modules/client/front/summary/index.spec.js b/modules/client/front/summary/index.spec.js index 71f78dad5..4c67e2bfe 100644 --- a/modules/client/front/summary/index.spec.js +++ b/modules/client/front/summary/index.spec.js @@ -20,8 +20,8 @@ describe('Client', () => { let res = {name: 'Superman', classifications: []}; spyOn(controller, 'sumRisk'); - $httpBackend.when('GET', `/client/api/Clients/101/summary`).respond(200, res); - $httpBackend.expect('GET', `/client/api/Clients/101/summary`); + $httpBackend.when('GET', `api/Clients/101/summary`).respond(200, res); + $httpBackend.expect('GET', `api/Clients/101/summary`); controller.$onChanges(); $httpBackend.flush(); diff --git a/modules/client/front/web-access/index.html b/modules/client/front/web-access/index.html index 40f9f77b9..2302b07c1 100644 --- a/modules/client/front/web-access/index.html +++ b/modules/client/front/web-access/index.html @@ -1,6 +1,6 @@ diff --git a/modules/client/front/web-access/index.js b/modules/client/front/web-access/index.js index 6282db5fb..2ef87d6dd 100644 --- a/modules/client/front/web-access/index.js +++ b/modules/client/front/web-access/index.js @@ -20,7 +20,7 @@ export default class Controller { isCustomer() { if (this.client.id) { - this.$http.get(`/client/api/Clients/${this.client.id}/hasCustomerRole`).then(res => { + this.$http.get(`api/Clients/${this.client.id}/hasCustomerRole`).then(res => { this.canChangePassword = res.data && res.data.isCustomer; }); } @@ -28,7 +28,7 @@ export default class Controller { checkConditions() { if (this.client.id) { - this.$http.get(`/client/api/Clients/${this.client.id}/isValidClient`).then(res => { + this.$http.get(`api/Clients/${this.client.id}/isValidClient`).then(res => { this.canEnableCheckBox = res.data; }); } @@ -51,7 +51,7 @@ export default class Controller { password: this.newPassword }; - this.$http.patch(`/client/api/Accounts/${this.client.id}`, account).then(res => { + this.$http.patch(`api/Accounts/${this.client.id}`, account).then(res => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); }); } catch (e) { diff --git a/modules/client/front/web-access/index.spec.js b/modules/client/front/web-access/index.spec.js index 5e24d9182..6be0bde5c 100644 --- a/modules/client/front/web-access/index.spec.js +++ b/modules/client/front/web-access/index.spec.js @@ -35,8 +35,8 @@ describe('Component VnClientWebAccess', () => { controller.client = {id: '1234'}; controller.isCustomer(); - $httpBackend.when('GET', `/client/api/Clients/${controller.client.id}/hasCustomerRole`).respond('ok'); - $httpBackend.expectGET(`/client/api/Clients/${controller.client.id}/hasCustomerRole`); + $httpBackend.when('GET', `api/Clients/${controller.client.id}/hasCustomerRole`).respond('ok'); + $httpBackend.expectGET(`api/Clients/${controller.client.id}/hasCustomerRole`); $httpBackend.flush(); }); }); @@ -47,8 +47,8 @@ describe('Component VnClientWebAccess', () => { expect(controller.canEnableCheckBox).toBeTruthy(); - $httpBackend.when('GET', `/client/api/Clients/${controller.client.id}/isValidClient`).respond(false); - $httpBackend.expectGET(`/client/api/Clients/${controller.client.id}/isValidClient`); + $httpBackend.when('GET', `api/Clients/${controller.client.id}/isValidClient`).respond(false); + $httpBackend.expectGET(`api/Clients/${controller.client.id}/isValidClient`); controller.checkConditions(); $httpBackend.flush(); @@ -73,8 +73,8 @@ describe('Component VnClientWebAccess', () => { controller.newPassword = 'm24x8'; controller.repeatPassword = 'm24x8'; controller.canChangePassword = true; - $httpBackend.when('PATCH', '/client/api/Accounts/1234').respond('done'); - $httpBackend.expectPATCH('/client/api/Accounts/1234', {password: 'm24x8'}); + $httpBackend.when('PATCH', 'api/Accounts/1234').respond('done'); + $httpBackend.expectPATCH('api/Accounts/1234', {password: 'm24x8'}); controller.onPassChange('ACCEPT'); $httpBackend.flush(); }); diff --git a/modules/client/front/web-payment/index.html b/modules/client/front/web-payment/index.html index cf7e8fbc2..e7f5c5191 100644 --- a/modules/client/front/web-payment/index.html +++ b/modules/client/front/web-payment/index.html @@ -1,6 +1,6 @@ diff --git a/modules/client/front/web-payment/index.js b/modules/client/front/web-payment/index.js index 0ec1a6858..8d15ad9a4 100644 --- a/modules/client/front/web-payment/index.js +++ b/modules/client/front/web-payment/index.js @@ -9,7 +9,7 @@ class Controller { } confirm(transaction) { - const path = '/client/api/Clients/confirmTransaction'; + const path = 'api/Clients/confirmTransaction'; let data = {id: transaction.id}; this.$http.post(path, data).then(res => { this.$scope.model.refresh(); diff --git a/modules/client/front/web-payment/index.spec.js b/modules/client/front/web-payment/index.spec.js index 861bb3da1..c998d0fa0 100644 --- a/modules/client/front/web-payment/index.spec.js +++ b/modules/client/front/web-payment/index.spec.js @@ -23,7 +23,7 @@ describe('Component vnClientWebPayment', () => { describe('confirm()', () => { it(`should confirm a transaction`, () => { let transaction = {id: 1}; - let query = '/client/api/Clients/confirmTransaction'; + let query = 'api/Clients/confirmTransaction'; controller.confirm(transaction); $httpBackend.when('POST', query, transaction).respond('ok'); diff --git a/modules/invoiceOut/front/descriptor/index.js b/modules/invoiceOut/front/descriptor/index.js index bd9891193..4bdad975e 100644 --- a/modules/invoiceOut/front/descriptor/index.js +++ b/modules/invoiceOut/front/descriptor/index.js @@ -67,7 +67,7 @@ class Controller { deleteInvoiceOut(response) { if (response === 'ACCEPT') { - const query = `/invoiceOut/api/InvoiceOuts/${this.invoiceOut.id}/delete`; + const query = `api/InvoiceOuts/${this.invoiceOut.id}/delete`; this.$http.post(query).then(() => { this.vnApp.showSuccess(this.$translate.instant('InvoiceOut deleted')); this.$state.go('invoiceOut.index'); @@ -77,7 +77,7 @@ class Controller { bookInvoiceOut(response) { if (response === 'ACCEPT') { - const query = `/invoiceOut/api/InvoiceOuts/${this.invoiceOut.ref}/book`; + const query = `api/InvoiceOuts/${this.invoiceOut.ref}/book`; this.$http.post(query).then(() => { this.vnApp.showSuccess(this.$translate.instant('InvoiceOut booked')); this.$state.reload(); diff --git a/modules/item/front/barcode/index.html b/modules/item/front/barcode/index.html index 14bde170b..74af3e1ae 100644 --- a/modules/item/front/barcode/index.html +++ b/modules/item/front/barcode/index.html @@ -1,6 +1,6 @@ @@ -19,7 +19,7 @@ info="Full name calculates based on tags 1-3. Is not recommended to change it manually"> @@ -33,7 +33,7 @@ vn-one initial-data="$ctrl.botanical.specie" field="$ctrl.botanical.specieFk" - url="/item/api/species" + url="api/species" show-field="latin_species_name" value-field="specie_id" label="Species"> diff --git a/modules/item/front/botanical/index.js b/modules/item/front/botanical/index.js index 92cea41aa..2d36fce7f 100644 --- a/modules/item/front/botanical/index.js +++ b/modules/item/front/botanical/index.js @@ -14,7 +14,7 @@ class Controller { where: {itemFk: this.$state.params.id}, include: [{relation: 'genus'}, {relation: 'specie'}] }; - this.$http.get(`/item/api/ItemBotanicals?filter=${JSON.stringify(filter)}`) + this.$http.get(`api/ItemBotanicals?filter=${JSON.stringify(filter)}`) .then(res => { if (res.data.length) this.botanical = res.data[0]; diff --git a/modules/item/front/botanical/index.spec.js b/modules/item/front/botanical/index.spec.js index 879701ddd..20140f622 100644 --- a/modules/item/front/botanical/index.spec.js +++ b/modules/item/front/botanical/index.spec.js @@ -22,8 +22,8 @@ describe('ItemBotanical', () => { describe('_getBotanical()', () => { it('should request to patch the propagation of botanical status', () => { - $httpBackend.whenGET('/item/api/ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}').respond({data: 'item'}); - $httpBackend.expectGET('/item/api/ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}'); + $httpBackend.whenGET('api/ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}').respond({data: 'item'}); + $httpBackend.expectGET('api/ItemBotanicals?filter={"where":{"itemFk":123},"include":[{"relation":"genus"},{"relation":"specie"}]}'); controller.$onInit(); $httpBackend.flush(); }); diff --git a/modules/item/front/card/index.js b/modules/item/front/card/index.js index 9e11a7045..7f89c8d95 100644 --- a/modules/item/front/card/index.js +++ b/modules/item/front/card/index.js @@ -12,7 +12,7 @@ class Controller { } getCard() { - this.$http.get(`/item/api/Items/${this.$stateParams.id}/getCard`).then(response => { + this.$http.get(`api/Items/${this.$stateParams.id}/getCard`).then(response => { this.item = response.data; }); } diff --git a/modules/item/front/card/index.spec.js b/modules/item/front/card/index.spec.js index 6d4fa9832..01895caac 100644 --- a/modules/item/front/card/index.spec.js +++ b/modules/item/front/card/index.spec.js @@ -21,8 +21,8 @@ describe('Item', () => { describe('getCard()', () => { it('should request to set the item into the controller', () => { let response = {id: 123}; - $httpBackend.when('GET', `/item/api/Items/123/getCard`).respond(response); - $httpBackend.expect('GET', `/item/api/Items/123/getCard`); + $httpBackend.when('GET', `api/Items/123/getCard`).respond(response); + $httpBackend.expect('GET', `api/Items/123/getCard`); controller.getCard(); $httpBackend.flush(); diff --git a/modules/item/front/create/index.html b/modules/item/front/create/index.html index 7cb96a024..17dc61743 100644 --- a/modules/item/front/create/index.html +++ b/modules/item/front/create/index.html @@ -1,4 +1,4 @@ - + { this.item = response.data; this.canceler = null; diff --git a/modules/item/front/descriptor-popover/index.spec.js b/modules/item/front/descriptor-popover/index.spec.js index ffe744218..76c083a72 100644 --- a/modules/item/front/descriptor-popover/index.spec.js +++ b/modules/item/front/descriptor-popover/index.spec.js @@ -70,8 +70,8 @@ describe('Item', () => { controller.itemFk = 1; controller.canceler = null; let response = {}; - $httpBackend.when('GET', `/item/api/Items/${controller._itemFk}/getCard`).respond(response); - $httpBackend.expect('GET', `/item/api/Items/${controller._itemFk}/getCard`); + $httpBackend.when('GET', `api/Items/${controller._itemFk}/getCard`).respond(response); + $httpBackend.expect('GET', `api/Items/${controller._itemFk}/getCard`); controller.getCard(); $httpBackend.flush(); diff --git a/modules/item/front/descriptor/index.js b/modules/item/front/descriptor/index.js index da94aacb6..668d7c0b8 100644 --- a/modules/item/front/descriptor/index.js +++ b/modules/item/front/descriptor/index.js @@ -51,7 +51,7 @@ class Controller { warehouseFk: warehouseFk } }; - this.$http.get(`/item/api/Items/${this._item.id}/getVisibleAvailable`, options).then(response => { + this.$http.get(`api/Items/${this._item.id}/getVisibleAvailable`, options).then(response => { this.available = response.data.available; this.visible = response.data.visible; }); @@ -76,7 +76,7 @@ class Controller { saveRegularize(response) { if (response == 'ACCEPT') { - this.$http.post(`/item/api/Items/regularize`, { + this.$http.post(`api/Items/regularize`, { itemFk: this.item.id, quantity: this.quantity, warehouseFk: this.warehouseFk diff --git a/modules/item/front/diary/index.html b/modules/item/front/diary/index.html index 47506eed9..9f55b483e 100644 --- a/modules/item/front/diary/index.html +++ b/modules/item/front/diary/index.html @@ -1,6 +1,6 @@ @@ -11,7 +11,7 @@ { + this.$http.post(`api/Items/${this.itemSelected.id}/clone`).then(res => { if (res && res.data && res.data.id) this.$state.go('item.card.tags', {id: res.data.id}); }); diff --git a/modules/item/front/index/index.spec.js b/modules/item/front/index/index.spec.js index b90c62b9b..613e59556 100644 --- a/modules/item/front/index/index.spec.js +++ b/modules/item/front/index/index.spec.js @@ -47,8 +47,8 @@ describe('Item', () => { let response = 'ACCEPT'; controller.itemSelected = {id: 1}; - $httpBackend.when('POST', `/item/api/Items/1/clone`).respond({id: 99}); - $httpBackend.expect('POST', `/item/api/Items/1/clone`); + $httpBackend.when('POST', `api/Items/1/clone`).respond({id: 99}); + $httpBackend.expect('POST', `api/Items/1/clone`); controller.onCloneAccept(response); $httpBackend.flush(); diff --git a/modules/item/front/last-entries/index.html b/modules/item/front/last-entries/index.html index f6548079b..229c0cd5e 100644 --- a/modules/item/front/last-entries/index.html +++ b/modules/item/front/last-entries/index.html @@ -1,6 +1,6 @@ diff --git a/modules/item/front/niche/index.html b/modules/item/front/niche/index.html index e87034577..81d342ae3 100644 --- a/modules/item/front/niche/index.html +++ b/modules/item/front/niche/index.html @@ -1,6 +1,6 @@ +
@@ -14,7 +14,7 @@ { + this.$http.get(`api/Items/${this.item.id}/getSummary`).then(response => { this.summary = response.data; }); } diff --git a/modules/item/front/summary/index.spec.js b/modules/item/front/summary/index.spec.js index 99a688554..31158fb18 100644 --- a/modules/item/front/summary/index.spec.js +++ b/modules/item/front/summary/index.spec.js @@ -18,8 +18,8 @@ describe('Item', () => { describe('getSummary()', () => { it('should perform a query to set summary', () => { let data = {id: 1, name: 'Gem of mind'}; - $httpBackend.when('GET', `/item/api/Items/1/getSummary`).respond(200, data); - $httpBackend.expect('GET', `/item/api/Items/1/getSummary`); + $httpBackend.when('GET', `api/Items/1/getSummary`).respond(200, data); + $httpBackend.expect('GET', `api/Items/1/getSummary`); controller.getSummary(); $httpBackend.flush(); diff --git a/modules/item/front/tags/index.html b/modules/item/front/tags/index.html index ad50ebe64..56e932558 100644 --- a/modules/item/front/tags/index.html +++ b/modules/item/front/tags/index.html @@ -1,6 +1,6 @@ diff --git a/modules/item/front/tax/index.html b/modules/item/front/tax/index.html index 8be5adeae..b8e9374e1 100644 --- a/modules/item/front/tax/index.html +++ b/modules/item/front/tax/index.html @@ -1,5 +1,5 @@ diff --git a/modules/item/front/tax/index.js b/modules/item/front/tax/index.js index f4cc6f73e..b27f4a674 100644 --- a/modules/item/front/tax/index.js +++ b/modules/item/front/tax/index.js @@ -22,7 +22,7 @@ export default class Controller { }; let urlFilter = encodeURIComponent(JSON.stringify(filter)); - let url = `/item/api/Items/${this.$stateParams.id}/taxes?filter=${urlFilter}`; + let url = `api/Items/${this.$stateParams.id}/taxes?filter=${urlFilter}`; this.$http.get(url).then(json => { this.taxes = json.data; }); @@ -33,7 +33,7 @@ export default class Controller { for (let tax of this.taxes) data.push({id: tax.id, taxClassFk: tax.taxClassFk}); - let url = `/item/api/Items/updateTaxes`; + let url = `api/Items/updateTaxes`; this.$http.post(url, data).then( () => this.vnApp.showSuccess(this._.instant('Data saved!')) ); diff --git a/modules/item/front/tax/index.spec.js b/modules/item/front/tax/index.spec.js index 56c3b9306..6f1679041 100644 --- a/modules/item/front/tax/index.spec.js +++ b/modules/item/front/tax/index.spec.js @@ -31,8 +31,8 @@ describe('Item', () => { }; let response = [{id: 1, taxClassFk: 1}]; filter = encodeURIComponent(JSON.stringify(filter)); - $httpBackend.when('GET', `/item/api/Items/1/taxes?filter=${filter}`).respond(response); - $httpBackend.expect('GET', `/item/api/Items/1/taxes?filter=${filter}`); + $httpBackend.when('GET', `api/Items/1/taxes?filter=${filter}`).respond(response); + $httpBackend.expect('GET', `api/Items/1/taxes?filter=${filter}`); controller.$onInit(); $httpBackend.flush(); @@ -51,12 +51,12 @@ describe('Item', () => { }; let response = [{id: 1, taxClassFk: 1}]; filter = encodeURIComponent(JSON.stringify(filter)); - $httpBackend.when('GET', `/item/api/Items/1/taxes?filter=${filter}`).respond(response); + $httpBackend.when('GET', `api/Items/1/taxes?filter=${filter}`).respond(response); controller.$onInit(); $httpBackend.flush(); - $httpBackend.when('POST', `/item/api/Items/updateTaxes`).respond('ok'); - $httpBackend.expect('POST', `/item/api/Items/updateTaxes`); + $httpBackend.when('POST', `api/Items/updateTaxes`).respond('ok'); + $httpBackend.expect('POST', `api/Items/updateTaxes`); controller.submit(); $httpBackend.flush(); diff --git a/modules/order/front/basic-data/index.html b/modules/order/front/basic-data/index.html index 7a76d937f..ad2495e9f 100644 --- a/modules/order/front/basic-data/index.html +++ b/modules/order/front/basic-data/index.html @@ -1,4 +1,4 @@ - + { if (res.data && res.data.rows) { if (res.data.rows.length == 0) @@ -66,7 +66,7 @@ class Controller { } getTotal() { - let query = `/order/api/Orders/${this.$state.params.id}/getTotal`; + let query = `api/Orders/${this.$state.params.id}/getTotal`; this.$http.get(query).then(res => { if (res.data) this.order.total = res.data; diff --git a/modules/order/front/card/index.spec.js b/modules/order/front/card/index.spec.js index 232886abd..ade22b0e3 100644 --- a/modules/order/front/card/index.spec.js +++ b/modules/order/front/card/index.spec.js @@ -23,7 +23,7 @@ describe('Order', () => { it(`should make a query, save the data in order and call get order if the response has data`, () => { spyOn(controller, 'getTotal'); let json = encodeURIComponent(JSON.stringify(controller.filter)); - $httpBackend.expectGET(`/order/api/Orders/${controller.$state.params.id}?filter=${json}`).respond({rows: [1, 2, 3]}); + $httpBackend.expectGET(`api/Orders/${controller.$state.params.id}?filter=${json}`).respond({rows: [1, 2, 3]}); controller.getCard(); $httpBackend.flush(); @@ -34,7 +34,7 @@ describe('Order', () => { it(`should make a query and not call getTotal if the response is not defined`, () => { spyOn(controller, 'getTotal'); let json = encodeURIComponent(JSON.stringify(controller.filter)); - $httpBackend.expectGET(`/order/api/Orders/${controller.$state.params.id}?filter=${json}`).respond(undefined); + $httpBackend.expectGET(`api/Orders/${controller.$state.params.id}?filter=${json}`).respond(undefined); controller.getCard(); $httpBackend.flush(); @@ -45,7 +45,7 @@ describe('Order', () => { describe('getTotal()', () => { it(`should make a query and save the data in order.total`, () => { - $httpBackend.expectGET(`/order/api/Orders/${controller.$state.params.id}/getTotal`).respond('20M'); + $httpBackend.expectGET(`api/Orders/${controller.$state.params.id}/getTotal`).respond('20M'); controller.getTotal(); $httpBackend.flush(); @@ -53,7 +53,7 @@ describe('Order', () => { }); it(`should make a query and not save the respones if is not defined`, () => { - $httpBackend.expectGET(`/order/api/Orders/${controller.$state.params.id}/getTotal`).respond(); + $httpBackend.expectGET(`api/Orders/${controller.$state.params.id}/getTotal`).respond(); controller.getTotal(); $httpBackend.flush(); diff --git a/modules/order/front/catalog/index.html b/modules/order/front/catalog/index.html index 118a5cda8..e83b98b31 100644 --- a/modules/order/front/catalog/index.html +++ b/modules/order/front/catalog/index.html @@ -1,6 +1,6 @@ { + this.$http.post(`api/Orders/new`, params).then(res => { this.vnApp.showSuccess(this.translate.instant('Data saved!')); this.$state.go('order.card.catalog', {id: res.data}); }); diff --git a/modules/order/front/create/card.spec.js b/modules/order/front/create/card.spec.js index e09d95a00..5deff2dda 100644 --- a/modules/order/front/create/card.spec.js +++ b/modules/order/front/create/card.spec.js @@ -92,8 +92,8 @@ describe('Order', () => { spyOn(controller.vnApp, 'showSuccess'); spyOn(controller.$state, 'go'); - $httpBackend.when('POST', 'order/api/Orders/new', {landed: 101, addressId: 101, agencyModeId: 101}).respond(200, 1); - $httpBackend.expect('POST', 'order/api/Orders/new', {landed: 101, addressId: 101, agencyModeId: 101}); + $httpBackend.when('POST', 'api/Orders/new', {landed: 101, addressId: 101, agencyModeId: 101}).respond(200, 1); + $httpBackend.expect('POST', 'api/Orders/new', {landed: 101, addressId: 101, agencyModeId: 101}); controller.createOrder(); $httpBackend.flush(); diff --git a/modules/order/front/filter/index.html b/modules/order/front/filter/index.html index d4d8fd751..96c4c1840 100644 --- a/modules/order/front/filter/index.html +++ b/modules/order/front/filter/index.html @@ -1,6 +1,6 @@ diff --git a/modules/order/front/line/index.js b/modules/order/front/line/index.js index a3e9f77ad..38de2b878 100644 --- a/modules/order/front/line/index.js +++ b/modules/order/front/line/index.js @@ -33,7 +33,7 @@ class Controller { {relation: 'warehouse'}] }; filter = encodeURIComponent(JSON.stringify(filter)); - let query = `/order/api/OrderRows?filter=${filter}`; + let query = `api/OrderRows?filter=${filter}`; this.$http.get(query).then(res => { this.rows = res.data; @@ -41,7 +41,7 @@ class Controller { } getVAT() { - let query = `/order/api/Orders/${this.$state.params.id}/getVAT`; + let query = `api/Orders/${this.$state.params.id}/getVAT`; this.$http.get(query).then(res => { this.VAT = res.data; @@ -65,7 +65,7 @@ class Controller { rows: this.idsToRemove, actualOrderId: this.$state.params.id }; - let query = `/order/api/OrderRows/removes`; + let query = `api/OrderRows/removes`; this.$http.post(query, params).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); diff --git a/modules/order/front/line/index.spec.js b/modules/order/front/line/index.spec.js index 56b53ddb8..295113e78 100644 --- a/modules/order/front/line/index.spec.js +++ b/modules/order/front/line/index.spec.js @@ -35,7 +35,7 @@ describe('Order', () => { }; filter = encodeURIComponent(JSON.stringify(filter)); - $httpBackend.expectGET(`/order/api/OrderRows?filter=${filter}`).respond({data: [{id: 1}]}); + $httpBackend.expectGET(`api/OrderRows?filter=${filter}`).respond({data: [{id: 1}]}); controller.getRows(); $httpBackend.flush(); }); @@ -43,7 +43,7 @@ describe('Order', () => { describe('getVAT()', () => { it('should make a query to get the VAT of a given order', () => { - $httpBackend.expectGET(`/order/api/Orders/1/getVAT`).respond({data: {tax: 3}}); + $httpBackend.expectGET(`api/Orders/1/getVAT`).respond({data: {tax: 3}}); controller.getVAT(); $httpBackend.flush(); }); @@ -57,7 +57,7 @@ describe('Order', () => { spyOn(controller.card, 'reload'); controller.deleteRow('ACCEPT'); - $httpBackend.expectPOST(`/order/api/OrderRows/removes`).respond(); + $httpBackend.expectPOST(`api/OrderRows/removes`).respond(); $httpBackend.flush(); expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Data saved!'); diff --git a/modules/order/front/prices-popover/index.js b/modules/order/front/prices-popover/index.js index 826535ba9..b306521fd 100644 --- a/modules/order/front/prices-popover/index.js +++ b/modules/order/front/prices-popover/index.js @@ -33,7 +33,7 @@ class Controller { tooltip: 'Diary' } }; - this.$http.get(`/item/api/ItemTags?filter=${JSON.stringify(filter)}`).then(response => { + this.$http.get(`api/ItemTags?filter=${JSON.stringify(filter)}`).then(response => { this.tags = response.data; this.$.$applyAsync(() => { this.$.popover.relocate(); @@ -125,7 +125,7 @@ class Controller { items: filledLines }; - this.$http.post(`/order/api/OrderRows/addToOrder`, params).then(res => { + this.$http.post(`api/OrderRows/addToOrder`, params).then(res => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.$.popover.hide(); this.card.reload(); diff --git a/modules/order/front/search-panel/index.html b/modules/order/front/search-panel/index.html index 953524625..84edae23f 100644 --- a/modules/order/front/search-panel/index.html +++ b/modules/order/front/search-panel/index.html @@ -26,14 +26,14 @@ vn-one label="Agency" field="filter.agencyModeFk" - url="/agency/api/AgencyModes/isActive" + url="api/AgencyModes/isActive" show-field="name" value-field="id"> diff --git a/modules/order/front/summary/index.js b/modules/order/front/summary/index.js index 19323e4bb..0dfd468fc 100644 --- a/modules/order/front/summary/index.js +++ b/modules/order/front/summary/index.js @@ -10,7 +10,7 @@ class Controller { } setSummary() { - this.$http.get(`/order/api/Orders/${this.order.id}/summary`).then(res => { + this.$http.get(`api/Orders/${this.order.id}/summary`).then(res => { if (res && res.data) this.summary = res.data; }); diff --git a/modules/order/front/summary/index.spec.js b/modules/order/front/summary/index.spec.js index 171b23a83..51415251a 100644 --- a/modules/order/front/summary/index.spec.js +++ b/modules/order/front/summary/index.spec.js @@ -18,8 +18,8 @@ describe('Order', () => { describe('getSummary()', () => { it('should perform a GET query and define summary property', () => { let res = {id: 1, nickname: 'Batman'}; - $httpBackend.when('GET', `/order/api/Orders/1/summary`).respond(200, res); - $httpBackend.expect('GET', `/order/api/Orders/1/summary`); + $httpBackend.when('GET', `api/Orders/1/summary`).respond(200, res); + $httpBackend.expect('GET', `api/Orders/1/summary`); controller.setSummary(); $httpBackend.flush(); diff --git a/modules/order/front/volume/index.html b/modules/order/front/volume/index.html index e368e9c1b..b6de504f6 100644 --- a/modules/order/front/volume/index.html +++ b/modules/order/front/volume/index.html @@ -1,12 +1,12 @@ - + diff --git a/modules/order/front/volume/index.js b/modules/order/front/volume/index.js index 3275b0b5c..01b27c1b3 100644 --- a/modules/order/front/volume/index.js +++ b/modules/order/front/volume/index.js @@ -16,7 +16,7 @@ class Controller { } onDataChange() { - this.$http.get(`/order/api/Orders/${this.$stateParams.id}/getVolumes`) + this.$http.get(`api/Orders/${this.$stateParams.id}/getVolumes`) .then(response => { if (response.data) this.$scope.model.data.forEach(order => { diff --git a/modules/order/front/volume/index.spec.js b/modules/order/front/volume/index.spec.js index d18fde6d6..f85ade6ec 100644 --- a/modules/order/front/volume/index.spec.js +++ b/modules/order/front/volume/index.spec.js @@ -28,8 +28,8 @@ describe('Order', () => { it('should join the sale volumes to its respective sale', () => { let response = {volumes: [{itemFk: 1, volume: 0.008}, {itemFk: 2, volume: 0.003}]}; - $httpBackend.whenGET(`/order/api/Orders/1/getVolumes`).respond(response); - $httpBackend.expectGET(`/order/api/Orders/1/getVolumes`); + $httpBackend.whenGET(`api/Orders/1/getVolumes`).respond(response); + $httpBackend.expectGET(`api/Orders/1/getVolumes`); controller.onDataChange(); $httpBackend.flush(); diff --git a/modules/route/front/card/index.js b/modules/route/front/card/index.js index 9182d9cdc..3573de7ea 100644 --- a/modules/route/front/card/index.js +++ b/modules/route/front/card/index.js @@ -46,7 +46,7 @@ export default class Controller { getCard() { let json = encodeURIComponent(JSON.stringify(this.filter)); - this.$http.get(`/client/api/Routes?filter=${json}`).then(response => { + this.$http.get(`api/Routes?filter=${json}`).then(response => { this.route = response.data[0]; }); } diff --git a/modules/route/front/descriptor/index.js b/modules/route/front/descriptor/index.js index 15472726e..631a86c4d 100644 --- a/modules/route/front/descriptor/index.js +++ b/modules/route/front/descriptor/index.js @@ -54,7 +54,7 @@ class Controller { updateVolume(response) { if (response === 'ACCEPT') { - let url = `/route/api/Routes/${this.route.id}/updateVolume`; + let url = `api/Routes/${this.route.id}/updateVolume`; this.$http.post(url).then(() => { this.vnApp.showSuccess(this.$translate.instant('Volume updated')); this.card.reload(); diff --git a/modules/route/front/search-panel/index.html b/modules/route/front/search-panel/index.html index f19f88ee6..2f834ddb6 100644 --- a/modules/route/front/search-panel/index.html +++ b/modules/route/front/search-panel/index.html @@ -13,7 +13,7 @@ @@ -44,7 +44,7 @@ vn-one label="Vehicle" field="filter.vehicleFk" - url="/route/api/Vehicles" + url="api/Vehicles" show-field="numberPlate" value-field="id"> @@ -59,7 +59,7 @@ vn-one label="Warehouse" field="filter.warehouseFk" - url="/route/api/Warehouses" + url="api/Warehouses" show-field="name" value-field="id"> diff --git a/modules/route/front/tickets/index.js b/modules/route/front/tickets/index.js index ce12d88ac..c10a0cc42 100644 --- a/modules/route/front/tickets/index.js +++ b/modules/route/front/tickets/index.js @@ -81,7 +81,7 @@ class Controller { } updateVolume() { - let url = `/route/api/Routes/${this.$stateParams.id}/updateVolume`; + let url = `api/Routes/${this.$stateParams.id}/updateVolume`; this.$http.post(url).then(() => { this.card.reload(); this.$.model.refresh(); diff --git a/modules/ticket/front/basic-data/step-three/index.html b/modules/ticket/front/basic-data/step-three/index.html index 4208aaf8d..2e4d3ff3d 100644 --- a/modules/ticket/front/basic-data/step-three/index.html +++ b/modules/ticket/front/basic-data/step-three/index.html @@ -2,7 +2,7 @@ { if (res.data) { this.ticket = res.data; @@ -60,7 +60,7 @@ class Controller { } getDebt(id) { - const query = `/ticket/api/Clients/${id}/getDebt`; + const query = `api/Clients/${id}/getDebt`; this.$http.get(query).then(res => { if (res.data) this.ticket.client.debt = res.data.debt; diff --git a/modules/ticket/front/card/index.spec.js b/modules/ticket/front/card/index.spec.js index 7b9f7088f..2c9fa1472 100644 --- a/modules/ticket/front/card/index.spec.js +++ b/modules/ticket/front/card/index.spec.js @@ -23,10 +23,10 @@ describe('Ticket', () => { filter = encodeURIComponent(JSON.stringify(filter)); - $httpBackend.when('GET', `/ticket/api/Tickets/1?filter=${filter}`).respond({id: 1, client: {id: 1}}); - $httpBackend.expect('GET', `/ticket/api/Tickets/1?filter=${filter}`); - $httpBackend.when('GET', `/ticket/api/Clients/1/getDebt`).respond(); - $httpBackend.expect('GET', `/ticket/api/Clients/1/getDebt`); + $httpBackend.when('GET', `api/Tickets/1?filter=${filter}`).respond({id: 1, client: {id: 1}}); + $httpBackend.expect('GET', `api/Tickets/1?filter=${filter}`); + $httpBackend.when('GET', `api/Clients/1/getDebt`).respond(); + $httpBackend.expect('GET', `api/Clients/1/getDebt`); controller.getCard(); $httpBackend.flush(); diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html index 228a0270c..def434ca2 100644 --- a/modules/ticket/front/component/index.html +++ b/modules/ticket/front/component/index.html @@ -1,6 +1,6 @@ diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js index c0321e3d5..17d4690a3 100644 --- a/modules/ticket/front/create/card.js +++ b/modules/ticket/front/create/card.js @@ -109,7 +109,7 @@ class Controller { agencyModeFk: this.ticket.agencyModeFk, warehouseFk: this.ticket.warehouseFk, }; - this.$http.post(`ticket/api/Tickets/new`, params).then(res => { + this.$http.post(`api/Tickets/new`, params).then(res => { this.vnApp.showSuccess(this.translate.instant('Data saved!')); this.$state.go('ticket.card.summary', {id: res.data.id}); }); diff --git a/modules/ticket/front/descriptor-popover/index.js b/modules/ticket/front/descriptor-popover/index.js index 1c8b997a7..dddfba544 100644 --- a/modules/ticket/front/descriptor-popover/index.js +++ b/modules/ticket/front/descriptor-popover/index.js @@ -97,7 +97,7 @@ class Controller extends Component { ] }; let json = encodeURIComponent(JSON.stringify(filter)); - let query = `/ticket/api/Tickets/${this._ticketFk}?filter=${json}`; + let query = `api/Tickets/${this._ticketFk}?filter=${json}`; this.$http.get(query, options).then( response => { this.ticket = response.data; diff --git a/modules/ticket/front/descriptor-popover/index.spec.js b/modules/ticket/front/descriptor-popover/index.spec.js index a7b4a92e2..5760c28da 100644 --- a/modules/ticket/front/descriptor-popover/index.spec.js +++ b/modules/ticket/front/descriptor-popover/index.spec.js @@ -115,8 +115,8 @@ describe('ticket Component vnTicketDescriptorPopover', () => { ] }; let json = encodeURIComponent(JSON.stringify(filter)); - $httpBackend.when('GET', `/ticket/api/Tickets/${controller._ticketFk}?filter=${json}`).respond(response); - $httpBackend.expect('GET', `/ticket/api/Tickets/${controller._ticketFk}?filter=${json}`); + $httpBackend.when('GET', `api/Tickets/${controller._ticketFk}?filter=${json}`).respond(response); + $httpBackend.expect('GET', `api/Tickets/${controller._ticketFk}?filter=${json}`); controller.getCard(); $httpBackend.flush(); diff --git a/modules/ticket/front/descriptor/index.js b/modules/ticket/front/descriptor/index.js index 0453a55b2..c85f39696 100644 --- a/modules/ticket/front/descriptor/index.js +++ b/modules/ticket/front/descriptor/index.js @@ -53,7 +53,7 @@ class Controller { changeShipped(response) { if (response === 'ACCEPT') { let data = {shipped: this.newShipped}; - let query = `/ticket/api/Tickets/${this.ticket.id}/updateEditableTicket`; + let query = `api/Tickets/${this.ticket.id}/updateEditableTicket`; this.$http.post(query, data).then(() => { this.vnApp.showSuccess(this.$translate.instant('Shipped hour updated')); this.cardReload(); @@ -122,7 +122,7 @@ class Controller { addTurn(day) { let params = {ticketFk: this.ticket.id, weekDay: day}; - this.$http.patch(`/ticket/api/TicketWeeklies`, params).then(() => { + this.$http.patch(`api/TicketWeeklies`, params).then(() => { this.$scope.addTurn.hide(); this.vnApp.showSuccess(this.$translate.instant('Data saved!')); }); @@ -236,7 +236,7 @@ class Controller { */ makeInvoice(response) { if (response === 'ACCEPT') { - const query = `/ticket/api/Tickets/${this.ticket.id}/makeInvoice`; + const query = `api/Tickets/${this.ticket.id}/makeInvoice`; this.$http.post(query).then(() => { this.vnApp.showSuccess(this.$translate.instant('Ticket invoiced')); this.$state.reload(); @@ -260,7 +260,7 @@ class Controller { regenerateInvoice(response) { if (response === 'ACCEPT') { const invoiceId = this.ticket.invoiceOut.id; - const query = `/invoiceOut/api/InvoiceOuts/${invoiceId}/regenerate`; + const query = `api/InvoiceOuts/${invoiceId}/regenerate`; this.$http.post(query).then(() => { const snackbarMessage = this.$translate.instant( `Invoice sent for a regeneration, will be available in a few minutes`); diff --git a/modules/ticket/front/descriptor/index.spec.js b/modules/ticket/front/descriptor/index.spec.js index 6fc167a41..f049a6903 100644 --- a/modules/ticket/front/descriptor/index.spec.js +++ b/modules/ticket/front/descriptor/index.spec.js @@ -40,7 +40,7 @@ describe('Ticket Component vnTicketDescriptor', () => { controller.$scope.addTurn = {hide: () => {}}; spyOn(controller.$scope.addTurn, 'hide'); - $httpBackend.expectPATCH(`/ticket/api/TicketWeeklies`).respond(); + $httpBackend.expectPATCH(`api/TicketWeeklies`).respond(); controller.addTurn(1); $httpBackend.flush(); @@ -96,8 +96,8 @@ describe('Ticket Component vnTicketDescriptor', () => { spyOn(controller.$state, 'reload'); spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.when('POST', '/ticket/api/Tickets/2/makeInvoice').respond(); - $httpBackend.expect('POST', '/ticket/api/Tickets/2/makeInvoice').respond(); + $httpBackend.when('POST', 'api/Tickets/2/makeInvoice').respond(); + $httpBackend.expect('POST', 'api/Tickets/2/makeInvoice').respond(); controller.makeInvoice('ACCEPT'); $httpBackend.flush(); @@ -110,8 +110,8 @@ describe('Ticket Component vnTicketDescriptor', () => { it('should make a query and show a success snackbar if the response is ACCEPT', () => { spyOn(controller.vnApp, 'showSuccess'); - $httpBackend.when('POST', '/invoiceOut/api/InvoiceOuts/1/regenerate').respond(); - $httpBackend.expect('POST', '/invoiceOut/api/InvoiceOuts/1/regenerate').respond(); + $httpBackend.when('POST', 'api/InvoiceOuts/1/regenerate').respond(); + $httpBackend.expect('POST', 'api/InvoiceOuts/1/regenerate').respond(); controller.regenerateInvoice('ACCEPT'); $httpBackend.flush(); @@ -125,8 +125,8 @@ describe('Ticket Component vnTicketDescriptor', () => { spyOn(controller.vnApp, 'showSuccess'); spyOn(controller, 'cardReload'); - $httpBackend.when('POST', '/ticket/api/Tickets/12/updateEditableTicket').respond(); - $httpBackend.expect('POST', '/ticket/api/Tickets/12/updateEditableTicket').respond(); + $httpBackend.when('POST', 'api/Tickets/12/updateEditableTicket').respond(); + $httpBackend.expect('POST', 'api/Tickets/12/updateEditableTicket').respond(); controller.changeShipped('ACCEPT'); $httpBackend.flush(); diff --git a/modules/ticket/front/dms/index/index.html b/modules/ticket/front/dms/index/index.html index ce0dde211..ce606a2dd 100644 --- a/modules/ticket/front/dms/index/index.html +++ b/modules/ticket/front/dms/index/index.html @@ -1,6 +1,6 @@ diff --git a/modules/ticket/front/expedition/index.js b/modules/ticket/front/expedition/index.js index 74d22a792..8e5c5cc31 100644 --- a/modules/ticket/front/expedition/index.js +++ b/modules/ticket/front/expedition/index.js @@ -14,7 +14,7 @@ class Controller { returnDialog(response) { if (response === 'ACCEPT') { - this.$http.delete(`/ticket/api/Expeditions/${this.expeditionId}`).then( + this.$http.delete(`api/Expeditions/${this.expeditionId}`).then( () => this.$.model.refresh() ); } diff --git a/modules/ticket/front/expedition/index.spec.js b/modules/ticket/front/expedition/index.spec.js index c20f5e0ea..c5ae12671 100644 --- a/modules/ticket/front/expedition/index.spec.js +++ b/modules/ticket/front/expedition/index.spec.js @@ -28,8 +28,8 @@ describe('Ticket', () => { let response = 'ACCEPT'; controller.expeditionId = 1; - $httpBackend.when('DELETE', `/ticket/api/Expeditions/1`).respond(200); - $httpBackend.expect('DELETE', `/ticket/api/Expeditions/1`); + $httpBackend.when('DELETE', `api/Expeditions/1`).respond(200); + $httpBackend.expect('DELETE', `api/Expeditions/1`); controller.returnDialog(response); $httpBackend.flush(); diff --git a/modules/ticket/front/index/index.html b/modules/ticket/front/index/index.html index 5d05bd7c5..1bcbd9fc4 100644 --- a/modules/ticket/front/index/index.html +++ b/modules/ticket/front/index/index.html @@ -1,6 +1,6 @@ diff --git a/modules/ticket/front/package/index.html b/modules/ticket/front/package/index.html index e774012c5..7257093b9 100644 --- a/modules/ticket/front/package/index.html +++ b/modules/ticket/front/package/index.html @@ -17,7 +17,7 @@ + diff --git a/modules/ticket/front/search-panel/index.html b/modules/ticket/front/search-panel/index.html index 70fa24e63..77aa0c8ce 100644 --- a/modules/ticket/front/search-panel/index.html +++ b/modules/ticket/front/search-panel/index.html @@ -54,7 +54,7 @@ diff --git a/modules/ticket/front/summary/index.js b/modules/ticket/front/summary/index.js index 2bdbe7fef..e1b1d1f9b 100644 --- a/modules/ticket/front/summary/index.js +++ b/modules/ticket/front/summary/index.js @@ -30,7 +30,7 @@ class Controller { } getSummary() { - this.$http.get(`/ticket/api/Tickets/${this.ticket.id}/summary`).then(res => { + this.$http.get(`api/Tickets/${this.ticket.id}/summary`).then(res => { if (res && res.data) this.summary = res.data; }); @@ -76,7 +76,7 @@ class Controller { params.code = 'OK'; - this.$http.post(`/ticket/api/TicketTrackings/changeState`, params).then(() => { + this.$http.post(`api/TicketTrackings/changeState`, params).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); if (this.card) this.card.reload(); diff --git a/modules/ticket/front/summary/index.spec.js b/modules/ticket/front/summary/index.spec.js index 4653c80a4..ccf6f3ffc 100644 --- a/modules/ticket/front/summary/index.spec.js +++ b/modules/ticket/front/summary/index.spec.js @@ -18,8 +18,8 @@ describe('Ticket', () => { describe('ticket()', () => { it('should perform a GET query and define summary property', () => { let res = {id: 1, nickname: 'Batman'}; - $httpBackend.when('GET', `/ticket/api/Tickets/1/summary`).respond(200, res); - $httpBackend.expect('GET', `/ticket/api/Tickets/1/summary`); + $httpBackend.when('GET', `api/Tickets/1/summary`).respond(200, res); + $httpBackend.expect('GET', `api/Tickets/1/summary`); controller.ticket = {id: 1}; $httpBackend.flush(); diff --git a/modules/ticket/front/tracking/edit/index.html b/modules/ticket/front/tracking/edit/index.html index e7368ba7a..79ad70ab7 100644 --- a/modules/ticket/front/tracking/edit/index.html +++ b/modules/ticket/front/tracking/edit/index.html @@ -10,13 +10,13 @@ - + diff --git a/modules/ticket/front/weekly/index/index.html b/modules/ticket/front/weekly/index/index.html index 51f40c9eb..10646c561 100644 --- a/modules/ticket/front/weekly/index/index.html +++ b/modules/ticket/front/weekly/index/index.html @@ -1,6 +1,6 @@ { + this.$http.patch('api/TicketWeeklies/', params).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); }); } @@ -77,7 +77,7 @@ export default class Controller { returnDialog(response) { const ticket = this.$.model.data[this.ticketIndex]; if (response === 'ACCEPT') { - this.$http.delete(`/ticket/api/TicketWeeklies/${ticket.ticketFk}`).then(() => { + this.$http.delete(`api/TicketWeeklies/${ticket.ticketFk}`).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.$.model.remove(this.ticketIndex); }); diff --git a/modules/travel/front/index/index.html b/modules/travel/front/index/index.html index c7f2a6d6e..cc7a07207 100644 --- a/modules/travel/front/index/index.html +++ b/modules/travel/front/index/index.html @@ -1,6 +1,6 @@ @@ -51,14 +51,14 @@ diff --git a/modules/worker/front/calendar/index.js b/modules/worker/front/calendar/index.js index d1b042619..988004d32 100644 --- a/modules/worker/front/calendar/index.js +++ b/modules/worker/front/calendar/index.js @@ -24,7 +24,7 @@ class Controller { ended: this.ended }}; - let query = `/worker/api/WorkerCalendars/absences`; + let query = `api/WorkerCalendars/absences`; this.$http.get(query, params).then(res => { if (!res.data) return; diff --git a/modules/worker/front/calendar/index.spec.js b/modules/worker/front/calendar/index.spec.js index 90c50ba01..623e058e3 100644 --- a/modules/worker/front/calendar/index.spec.js +++ b/modules/worker/front/calendar/index.spec.js @@ -74,8 +74,8 @@ describe('Worker', () => { started: controller.started, ended: controller.ended }); - $httpBackend.when('GET', `/worker/api/WorkerCalendars/absences?${params}`).respond(expectedData); - $httpBackend.expect('GET', `/worker/api/WorkerCalendars/absences?${params}`); + $httpBackend.when('GET', `api/WorkerCalendars/absences?${params}`).respond(expectedData); + $httpBackend.expect('GET', `api/WorkerCalendars/absences?${params}`); controller.worker = worker; diff --git a/modules/worker/front/department/index.html b/modules/worker/front/department/index.html index 6cf2cd063..8824d8349 100644 --- a/modules/worker/front/department/index.html +++ b/modules/worker/front/department/index.html @@ -1,6 +1,6 @@ diff --git a/modules/worker/front/department/index.js b/modules/worker/front/department/index.js index 2047c06c7..c3a4a75ed 100644 --- a/modules/worker/front/department/index.js +++ b/modules/worker/front/department/index.js @@ -50,7 +50,7 @@ class Controller { if (!this.newNode.name) throw new Error(`Name can't be empty`); - this.$http.post(`/worker/api/Departments/nodeAdd`, this.newNode).then(response => { + this.$http.post(`api/Departments/nodeAdd`, this.newNode).then(response => { if (response.data) { let parent = this.selectedNode.parent; if ((parent instanceof Object) && !(parent instanceof Array)) { @@ -70,7 +70,7 @@ class Controller { onRemoveResponse(response) { if (response === 'ACCEPT') { - const path = `/worker/api/Departments/nodeDelete`; + const path = `api/Departments/nodeDelete`; this.$http.post(path, {parentFk: this.selectedNode.id}).then(() => { let parent = this.selectedNode.parent; diff --git a/modules/worker/front/index/index.html b/modules/worker/front/index/index.html index 3c254e7f7..cfbece2cf 100644 --- a/modules/worker/front/index/index.html +++ b/modules/worker/front/index/index.html @@ -1,6 +1,6 @@ diff --git a/modules/worker/front/time-control/index.html b/modules/worker/front/time-control/index.html index 1aeb70304..0bdddef95 100644 --- a/modules/worker/front/time-control/index.html +++ b/modules/worker/front/time-control/index.html @@ -1,6 +1,6 @@ From ad7636b879aabae603bdbe0bb60f66bb39e8a7a3 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Mon, 9 Dec 2019 09:33:59 +0100 Subject: [PATCH 09/59] Back restart at night --- back/process.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/back/process.yml b/back/process.yml index c35876898..edf66a8c1 100644 --- a/back/process.yml +++ b/back/process.yml @@ -1,6 +1,6 @@ apps: - script: ./loopback/server/server.js name: salix-back - cron_restart: '*/30 * * * *' + cron_restart: '0 4 * * *' instances: 1 max_restarts: 10 From 9c4f7762816e540da70b1aaed326d296cba96787 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Wed, 11 Dec 2019 16:51:45 +0100 Subject: [PATCH 10/59] Disabled back restart, added back healthcheck --- Dockerfile | 3 +++ back/process.yml | 3 +-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/Dockerfile b/Dockerfile index 65c2aa0b1..13200caa7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -34,3 +34,6 @@ COPY \ ./ CMD ["pm2-runtime", "./back/process.yml"] + +HEALTHCHECK --interval=1m --timeout=10s \ + CMD curl -f http://localhost:3000/api/Applications/status || exit 1 diff --git a/back/process.yml b/back/process.yml index edf66a8c1..3062091b4 100644 --- a/back/process.yml +++ b/back/process.yml @@ -1,6 +1,5 @@ apps: - script: ./loopback/server/server.js name: salix-back - cron_restart: '0 4 * * *' instances: 1 - max_restarts: 10 + max_restarts: 5 From 3532c52e071ab502cb027f25ba07af788b080378 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Wed, 11 Dec 2019 17:04:41 +0100 Subject: [PATCH 11/59] Back docker healthcheck fix --- Dockerfile | 1 - 1 file changed, 1 deletion(-) diff --git a/Dockerfile b/Dockerfile index 13200caa7..f2cbeeff9 100644 --- a/Dockerfile +++ b/Dockerfile @@ -12,7 +12,6 @@ RUN apt-get update \ && apt-get install -y --no-install-recommends \ nodejs \ && apt-get purge -y --auto-remove \ - curl \ gnupg2 \ && rm -rf /var/lib/apt/lists/* \ && npm -g install pm2 From ef95244d074817a7021987f42cddaa306fa8795c Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Tue, 17 Dec 2019 08:38:36 +0100 Subject: [PATCH 12/59] stowaway refactor --- .../00-expedition_beforeInsert.sql | 33 ++++ .../10120-december/00-stowaway_unboarding.sql | 31 ++++ modules/claim/front/locale/es.yml | 2 +- modules/client/front/locale/es.yml | 2 +- .../invoiceOut/front/descriptor/locale/es.yml | 2 +- modules/order/front/descriptor/locale/es.yml | 4 +- modules/order/front/line/locale/es.yml | 2 +- modules/route/front/tickets/locale/es.yml | 6 +- .../back/methods/ticket/canHaveStowaway.js | 13 +- .../back/methods/ticket/deleteStowaway.js | 39 +++++ .../ticket/specs/deleteStowaway.spec.js | 42 +++++ modules/ticket/back/models/ticket.js | 1 + modules/ticket/back/models/ticket.json | 2 +- .../ticket/front/descriptor/addStowaway.html | 4 +- modules/ticket/front/descriptor/index.html | 11 +- modules/ticket/front/descriptor/index.js | 145 +++++++++--------- modules/ticket/front/descriptor/index.spec.js | 8 +- modules/ticket/front/descriptor/locale/es.yml | 4 +- .../front/descriptor/removeStowaway.html | 38 ----- .../ticket/front/descriptor/removeStowaway.js | 78 ---------- modules/ticket/front/descriptor/style.scss | 2 +- modules/ticket/front/index.js | 1 - modules/ticket/front/locale/es.yml | 6 +- modules/ticket/front/sale/locale/es.yml | 6 +- .../worker/front/time-control/locale/es.yml | 2 +- 25 files changed, 264 insertions(+), 220 deletions(-) create mode 100644 db/changes/10120-december/00-expedition_beforeInsert.sql create mode 100644 db/changes/10120-december/00-stowaway_unboarding.sql create mode 100644 modules/ticket/back/methods/ticket/deleteStowaway.js create mode 100644 modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js delete mode 100644 modules/ticket/front/descriptor/removeStowaway.html delete mode 100644 modules/ticket/front/descriptor/removeStowaway.js diff --git a/db/changes/10120-december/00-expedition_beforeInsert.sql b/db/changes/10120-december/00-expedition_beforeInsert.sql new file mode 100644 index 000000000..819cd7a7f --- /dev/null +++ b/db/changes/10120-december/00-expedition_beforeInsert.sql @@ -0,0 +1,33 @@ +DROP TRIGGER IF EXISTS `vn`.`expedition_beforeInsert`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` TRIGGER `vn`.`expedition_beforeInsert` + BEFORE INSERT ON `expedition` FOR EACH ROW +BEGIN + DECLARE intcounter INT; + DECLARE vShipFk INT; + + IF NEW.isBox > 0 THEN + + UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; + + SELECT IFNULL(MAX(counter),0) +1 INTO intcounter + FROM expedition e + INNER JOIN ticket t1 ON e.ticketFk = t1.id + LEFT JOIN ticketState ts ON ts.ticket = t1.id + INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) + AND t1.warehouseFk = t2.warehouseFk + WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk + AND t1.agencyModeFk = t2.agencyModeFk; + + SET NEW.`counter` = intcounter; + END IF; + + SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; + + IF vShipFk THEN + CALL stowaway_unboarding(vShipFk, NEW.ticketFk); + END IF; +END$$ +DELIMITER ; diff --git a/db/changes/10120-december/00-stowaway_unboarding.sql b/db/changes/10120-december/00-stowaway_unboarding.sql new file mode 100644 index 000000000..271baba6c --- /dev/null +++ b/db/changes/10120-december/00-stowaway_unboarding.sql @@ -0,0 +1,31 @@ + +USE `vn`; +DROP procedure IF EXISTS `vn`.`stowawayUnBoarding`; + +DELIMITER $$ +USE `vn`$$ +CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) +BEGIN + DECLARE vWorker VARCHAR(255); + + DELETE FROM stowaway + WHERE shipFk = vShipFk AND id = vStowawayFk; + + DELETE tt FROM ticketTracking tt + JOIN state s ON s.id = tt.stateFk + WHERE code = 'BOARDING' AND ticketFk = vShipFk; + + DELETE FROM sale + WHERE ticketFk = vShipFk + AND itemFk = 98 + AND concept = CONCAT('POLIZÓN! ',vStowawayFk); + + SELECT u.`name` INTO vWorker + FROM account.user u JOIN worker w ON w.userFk = u.id + WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); + + SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; +END$$ + +DELIMITER ; +; diff --git a/modules/claim/front/locale/es.yml b/modules/claim/front/locale/es.yml index f636b43ee..26b1eba32 100644 --- a/modules/claim/front/locale/es.yml +++ b/modules/claim/front/locale/es.yml @@ -7,7 +7,7 @@ Claimed ticket: Ticket reclamado Delete claim: Eliminar reclamación Observation: Observación Responsible: Responsable -Remove sale: Borrar linea +Remove sale: Eliminar linea Claim Id: Id reclamación Created: Creado Send Pickup order: Enviar orden de recogida diff --git a/modules/client/front/locale/es.yml b/modules/client/front/locale/es.yml index baca4d479..1b44b5652 100644 --- a/modules/client/front/locale/es.yml +++ b/modules/client/front/locale/es.yml @@ -18,7 +18,7 @@ Sent: Enviado Worker: Trabajador Sample: Plantilla Credit: Crédito -Are you sure you want to delete this expedition?: ¿Está seguro de borrar esta expedición? +Are you sure you want to delete this expedition?: ¿Está seguro de eliminar esta expedición? Others: Otros New order: Nuevo pedido Client frozen: Cliente congelado diff --git a/modules/invoiceOut/front/descriptor/locale/es.yml b/modules/invoiceOut/front/descriptor/locale/es.yml index 4f6abcea3..e85be96bf 100644 --- a/modules/invoiceOut/front/descriptor/locale/es.yml +++ b/modules/invoiceOut/front/descriptor/locale/es.yml @@ -3,7 +3,7 @@ Volume: Volumen Client card: Ficha del cliente Invoice ticket list: Listado de tickets de la factura Show invoice PDF: Ver factura en PDF -Delete Invoice: Borrar factura +Delete Invoice: Eliminar factura InvoiceOut deleted: Factura eliminada Are you sure you want to delete this invoice?: Estas seguro de eliminar esta factura? Book invoice: Asentar factura diff --git a/modules/order/front/descriptor/locale/es.yml b/modules/order/front/descriptor/locale/es.yml index 21f3051ca..0734d7638 100644 --- a/modules/order/front/descriptor/locale/es.yml +++ b/modules/order/front/descriptor/locale/es.yml @@ -7,6 +7,6 @@ Items: Articulos Agency: Agencia Sales person: Comercial Order ticket list: Ticket del pedido -Delete order: Borrar pedido -You are going to delete this order: El pedido se borrará +Delete order: Eliminar pedido +You are going to delete this order: El pedido se eliminará continue anyway?: ¿Continuar de todos modos? \ No newline at end of file diff --git a/modules/order/front/line/locale/es.yml b/modules/order/front/line/locale/es.yml index 688778561..d1368d369 100644 --- a/modules/order/front/line/locale/es.yml +++ b/modules/order/front/line/locale/es.yml @@ -1,3 +1,3 @@ Delete row: Eliminar linea Order confirmed: Pedido confirmado -Are you sure you want to delete this row?: ¿Estas seguro de que quieres borrar esta línea? \ No newline at end of file +Are you sure you want to delete this row?: ¿Estas seguro de que quieres eliminar esta línea? \ No newline at end of file diff --git a/modules/route/front/tickets/locale/es.yml b/modules/route/front/tickets/locale/es.yml index 7edeff17b..02f9eed08 100644 --- a/modules/route/front/tickets/locale/es.yml +++ b/modules/route/front/tickets/locale/es.yml @@ -1,8 +1,8 @@ -Remove ticket: Borrar ticket +Remove ticket: Eliminar ticket Open buscaman: Abrir buscaman -Ticket removed from route: Ticket borrado de la ruta +Ticket removed from route: Ticket quitado de la ruta Order changed: Orden cambiado -Delete ticket from route?: ¿Borrar ticket de la ruta? +Delete ticket from route?: ¿Quitar el ticket de la ruta? Sort routes: Ordenar rutas Add ticket: Añadir ticket Tickets to add: Tickets a añadir \ No newline at end of file diff --git a/modules/ticket/back/methods/ticket/canHaveStowaway.js b/modules/ticket/back/methods/ticket/canHaveStowaway.js index 0d64c2d11..bbc6cf4b3 100644 --- a/modules/ticket/back/methods/ticket/canHaveStowaway.js +++ b/modules/ticket/back/methods/ticket/canHaveStowaway.js @@ -21,10 +21,17 @@ module.exports = Self => { Self.canHaveStowaway = async id => { const models = Self.app.models; - const ticket = await models.Ticket.findById(id); + const ticket = await models.Ticket.findById(id, { + include: { + relation: 'ship', + scope: { + fields: ['id'] + } + } + }); const warehouse = await models.Warehouse.findById(ticket.warehouseFk); - - if (warehouse && warehouse.hasStowaway) + const hasStowaway = ticket.ship() ? true : false; + if (warehouse && warehouse.hasStowaway && !hasStowaway) return true; return false; diff --git a/modules/ticket/back/methods/ticket/deleteStowaway.js b/modules/ticket/back/methods/ticket/deleteStowaway.js new file mode 100644 index 000000000..6f3a1760f --- /dev/null +++ b/modules/ticket/back/methods/ticket/deleteStowaway.js @@ -0,0 +1,39 @@ + +module.exports = Self => { + Self.remoteMethod('deleteStowaway', { + description: 'Deletes an stowaway', + accessType: 'WRITE', + accepts: [{ + arg: 'id', + type: 'number', + required: true, + description: 'The ticket id', + http: {source: 'path'} + }], + returns: { + root: true + }, + http: { + path: `/:id/deleteStowaway`, + verb: 'POST' + } + }); + + Self.deleteStowaway = async id => { + const ticket = await Self.findById(id, { + include: [{ + relation: 'ship' + }, { + relation: 'stowaway' + }] + }); + + let params; + if (ticket.stowaway()) + params = [ticket.stowaway().shipFk, ticket.stowaway().id]; + else if (ticket.ship()) + params = [ticket.ship().shipFk, ticket.ship().id]; + + return Self.rawSql(`CALL vn.stowaway_unboarding(?, ?)`, params); + }; +}; diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js new file mode 100644 index 000000000..d5a10ac3b --- /dev/null +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -0,0 +1,42 @@ +const app = require('vn-loopback/server/server'); + +fdescribe('ticket deleteStowaway()', () => { + const shipId = 16; + const stowawayId = 17; + + it('should create an stowaway', async() => { + await app.models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId]); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(1); + }); + + it('should delete the stowaway from the ship ticket', async() => { + await app.models.Ticket.deleteStowaway(shipId); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(0); + }); + + it('should create again an stowaway', async() => { + await app.models.Stowaway.rawSql(` + INSERT INTO stowaway (id, shipFk) VALUES (?, ?) + `, [stowawayId, shipId]); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(1); + }); + + it('should delete the stowaway from the stowaway ticket', async() => { + await app.models.Ticket.deleteStowaway(stowawayId); + + const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + + expect(stowawayExists).toEqual(0); + }); +}); diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index c42df62ef..8ba2bfb0d 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -27,6 +27,7 @@ module.exports = Self => { require('../methods/ticket/transferSales')(Self); require('../methods/ticket/canHaveStowaway')(Self); require('../methods/ticket/recalculateComponents')(Self); + require('../methods/ticket/deleteStowaway')(Self); Self.observe('before save', async function(ctx) { if (ctx.isNewInstance) return; diff --git a/modules/ticket/back/models/ticket.json b/modules/ticket/back/models/ticket.json index 7b6c4a64b..113e6a75f 100644 --- a/modules/ticket/back/models/ticket.json +++ b/modules/ticket/back/models/ticket.json @@ -51,7 +51,7 @@ "foreignKey": "clientFk" }, "ship": { - "type": "hasMany", + "type": "hasOne", "model": "Stowaway", "foreignKey": "shipFk" }, diff --git a/modules/ticket/front/descriptor/addStowaway.html b/modules/ticket/front/descriptor/addStowaway.html index 4ffab8ce5..ec7005e79 100644 --- a/modules/ticket/front/descriptor/addStowaway.html +++ b/modules/ticket/front/descriptor/addStowaway.html @@ -7,10 +7,10 @@ class="modal-form" on-open="model.refresh()"> -
+
Stowaways to add
- + diff --git a/modules/ticket/front/descriptor/index.html b/modules/ticket/front/descriptor/index.html index decc0b6d4..3632d37f1 100644 --- a/modules/ticket/front/descriptor/index.html +++ b/modules/ticket/front/descriptor/index.html @@ -139,11 +139,12 @@ card-reload="$ctrl.cardReload()" ticket="$ctrl.ticket"> - - + + this.shouldShowRemoveStowaway() + callback: this.showDeleteStowaway, + show: () => this.shouldShowDeleteStowaway() }, { name: 'Make invoice', @@ -43,6 +43,54 @@ class Controller extends Component { ]; } + get ticket() { + return this._ticket; + } + + set ticket(value) { + this._ticket = value; + + if (!value) return; + + if (this.$params.sendSMS) + this.showSMSDialog(); + + this.canStowaway(); + + let links = { + btnOne: { + icon: 'person', + state: `client.card.summary({id: ${value.clientFk}})`, + tooltip: 'Client card' + }}; + + if (value.stowaway) { + links.btnTwo = { + icon: 'icon-stowaway', + state: `ticket.card.summary({id: ${value.stowaway.shipFk}})`, + tooltip: 'Ship stowaways' + }; + } + + if (value.ship) { + links.btnThree = { + icon: 'icon-stowaway', + state: `ticket.card.summary({id: ${value.ship.id}})`, + tooltip: 'Stowaway' + }; + } + + this._quicklinks = links; + } + + get quicklinks() { + return this._quicklinks; + } + + set quicklinks(value = {}) { + this._quicklinks = Object.assign(value, this._quicklinks); + } + showChangeShipped() { if (!this.isEditable) { this.vnApp.showError(this.$translate.instant(`This ticket can't be modified`)); @@ -72,24 +120,6 @@ class Controller extends Component { return false; } - canStowaway() { - if (!this.isTicketModule()) return; - - this.$http.get(`Tickets/${this.ticket.id}/canHaveStowaway`).then(response => { - if (response.data === true) - return this.canShowStowaway = true; - - return this.canShowStowaway = false; - }); - } - - shouldShowRemoveStowaway() { - if (!this._ticket || !this.isTicketModule()) - return false; - - return (this._ticket.stowaway || (this._ticket.ship && this._ticket.ship.length > 0)); - } - onMoreChange(callback) { callback.call(this); } @@ -149,61 +179,38 @@ class Controller extends Component { } } + canStowaway() { + if (!this.isTicketModule()) return; + + this.$http.get(`Tickets/${this.ticket.id}/canHaveStowaway`).then(response => { + if (response.data === true) + return this.canShowStowaway = true; + + return this.canShowStowaway = false; + }); + } + + shouldShowDeleteStowaway() { + if (!this._ticket || !this.isTicketModule()) + return false; + + return this._ticket.stowaway || this._ticket.ship; + } + showAddStowaway() { this.$.addStowaway.show(); } - showRemoveStowaway() { - this.$.removeStowaway.show(); + showDeleteStowaway() { + this.$.deleteStowaway.show(); } - get ticket() { - return this._ticket; - } - - set ticket(value) { - this._ticket = value; - - if (!value) return; - - if (this.$params.sendSMS) - this.showSMSDialog(); - - this.canStowaway(); - - let links = { - btnOne: { - icon: 'person', - state: `client.card.summary({id: ${value.clientFk}})`, - tooltip: 'Client card' - }}; - - if (value.stowaway) { - links.btnTwo = { - icon: 'icon-stowaway', - state: `ticket.card.summary({id: ${value.stowaway.shipFk}})`, - tooltip: 'Ship stowaways' - }; - } - - if (value.ship && value.ship.length == 1) { - links.btnThree = { - icon: 'icon-stowaway', - state: `ticket.card.summary({id: ${value.ship[0].id}})`, - tooltip: 'Stowaway' - }; - } else if (value.ship && value.ship.length > 1) - this.shipStowaways = value.ship; - - this._quicklinks = links; - } - - set quicklinks(value = {}) { - this._quicklinks = Object.assign(value, this._quicklinks); - } - - get quicklinks() { - return this._quicklinks; + deleteStowaway() { + const query = `Tickets/${this.ticket.id}/deleteStowaway`; + this.$http.post(query).then(res => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.cardReload(); + }); } showDeliveryNote() { diff --git a/modules/ticket/front/descriptor/index.spec.js b/modules/ticket/front/descriptor/index.spec.js index 937a837b3..eb554218e 100644 --- a/modules/ticket/front/descriptor/index.spec.js +++ b/modules/ticket/front/descriptor/index.spec.js @@ -174,11 +174,11 @@ describe('Ticket Component vnTicketDescriptor', () => { describe('showRemoveStowaway()', () => { it('should show a dialog for an stowaway removal', () => { - controller.$.removeStowaway = {}; - controller.$.removeStowaway.show = jasmine.createSpy('show'); - controller.showRemoveStowaway(); + controller.$.deleteStowaway = {}; + controller.$.deleteStowaway.show = jasmine.createSpy('show'); + controller.showDeleteStowaway(); - expect(controller.$.removeStowaway.show).toHaveBeenCalledWith(); + expect(controller.$.deleteStowaway.show).toHaveBeenCalledWith(); }); }); diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index 2f72e226e..68512fec2 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -5,8 +5,8 @@ Ship stowaways: Polizones del barco Stowaways to add: Polizones a añadir Stowaways of the ticket: Polizones del ticket Add stowaway: Añadir polizón -Remove stowaway: Borrar polizón -Are you sure you want to delete this stowaway?: ¿Seguro que quieres borrar este polizón? +Remove stowaway: Eliminar polizón +Are you sure you want to delete this stowaway?: ¿Seguro que quieres eliminar este polizón? Are you sure you want to send it?: ¿Seguro que quieres enviarlo? Show Delivery Note: Ver albarán Send Delivery Note: Enviar albarán diff --git a/modules/ticket/front/descriptor/removeStowaway.html b/modules/ticket/front/descriptor/removeStowaway.html deleted file mode 100644 index 891329b7e..000000000 --- a/modules/ticket/front/descriptor/removeStowaway.html +++ /dev/null @@ -1,38 +0,0 @@ - - - -
Stowaways of the ticket {{$ctrl.ticket.id}}
-
- - - - - Ticket id - Shipped - Agency - Warehouse - State - - - - - {{stowaway.id}} - {{stowaway.ticket.landed | date: 'dd/MM/yyyy'}} - {{stowaway.ticket.agencyMode.name}} - {{stowaway.ticket.warehouse.name}} - {{stowaway.ticket.state.state.name}} - - - - -
-
- - - \ No newline at end of file diff --git a/modules/ticket/front/descriptor/removeStowaway.js b/modules/ticket/front/descriptor/removeStowaway.js deleted file mode 100644 index 05ace7d9e..000000000 --- a/modules/ticket/front/descriptor/removeStowaway.js +++ /dev/null @@ -1,78 +0,0 @@ -import ngModule from '../module'; - -class Controller { - constructor($state, $scope, $http, vnApp, $translate) { - this.vnApp = vnApp; - this.$translate = $translate; - this.$scope = $scope; - this.$state = $state; - this.$http = $http; - } - - getTicketStowaways() { - if (this.ticket.stowaway) { - this.ticketStowaways = [this.ticket.stowaway]; - this.showDeleteConfirm(0); - } else if (this.ticket.ship.length > 1) { - let filter = { - where: {shipFk: this.ticket.id}, - include: { - relation: 'ticket', - scope: { - include: [ - {relation: 'agencyMode'}, - {relation: 'warehouse'}, - {relation: 'state', - scope: { - fields: ['stateFk'], - include: { - relation: 'state' - } - }, - }, - ] - } - } - }; - - let json = encodeURIComponent(JSON.stringify(filter)); - this.$http.get(`Stowaways?filter=${json}`).then(res => { - this.ticketStowaways = res.data; - this.$scope.dialog.show(); - }); - } - } - - deleteStowaway(response) { - if (response === 'accept') { - this.$http.delete(`Stowaways/${this.stowawayToDelete.id}`).then(res => { - this.cardReload(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); - }); - } - } - - showDeleteConfirm(index) { - this.stowawayToDelete = this.ticketStowaways[index]; - this.$scope.confirmationDialog.show(); - } - - show() { - this.getTicketStowaways(); - } - - hide() { - this.$scope.dialog.hide(); - } -} - -Controller.$inject = ['$state', '$scope', '$http', 'vnApp', '$translate']; - -ngModule.component('vnRemoveStowaway', { - template: require('./removeStowaway.html'), - controller: Controller, - bindings: { - ticket: '<', - cardReload: '&?' - } -}); diff --git a/modules/ticket/front/descriptor/style.scss b/modules/ticket/front/descriptor/style.scss index e0abcbc50..4becf9789 100644 --- a/modules/ticket/front/descriptor/style.scss +++ b/modules/ticket/front/descriptor/style.scss @@ -1,6 +1,6 @@ @import "variables"; -vn-add-stowaway { +.add-stowaway { vn-data-viewer { width: 40em } diff --git a/modules/ticket/front/index.js b/modules/ticket/front/index.js index f8433b5fe..58ee9136e 100644 --- a/modules/ticket/front/index.js +++ b/modules/ticket/front/index.js @@ -6,7 +6,6 @@ import './search-panel'; import './card'; import './descriptor'; import './descriptor/addStowaway'; -import './descriptor/removeStowaway'; import './descriptor-popover'; import './create/card'; import './create/index'; diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml index 2b7f75c0c..b26a6d6fa 100644 --- a/modules/ticket/front/locale/es.yml +++ b/modules/ticket/front/locale/es.yml @@ -14,8 +14,8 @@ Counter: Contador Created : Añadido Date : Fecha Delay: Retraso -Delete: Borrar -Delete expedition: Borrar expedición +Delete: Eliminar +Delete expedition: Eliminar expedición Description: Descripción Discount: Descuento Employee : Empleado @@ -42,7 +42,7 @@ PPU: Ud. Price: Precio Price gap: Diferencia de precio Quantity: Cantidad -Remove lines: Borrar lineas +Remove lines: Eliminar lineas Route: Ruta SET OK: PONER OK Shipment: Salida diff --git a/modules/ticket/front/sale/locale/es.yml b/modules/ticket/front/sale/locale/es.yml index f381eb6e6..3ccdd528e 100644 --- a/modules/ticket/front/sale/locale/es.yml +++ b/modules/ticket/front/sale/locale/es.yml @@ -1,7 +1,7 @@ New price: Nuevo precio Add item: Añadir artículo Add turn: Añadir a turno -Delete ticket: Borrar ticket +Delete ticket: Eliminar ticket Mark as reserved: Marcar como reservado Unmark as reserved: Desmarcar como reservado Update discount: Actualizar descuento @@ -10,7 +10,7 @@ Edit discount: Editar descuento Transfer to ticket: Transferir a ticket New ticket: Nuevo ticket Edit price: Editar precio -You are going to delete lines of the ticket: Vas a borrar lineas del ticket +You are going to delete lines of the ticket: Vas a eliminar lineas del ticket This ticket will be removed from current route! Continue anyway?: ¡Se eliminará el ticket de la ruta actual! ¿Continuar de todas formas? You have to allow pop-ups in your web browser to use this functionality: Debes permitir los pop-pups en tu navegador para que esta herramienta funcione correctamente @@ -29,5 +29,5 @@ SMSAvailability: >- {{notAvailables}} no disponible/s. Disculpe las molestias. Continue anyway?: ¿Continuar de todas formas? This ticket is now empty: El ticket ha quedado vacio -Do you want to delete it?: ¿Quieres borrarlo? +Do you want to delete it?: ¿Quieres eliminarlo? Recalculate price: Recalcular precio \ No newline at end of file diff --git a/modules/worker/front/time-control/locale/es.yml b/modules/worker/front/time-control/locale/es.yml index 2f92657dd..1d28b0e2b 100644 --- a/modules/worker/front/time-control/locale/es.yml +++ b/modules/worker/front/time-control/locale/es.yml @@ -5,7 +5,7 @@ Hours: Horas Add time: Añadir hora Week total: Total semana Current week: Semana actual -This time entry will be deleted: Se borrará la hora fichada +This time entry will be deleted: Se eliminará la hora fichada Are you sure you want to delete this entry?: ¿Seguro que quieres eliminarla? Finish at: Termina a las Entry removed: Fichada borrada \ No newline at end of file From aab970e667ebe9d93f6261afc9288189ab0ed536 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Tue, 17 Dec 2019 09:11:28 +0100 Subject: [PATCH 13/59] client.phone section --- back/models/user-phone-type.json | 10 +++- db/changes/10100-allSaints/00-ACL.sql | 2 +- db/dump/fixtures.sql | 30 +++++------ e2e/helpers/selectors.js | 2 - .../02_edit_basic_data.spec.js | 36 ------------- modules/client/back/methods/client/getCard.js | 2 + modules/client/back/methods/client/summary.js | 3 ++ modules/client/back/models/client.json | 7 ++- modules/client/front/basic-data/index.html | 14 ------ modules/client/front/contact/index.js | 35 ------------- modules/client/front/index.js | 2 +- modules/client/front/index/index.html | 4 -- .../front/{contact => phones}/index.html | 47 +++++++++-------- modules/client/front/phones/index.js | 44 ++++++++++++++++ modules/client/front/phones/index.spec.js | 50 +++++++++++++++++++ modules/client/front/routes.json | 10 ++-- modules/client/front/summary/index.html | 8 ++- 17 files changed, 164 insertions(+), 142 deletions(-) delete mode 100644 modules/client/front/contact/index.js rename modules/client/front/{contact => phones}/index.html (51%) create mode 100644 modules/client/front/phones/index.js create mode 100644 modules/client/front/phones/index.spec.js diff --git a/back/models/user-phone-type.json b/back/models/user-phone-type.json index 479f02d6f..9410bd8db 100644 --- a/back/models/user-phone-type.json +++ b/back/models/user-phone-type.json @@ -14,5 +14,13 @@ "description": { "type": "String" } - } + }, + "acls": [ + { + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + } + ] } diff --git a/db/changes/10100-allSaints/00-ACL.sql b/db/changes/10100-allSaints/00-ACL.sql index ea1ba706b..39b52df5d 100644 --- a/db/changes/10100-allSaints/00-ACL.sql +++ b/db/changes/10100-allSaints/00-ACL.sql @@ -1 +1 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', 'WRITE', 'ALLOW', 'ROLE', 'employee'); +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index b57575e02..53bb9ff23 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -205,23 +205,23 @@ INSERT INTO `vn`.`contactChannel`(`id`, `name`) (4, 'GCN Channel'), (5, 'The Newspaper'); -INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`phone`,`mobile`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) +INSERT INTO `vn`.`client`(`id`,`name`,`fi`,`socialName`,`contact`,`street`,`city`,`postcode`,`fax`,`isRelevant`,`email`,`iban`,`dueDay`,`accountingAccount`,`isEqualizated`,`provinceFk`,`hasToInvoice`,`credit`,`countryFk`,`isActive`,`gestdocFk`,`quality`,`payMethodFk`,`created`,`isToBeMailed`,`contactChannelFk`,`hasSepaVnl`,`hasCoreVnl`,`hasCoreVnh`,`riskCalculated`,`clientTypeFk`,`mailAddress`,`cplusTerIdNifFk`,`hasToInvoiceByAddress`,`isTaxDataChecked`,`isFreezed`,`creditInsurance`,`isCreatedAsServed`,`hasInvoiceSimplified`,`salesPersonFk`,`isVies`,`eypbc`) VALUES - (101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), - (105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), - (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'Evil hideout', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1), - (107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), - (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), - (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), - (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1), - (111, 'Missing', NULL, 'Missing man', 'Anton', 'The space', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1), - (112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city', 'Silla', 46460, 1111111111, 222222222, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1); + (101, 'Bruce Wayne', '84612325V', 'Batman', 'Alfred', '1007 Mountain Drive, Gotham', 'Silla', 46460, 333333333, 1, 'BruceWayne@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (102, 'Petter Parker', '87945234L', 'Spider man', 'Aunt May', '20 Ingram Street', 'Silla', 46460, 333333333, 1, 'PetterParker@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (103, 'Clark Kent', '06815934E', 'Super man', 'lois lane', '344 Clinton Street', 'Silla', 46460, 333333333, 1, 'ClarkKent@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 0, 19, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (104, 'Tony Stark', '06089160W', 'Iron man', 'Pepper Potts', '10880 Malibu Point', 'Silla', 46460, 333333333, 1, 'TonyStark@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 18, 0, 1), + (105, 'Max Eisenhardt', '251628698', 'Magneto', 'Rogue', 'Unknown Whereabouts', 'Silla', 46460, 333333333, 1, 'MaxEisenhardt@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 8, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 18, 0, 1), + (106, 'DavidCharlesHaller', '53136686Q', 'Legion', 'Charles Xavier', 'Evil hideout', 'Silla', 46460, 333333333, 1, 'DavidCharlesHaller@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 0, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 0, NULL, 0, 0, 19, 0, 1), + (107, 'Hank Pym', '09854837G', 'Ant man', 'Hawk', 'Anthill', 'Silla', 46460, 333333333, 1, 'HankPym@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), + (108, 'Charles Xavier', '22641921P', 'Professor X', 'Beast', '3800 Victory Pkwy, Cincinnati, OH 45207, USA', 'Silla', 46460, 333333333, 1, 'CharlesXavier@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 1, 1, NULL, 0, 0, 19, 0, 1), + (109, 'Bruce Banner', '16104829E', 'Hulk', 'Black widow', 'Somewhere in New York', 'Silla', 46460, 333333333, 1, 'BruceBanner@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, 19, 0, 1), + (110, 'Jessica Jones', '58282869H', 'Jessica Jones', 'Luke Cage', 'NYCC 2015 Poster', 'Silla', 46460, 333333333, 1, 'JessicaJones@mydomain.com', NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 1, NULL, 1, 1, 0, 0, NULL, 0, 0, NULL, 0, 1), + (111, 'Missing', NULL, 'Missing man', 'Anton', 'The space', 'Silla', 46460, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1), + (112, 'Trash', NULL, 'Garbage man', 'Unknown name', 'New York city', 'Silla', 46460, 333333333, 1, NULL, NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1, NULL, 10, 5,CURDATE(), 1, 5, 1, 1, 1, '0000-00-00', 4, NULL, 1, 0, 1, 0, NULL, 1, 0, NULL, 0, 1); -INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `phone`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) - SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'SILLA', 46460, 623111111, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, CURDATE(), 1 +INSERT INTO `vn`.`client`(`id`, `name`, `fi`, `socialName`, `contact`, `street`, `city`, `postcode`, `isRelevant`, `email`, `iban`,`dueDay`,`accountingAccount`, `isEqualizated`, `provinceFk`, `hasToInvoice`, `credit`, `countryFk`, `isActive`, `gestdocFk`, `quality`, `payMethodFk`,`created`, `isTaxDataChecked`) + SELECT id, name, CONCAT(RPAD(CONCAT(id,9),8,id),'A'), CONCAT(name, 'Social'), CONCAT(name, 'Contact'), CONCAT(name, 'Street'), 'SILLA', 46460, 1, CONCAT(name,'@mydomain.com'), NULL, 0, 1234567890, 0, 1, 1, 300, 1, 1,NULL, 10, 5, CURDATE(), 1 FROM `account`.`role` `r` WHERE `r`.`hasLogin` = 1; diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index d752b265f..daff34db8 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -50,8 +50,6 @@ export default { basicDataButton: 'vn-left-menu a[ui-sref="client.card.basicData"]', nameInput: 'vn-textfield[ng-model="$ctrl.client.name"] input', contactInput: 'vn-textfield[ng-model="$ctrl.client.contact"] input', - phoneInput: 'vn-textfield[ng-model="$ctrl.client.phone"] input', - mobileInput: 'vn-textfield[ng-model="$ctrl.client.mobile"] input', emailInput: 'vn-textfield[ng-model="$ctrl.client.email"] input', salesPersonAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', channelAutocomplete: 'vn-autocomplete[ng-model="$ctrl.client.contactChannelFk"]', diff --git a/e2e/paths/02-client-module/02_edit_basic_data.spec.js b/e2e/paths/02-client-module/02_edit_basic_data.spec.js index 988ad82c8..dc0631613 100644 --- a/e2e/paths/02-client-module/02_edit_basic_data.spec.js +++ b/e2e/paths/02-client-module/02_edit_basic_data.spec.js @@ -27,10 +27,6 @@ describe('Client Edit basicData path', () => { .write(selectors.clientBasicData.nameInput, 'Ptonomy Wallace') .clearInput(selectors.clientBasicData.contactInput) .write(selectors.clientBasicData.contactInput, 'David Haller') - .clearInput(selectors.clientBasicData.phoneInput) - .write(selectors.clientBasicData.phoneInput, '987654321') - .clearInput(selectors.clientBasicData.mobileInput) - .write(selectors.clientBasicData.mobileInput, '123456789') .clearInput(selectors.clientBasicData.emailInput) .write(selectors.clientBasicData.emailInput, 'PWallace@verdnatura.es') .autocompleteSearch(selectors.clientBasicData.channelAutocomplete, 'Rumors on the streets') @@ -55,20 +51,6 @@ describe('Client Edit basicData path', () => { expect(result).toEqual('David Haller'); }); - it('should confirm the landline phone number have been added', async() => { - const result = await nightmare - .waitToGetProperty(selectors.clientBasicData.phoneInput, 'value'); - - expect(result).toEqual('987654321'); - }); - - it('should confirm the mobile phone number have been added', async() => { - const result = await nightmare - .waitToGetProperty(selectors.clientBasicData.mobileInput, 'value'); - - expect(result).toEqual('123456789'); - }); - it('should confirm the email have been edited', async() => { const result = await nightmare .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); @@ -108,10 +90,6 @@ describe('Client Edit basicData path', () => { .write(selectors.clientBasicData.nameInput, 'Ororo Munroe') .clearInput(selectors.clientBasicData.contactInput) .write(selectors.clientBasicData.contactInput, 'Black Panther') - .clearInput(selectors.clientBasicData.phoneInput) - .write(selectors.clientBasicData.phoneInput, '123456789') - .clearInput(selectors.clientBasicData.mobileInput) - .write(selectors.clientBasicData.mobileInput, '987654321') .clearInput(selectors.clientBasicData.emailInput) .write(selectors.clientBasicData.emailInput, 'Storm@verdnatura.es') .autocompleteSearch(selectors.clientBasicData.salesPersonAutocomplete, 'replenisherNick') @@ -137,20 +115,6 @@ describe('Client Edit basicData path', () => { expect(result).toEqual('Black Panther'); }); - it('should now confirm the landline phone number have been added', async() => { - const result = await nightmare - .waitToGetProperty(selectors.clientBasicData.phoneInput, 'value'); - - expect(result).toEqual('123456789'); - }); - - it('should now confirm the mobile phone number have been added', async() => { - const result = await nightmare - .waitToGetProperty(selectors.clientBasicData.mobileInput, 'value'); - - expect(result).toEqual('987654321'); - }); - it('should now confirm the email have been edited', async() => { const result = await nightmare .waitToGetProperty(selectors.clientBasicData.emailInput, 'value'); diff --git a/modules/client/back/methods/client/getCard.js b/modules/client/back/methods/client/getCard.js index 6c69d32a8..e3b0edf8a 100644 --- a/modules/client/back/methods/client/getCard.js +++ b/modules/client/back/methods/client/getCard.js @@ -60,6 +60,8 @@ module.exports = function(Self) { scope: { fields: ['id', 'name', 'active'] } + }, { + relation: 'phones' } ] }); diff --git a/modules/client/back/methods/client/summary.js b/modules/client/back/methods/client/summary.js index 155d95d9e..13e898f09 100644 --- a/modules/client/back/methods/client/summary.js +++ b/modules/client/back/methods/client/summary.js @@ -53,6 +53,9 @@ module.exports = Self => { } } }, + { + relation: 'phones' + }, { relation: 'country', scope: { diff --git a/modules/client/back/models/client.json b/modules/client/back/models/client.json index c62ae3832..4529b3caf 100644 --- a/modules/client/back/models/client.json +++ b/modules/client/back/models/client.json @@ -200,6 +200,11 @@ "type": "hasOne", "model": "ClaimRatio", "foreignKey": "clientFk" - } + }, + "phones": { + "type": "hasMany", + "model": "UserPhone", + "foreignKey": "userFk" + } } } \ No newline at end of file diff --git a/modules/client/front/basic-data/index.html b/modules/client/front/basic-data/index.html index 8c00f7a18..fbf883d98 100644 --- a/modules/client/front/basic-data/index.html +++ b/modules/client/front/basic-data/index.html @@ -31,20 +31,6 @@ info="You can save multiple emails">
- - - - - - { - this.$scope.watcher.notifySaved(); - this.$scope.model.refresh(); - }); - } -} - -Controller.$inject = ['$scope', '$stateParams', '$translate']; - -ngModule.component('vnClientContact', { - template: require('./index.html'), - controller: Controller, - bindings: { - client: '<' - } -}); diff --git a/modules/client/front/index.js b/modules/client/front/index.js index 324046206..514319ee2 100644 --- a/modules/client/front/index.js +++ b/modules/client/front/index.js @@ -30,7 +30,7 @@ import './credit-insurance/index'; import './credit-insurance/create'; import './credit-insurance/insurance/index'; import './credit-insurance/insurance/create'; -import './contact'; +import './phones'; import './sample/index'; import './sample/create'; import './web-payment'; diff --git a/modules/client/front/index/index.html b/modules/client/front/index/index.html index 35a5234aa..184f18727 100644 --- a/modules/client/front/index/index.html +++ b/modules/client/front/index/index.html @@ -25,10 +25,6 @@ label="Id" value="{{::client.id}}"> - - diff --git a/modules/client/front/contact/index.html b/modules/client/front/phones/index.html similarity index 51% rename from modules/client/front/contact/index.html rename to modules/client/front/phones/index.html index 2cefdd86d..c0966ce0f 100644 --- a/modules/client/front/contact/index.html +++ b/modules/client/front/phones/index.html @@ -1,45 +1,48 @@ + + + url="UserPhones" + data="$ctrl.phones"> + data="$ctrl.phones"> - - - + + + + ng-model="clientPhone.phone"> + ng-click="model.remove($index)" + tabindex="-1"> @@ -48,4 +51,4 @@ - \ No newline at end of file + diff --git a/modules/client/front/phones/index.js b/modules/client/front/phones/index.js new file mode 100644 index 000000000..9839d27d7 --- /dev/null +++ b/modules/client/front/phones/index.js @@ -0,0 +1,44 @@ +import ngModule from '../module'; +import Section from 'salix/components/section'; + +class Controller extends Section { + get client() { + return this._client; + } + + set client(value) { + this._client = value; + if (value) + this.setLink(value); + } + + setLink(value) { + this.$.$applyAsync(()=> { + this.$.model.link = {userFk: value.id}; + this.$.model.refresh(); + }); + } + + onSubmit() { + this.$.watcher.check(); + return this.$.model.save().then(() => { + this.$.watcher.updateOriginalData(); + this.$.watcher.notifySaved(); + this.card.reload(); + }); + } + + add() { + this.$.model.insert(); + } +} + + +ngModule.component('vnClientPhones', { + template: require('./index.html'), + controller: Controller, + require: {card: '^vnClientCard'}, + bindings: { + client: '<' + } +}); diff --git a/modules/client/front/phones/index.spec.js b/modules/client/front/phones/index.spec.js new file mode 100644 index 000000000..3d0befd68 --- /dev/null +++ b/modules/client/front/phones/index.spec.js @@ -0,0 +1,50 @@ +import './index'; +import watcher from 'core/mocks/watcher'; + +describe('Component vnClientPhones', () => { + let controller; + let $element; + let $scope; + + beforeEach(ngModule('client')); + + beforeEach(angular.mock.inject(($componentController, $rootScope) => { + $scope = $rootScope.$new(); + $element = angular.element('
'); + $scope.watcher = watcher; + $scope.model = { + link: 1, + save: () => {} + }; + controller = $componentController('vnClientPhones', {$element, $scope}); + controller.card = {reload: () => {}}; + })); + + describe('setLink()', () => { + it('set the link in the model and refreshes it', () => { + spyOn(controller.$, '$applyAsync'); + let value = {id: 106}; + controller.setLink(value); + + expect(controller.$.$applyAsync).toHaveBeenCalledWith(jasmine.any(Function)); + }); + }); + + describe('onSubmit()', () => { + it('should call watcher functions, reload the card and save the model', done => { + spyOn(controller.$.watcher, 'check'); + spyOn(controller.$.model, 'save').and.returnValue(Promise.resolve()); + + spyOn(controller.$.watcher, 'updateOriginalData'); + spyOn(controller.$.watcher, 'notifySaved'); + spyOn(controller.card, 'reload'); + controller.onSubmit(); + controller.onSubmit().then(() => { + expect(controller.$.watcher.updateOriginalData).toHaveBeenCalledWith(); + expect(controller.$.watcher.notifySaved).toHaveBeenCalledWith(); + expect(controller.card.reload).toHaveBeenCalledWith(); + done(); + }).catch(done.fail); + }); + }); +}); diff --git a/modules/client/front/routes.json b/modules/client/front/routes.json index ef0d8cc7a..6d96bd284 100644 --- a/modules/client/front/routes.json +++ b/modules/client/front/routes.json @@ -26,7 +26,7 @@ {"state": "client.card.webAccess", "icon": "cloud"}, {"state": "client.card.mandate", "icon": "pan_tool"}, {"state": "client.card.creditInsurance.index", "icon": "icon-solunion"}, - {"state": "client.card.contact", "icon": "contact_phone"}, + {"state": "client.card.phones", "icon": "contact_phone"}, {"state": "client.card.sample.index", "icon": "mail"}, {"state": "client.card.webPayment", "icon": "icon-onlinepayment"}, {"state": "client.card.dms.index", "icon": "cloud_upload"} @@ -282,10 +282,10 @@ "client": "$ctrl.client" } }, { - "url": "/contact", - "state": "client.card.contact", - "component": "vn-client-contact", - "description": "Contacts", + "url": "/phones", + "state": "client.card.phones", + "component": "vn-client-phones", + "description": "Client phones", "params": { "client": "$ctrl.client" } diff --git a/modules/client/front/summary/index.html b/modules/client/front/summary/index.html index eccf45873..7016a19ff 100644 --- a/modules/client/front/summary/index.html +++ b/modules/client/front/summary/index.html @@ -12,11 +12,9 @@ - - - + From d1341c275801c774d5fe39c0424963be127c551c Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 17 Dec 2019 09:23:11 +0100 Subject: [PATCH 14/59] Hotfixes --- .vscode/settings.json | 5 ++++- modules/claim/front/index/index.html | 2 +- modules/worker/front/department/index.html | 3 --- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index deb4b49e1..2298e4846 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,5 +3,8 @@ // Carácter predeterminado de final de línea. "files.eol": "\n", "vsicons.presets.angular": false, - "eslint.autoFixOnSave": true + "eslint.autoFixOnSave": true, + "editor.codeActionsOnSave": { + "source.fixAll.eslint": true + } } \ No newline at end of file diff --git a/modules/claim/front/index/index.html b/modules/claim/front/index/index.html index c85632571..383e55a9d 100644 --- a/modules/claim/front/index/index.html +++ b/modules/claim/front/index/index.html @@ -11,7 +11,7 @@ + class="vn-w-lg"> diff --git a/modules/worker/front/department/index.html b/modules/worker/front/department/index.html index e77d11e12..d50d33ace 100644 --- a/modules/worker/front/department/index.html +++ b/modules/worker/front/department/index.html @@ -16,9 +16,6 @@ {{::item.name}} - - - Date: Tue, 17 Dec 2019 12:18:17 +0100 Subject: [PATCH 15/59] ACL fixes --- modules/claim/front/summary/index.html | 2 +- modules/travel/front/routes.json | 3 +-- modules/worker/front/routes.json | 17 +++++++++++------ 3 files changed, 13 insertions(+), 9 deletions(-) diff --git a/modules/claim/front/summary/index.html b/modules/claim/front/summary/index.html index c5d954057..20dca702b 100644 --- a/modules/claim/front/summary/index.html +++ b/modules/claim/front/summary/index.html @@ -87,7 +87,7 @@
+ zoom-image="/api/dms/{{::photo.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}">
diff --git a/modules/travel/front/routes.json b/modules/travel/front/routes.json index 357ffffc2..d9b520816 100644 --- a/modules/travel/front/routes.json +++ b/modules/travel/front/routes.json @@ -24,8 +24,7 @@ "url": "/index?q", "state": "travel.index", "component": "vn-travel-index", - "description": "Travels", - "acl": ["developer"] + "description": "Travels" }, { "url": "/:id", "state": "travel.card", diff --git a/modules/worker/front/routes.json b/modules/worker/front/routes.json index d117cf18c..6414c9ed2 100644 --- a/modules/worker/front/routes.json +++ b/modules/worker/front/routes.json @@ -51,7 +51,7 @@ "params": { "worker": "$ctrl.worker" }, - "acl": ["developer"] + "acl": ["hr"] }, { "url": "/pbx", "state": "worker.card.pbx", @@ -81,7 +81,8 @@ "url" : "/department", "state": "worker.department", "component": "vn-worker-department", - "description": "Departments" + "description": "Departments", + "acl": ["hr"] }, { "url": "/phones", "state": "worker.card.phones", @@ -89,7 +90,8 @@ "description": "Phones", "params": { "worker": "$ctrl.worker" - } + }, + "acl": ["hr"] }, { "url": "/dms", @@ -101,7 +103,8 @@ "url": "/index", "state": "worker.card.dms.index", "component": "vn-worker-dms-index", - "description": "File management" + "description": "File management", + "acl": ["hr"] }, { "url": "/create", @@ -110,7 +113,8 @@ "description": "Upload file", "params": { "worker": "$ctrl.worker" - } + }, + "acl": ["hr"] }, { "url": "/:dmsId/edit", @@ -119,7 +123,8 @@ "description": "Edit file", "params": { "worker": "$ctrl.worker" - } + }, + "acl": ["hr"] } ] } \ No newline at end of file From 4da83ef963e2ef58636032b2f1c2b88d69a4e6fe Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 17 Dec 2019 12:23:31 +0100 Subject: [PATCH 16/59] Hotfixes: vnTicketSale menu, vnItemDiary width --- modules/item/front/diary/index.html | 2 +- modules/ticket/front/sale/index.js | 19 ++++++++----------- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/modules/item/front/diary/index.html b/modules/item/front/diary/index.html index 720a42fb7..f3c9ff63a 100644 --- a/modules/item/front/diary/index.html +++ b/modules/item/front/diary/index.html @@ -6,7 +6,7 @@ auto-load="false"> - + this.isEditable - }, - { + }, { name: 'Unmark as reserved', callback: this.unmarkAsReserved, show: () => this.isEditable - }, - { + }, { name: 'Update discount', callback: this.showEditDialog, show: () => this.isEditable - }, - { + }, { name: 'Add claim', - callback: this.createClaim, - show: () => this.isEditable - }, - { + callback: this.createClaim + }, { name: 'Recalculate price', callback: this.calculateSalePrice, show: () => this.hasOneSaleSelected() From 7d47757c64414b6b670970e5715ddb1008b9d59c Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Tue, 17 Dec 2019 13:03:09 +0100 Subject: [PATCH 17/59] fixed claim responsibility --- front/core/components/range/index.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/front/core/components/range/index.js b/front/core/components/range/index.js index 80410875a..88463e7cf 100644 --- a/front/core/components/range/index.js +++ b/front/core/components/range/index.js @@ -6,6 +6,16 @@ export default class Range extends FormInput { constructor($element, $scope) { super($element, $scope); this.input = this.element.querySelector('input'); + this.input.addEventListener('change', () => this.onValueUpdate()); + } + + get field() { + return super.field; + } + + set field(value) { + this.input.value = value; + super.field = value; } get max() { @@ -35,6 +45,11 @@ export default class Range extends FormInput { refreshTabIndex() { this.input.tabIndex = this.disabled ? -1 : this.tabIndex; } + + onValueUpdate() { + this.change(this.input.value); + this.$.$applyAsync(); + } } ngModule.vnComponent('vnRange', { From a39a35f1a1c8c2153cf8eaa46d201e607e9f8ee9 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Tue, 17 Dec 2019 13:18:58 +0100 Subject: [PATCH 18/59] 1941-autocomplete --- front/core/components/autocomplete/index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/front/core/components/autocomplete/index.js b/front/core/components/autocomplete/index.js index e2c9b7ad4..38c85db57 100755 --- a/front/core/components/autocomplete/index.js +++ b/front/core/components/autocomplete/index.js @@ -253,7 +253,7 @@ export default class Autocomplete extends Field { } showDropDown(search) { - if (this.readonly) return; + if (!this.editable) return; this.assignDropdownProps(); this.$.dropDown.show(this.container, search); } From 9d487f3ceecf4579161a08f4bd392a55aacd8e7d Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Tue, 17 Dec 2019 13:25:30 +0100 Subject: [PATCH 19/59] updated translation --- modules/ticket/front/descriptor/index.js | 2 +- modules/ticket/front/descriptor/locale/es.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/ticket/front/descriptor/index.js b/modules/ticket/front/descriptor/index.js index addcd825e..ef64bf84e 100644 --- a/modules/ticket/front/descriptor/index.js +++ b/modules/ticket/front/descriptor/index.js @@ -19,7 +19,7 @@ class Controller extends Component { show: () => this.canShowStowaway }, { - name: 'Remove stowaway', + name: 'Delete stowaway', callback: this.showDeleteStowaway, show: () => this.shouldShowDeleteStowaway() }, diff --git a/modules/ticket/front/descriptor/locale/es.yml b/modules/ticket/front/descriptor/locale/es.yml index 68512fec2..947377e19 100644 --- a/modules/ticket/front/descriptor/locale/es.yml +++ b/modules/ticket/front/descriptor/locale/es.yml @@ -5,7 +5,7 @@ Ship stowaways: Polizones del barco Stowaways to add: Polizones a añadir Stowaways of the ticket: Polizones del ticket Add stowaway: Añadir polizón -Remove stowaway: Eliminar polizón +Delete stowaway: Eliminar polizón Are you sure you want to delete this stowaway?: ¿Seguro que quieres eliminar este polizón? Are you sure you want to send it?: ¿Seguro que quieres enviarlo? Show Delivery Note: Ver albarán From 03af680968d793658d19fdea97e70160b32cec1b Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Wed, 18 Dec 2019 07:30:24 +0100 Subject: [PATCH 20/59] fix backtest --- .../back/methods/invoiceOut/specs/book.spec.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 345e29125..fece307de 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -2,13 +2,16 @@ const app = require('vn-loopback/server/server'); describe('invoiceOut book()', () => { const invoiceOutId = 1; - let invoiceOutRef; + let bookedDate; let OriginalInvoiceOut; let updatedInvoiceOut; - let bookedDate; afterAll(async done => { - updatedInvoiceOut.updateAttributes({booked: OriginalInvoiceOut.booked, hasPdf: OriginalInvoiceOut.hasPdf}); + updatedInvoiceOut.updateAttributes({ + booked: OriginalInvoiceOut.booked, + hasPdf: OriginalInvoiceOut.hasPdf, + amount: OriginalInvoiceOut.amount + }); done(); }); @@ -24,7 +27,7 @@ describe('invoiceOut book()', () => { it(`should confirm the book property have been updated`, async() => { OriginalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - invoiceOutRef = OriginalInvoiceOut.ref; + let invoiceOutRef = OriginalInvoiceOut.ref; await app.models.InvoiceOut.book(invoiceOutRef); From a1c6c0ab39e3eb64ded755b024ebb2e740d68539 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 19 Dec 2019 11:37:53 +0100 Subject: [PATCH 21/59] claim regularize refactor --- .../10130-christmas/00-greugeConfig.sql | 6 ++ db/changes/10130-christmas/00-greugeType.sql | 1 + modules/claim/front/action/index.js | 66 +++++++++++++------ modules/claim/front/action/index.spec.js | 27 ++++---- modules/claim/front/action/locale/en.yml | 1 + modules/claim/front/action/locale/es.yml | 3 +- modules/client/back/model-config.json | 3 + modules/client/back/models/greuge-config.json | 20 ++++++ modules/client/back/models/greuge-type.json | 25 +++---- modules/client/front/greuge/index/index.html | 4 +- 10 files changed, 110 insertions(+), 46 deletions(-) create mode 100644 db/changes/10130-christmas/00-greugeConfig.sql create mode 100644 db/changes/10130-christmas/00-greugeType.sql create mode 100644 modules/claim/front/action/locale/en.yml create mode 100644 modules/client/back/models/greuge-config.json diff --git a/db/changes/10130-christmas/00-greugeConfig.sql b/db/changes/10130-christmas/00-greugeConfig.sql new file mode 100644 index 000000000..f434c7fd7 --- /dev/null +++ b/db/changes/10130-christmas/00-greugeConfig.sql @@ -0,0 +1,6 @@ +CREATE TABLE `vn`.`greugeConfig` ( + `id` INT NOT NULL AUTO_INCREMENT, + `freightPickUpPrice` DECIMAL(10,2) NOT NULL, + PRIMARY KEY (`id`)); + +INSERT INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); diff --git a/db/changes/10130-christmas/00-greugeType.sql b/db/changes/10130-christmas/00-greugeType.sql new file mode 100644 index 000000000..3438ff923 --- /dev/null +++ b/db/changes/10130-christmas/00-greugeType.sql @@ -0,0 +1 @@ +INSERT INTO `vn`.`greugeType` (`id`, `name`, `code`) VALUES ('7', 'Freight Pickup ', 'freightPickUp'); diff --git a/modules/claim/front/action/index.js b/modules/claim/front/action/index.js index 7d67d58c9..873a783d7 100644 --- a/modules/claim/front/action/index.js +++ b/modules/claim/front/action/index.js @@ -2,12 +2,13 @@ import ngModule from '../module'; import './style.scss'; class Controller { - constructor($stateParams, $scope, $http, $translate, vnApp) { + constructor($stateParams, $scope, $http, $translate, vnApp, $httpParamSerializer) { this.$stateParams = $stateParams; this.$ = $scope; this.$http = $http; this.$translate = $translate; this.vnApp = vnApp; + this.$httpParamSerializer = $httpParamSerializer; this.filter = { where: {claimFk: $stateParams.id}, include: [ @@ -125,31 +126,57 @@ class Controller { let data = {claimFk: this.$stateParams.id}; let query = `Claims/regularizeClaim`; return this.$http.post(query, data).then(() => { - this.card.reload(); - this.vnApp.showSuccess(this.$translate.instant('Data saved!')); if (this.claim.responsibility >= Math.ceil(this.maxResponsibility) / 2) this.$.updateGreuge.show(); + else + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + + this.card.reload(); }); } + getGreugeTypeId() { + const params = {filter: {where: {code: 'freightPickUp'}}}; + const serializedParams = this.$httpParamSerializer(params); + const query = `GreugeTypes/findOne?${serializedParams}`; + return this.$http.get(query).then(res => { + this.greugeTypeFreightId = res.data.id; + }); + } + + getGreugeConfig() { + const query = `GreugeConfigs/findOne`; + return this.$http.get(query).then(res => { + this.freightPickUpPrice = res.data.freightPickUpPrice; + }); + } + + onUpdateGreugeResponse(response) { - if (response !== 'accept') - return; - let greugeTypeFreight = 7; - let query = `Greuges/`; - let data = { - clientFk: this.claim.clientFk, - description: `claim: ${this.claim.id}`, - amount: 11, - greugeTypeFk: greugeTypeFreight, - ticketFk: this.claim.ticketFk - }; + if (response == 'accept') { + const promises = []; + promises.push(this.getGreugeTypeId()); + promises.push(this.getGreugeConfig()); - this.$http.post(query, data).then(() => { - this.card.reload(); - this.vnApp.showSuccess(this.$translate.instant('Greuge inserted!')); - }); + Promise.all(promises).then(() => { + const data = { + clientFk: this.claim.clientFk, + description: this.$translate.instant('ClaimGreugeDescription', { + claimId: this.claim.id + }).toUpperCase(), + amount: this.freightPickUpPrice, + greugeTypeFk: this.greugeTypeFreightId, + ticketFk: this.claim.ticketFk + }; + this.$http.post(`Greuges/`, data).then(() => { + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); + this.vnApp.showMessage(this.$translate.instant('Greuge inserted')); + }); + }); + } else + this.vnApp.showSuccess(this.$translate.instant('Data saved!')); } + // Item Descriptor showDescriptor(event, itemFk) { this.$.descriptor.itemFk = itemFk; @@ -164,6 +191,7 @@ class Controller { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); }); } + saveMana(value) { let query = `Claims/${this.$stateParams.id}/updateClaimAction`; @@ -173,7 +201,7 @@ class Controller { } } -Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp']; +Controller.$inject = ['$stateParams', '$scope', '$http', '$translate', 'vnApp', '$httpParamSerializer']; ngModule.component('vnClaimAction', { template: require('./index.html'), diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index 56597fd2f..dfa680bef 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -6,15 +6,19 @@ describe('claim', () => { let controller; let $httpBackend; let $state; + let $httpParamSerializer; + let $scope; beforeEach(ngModule('claim')); - beforeEach(angular.mock.inject(($componentController, _$state_, _$httpBackend_) => { + beforeEach(angular.mock.inject(($rootScope, $componentController, _$state_, _$httpBackend_, _$httpParamSerializer_) => { + $scope = $rootScope.$new(); $httpBackend = _$httpBackend_; + $httpParamSerializer = _$httpParamSerializer_; $state = _$state_; $state.params.id = 1; - controller = $componentController('vnClaimAction', {$state}); + controller = $componentController('vnClaimAction', {$state, $scope}); controller.claim = {ticketFk: 1}; controller.$.model = {refresh: () => {}}; controller.$.addSales = { @@ -164,21 +168,16 @@ describe('claim', () => { it('should perform a insert into greuges', () => { spyOn(controller.card, 'reload'); spyOn(controller.vnApp, 'showSuccess'); - controller.claim.clientFk = 101; - controller.claim.id = 11; - let data = { - clientFk: 101, - description: `claim: ${controller.claim.id}`, - amount: 11, - greugeTypeFk: 7, - ticketFk: controller.claim.ticketFk - }; - $httpBackend.expect('POST', `Greuges/`, data).respond(); + + const greugeTypeParams = $httpParamSerializer({filter: {where: {code: 'freightPickUp'}}}); + $httpBackend.expect('GET', `GreugeTypes/findOne?${greugeTypeParams}`).respond({id: 7}); + $httpBackend.expect('GET', `GreugeConfigs/findOne`).respond({freightPickUpPrice: 11}); controller.onUpdateGreugeResponse('accept'); + $httpBackend.flush(); - expect(controller.card.reload).toHaveBeenCalledWith(); - expect(controller.vnApp.showSuccess).toHaveBeenCalledWith('Greuge inserted!'); + expect(controller.greugeTypeFreightId).toEqual(7); + expect(controller.freightPickUpPrice).toEqual(11); }); }); }); diff --git a/modules/claim/front/action/locale/en.yml b/modules/claim/front/action/locale/en.yml new file mode 100644 index 000000000..faab67c06 --- /dev/null +++ b/modules/claim/front/action/locale/en.yml @@ -0,0 +1 @@ +ClaimGreugeDescription: Claim id {{claimId}} \ No newline at end of file diff --git a/modules/claim/front/action/locale/es.yml b/modules/claim/front/action/locale/es.yml index 3950ec06a..db1a25755 100644 --- a/modules/claim/front/action/locale/es.yml +++ b/modules/claim/front/action/locale/es.yml @@ -8,4 +8,5 @@ Imports ticket lines: Importa las lineas de un ticket Regularize: Regularizar Do you want to insert greuges?: Desea insertar greuges? Insert greuges on client card: Insertar greuges en la ficha del cliente -Greuge inserted: Greuge insertado \ No newline at end of file +Greuge inserted: Greuge insertado +ClaimGreugeDescription: Reclamación id {{claimId}} \ No newline at end of file diff --git a/modules/client/back/model-config.json b/modules/client/back/model-config.json index 3aa709eb7..670b7d2ca 100644 --- a/modules/client/back/model-config.json +++ b/modules/client/back/model-config.json @@ -50,6 +50,9 @@ "GreugeType": { "dataSource": "vn" }, + "GreugeConfig": { + "dataSource": "vn" + }, "Mandate": { "dataSource": "vn" }, diff --git a/modules/client/back/models/greuge-config.json b/modules/client/back/models/greuge-config.json new file mode 100644 index 000000000..b72348023 --- /dev/null +++ b/modules/client/back/models/greuge-config.json @@ -0,0 +1,20 @@ +{ + "name": "GreugeConfig", + "base": "VnModel", + "options": { + "mysql": { + "table": "greugeConfig" + } + }, + "properties": { + "freightPickUpPrice": { + "type": "Number" + } + }, + "acls": [{ + "accessType": "READ", + "principalType": "ROLE", + "principalId": "$everyone", + "permission": "ALLOW" + }] +} diff --git a/modules/client/back/models/greuge-type.json b/modules/client/back/models/greuge-type.json index cafe1f7fc..5c5b1870d 100644 --- a/modules/client/back/models/greuge-type.json +++ b/modules/client/back/models/greuge-type.json @@ -2,19 +2,22 @@ "name": "GreugeType", "base": "VnModel", "options": { - "mysql": { - "table": "greugeType" - } + "mysql": { + "table": "greugeType" + } }, "properties": { - "id": { - "id": true, - "type": "Number", - "description": "Identifier" - }, - "name": { - "type": "String" - } + "id": { + "id": true, + "type": "Number", + "description": "Identifier" + }, + "name": { + "type": "String" + }, + "code": { + "type": "String" + } }, "acls": [ { diff --git a/modules/client/front/greuge/index/index.html b/modules/client/front/greuge/index/index.html index 636caaca2..683ac0afe 100644 --- a/modules/client/front/greuge/index/index.html +++ b/modules/client/front/greuge/index/index.html @@ -37,7 +37,9 @@ {{::greuge.shipped | date:'dd/MM/yyyy HH:mm' }} - {{::greuge.description}} + + {{::greuge.description}} + {{::greuge.greugeType.name}} {{::greuge.amount | currency: 'EUR': 2}} From 99470217362ac8844589e46a639c5d75e22ee90c Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 12:17:53 +0100 Subject: [PATCH 22/59] #1953 Temporal fix --- modules/ticket/back/methods/ticket/new.js | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index 25e5a08c5..7ddde8785 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -26,17 +26,22 @@ module.exports = Self => { let address = await models.Address.findOne({ where: {id: params.addressFk}, fields: ['id', 'clientFk'], - include: [ - {relation: 'client', - scope: { - include: { - relation: 'type' - } + include: { + relation: 'client', + scope: { + include: { + relation: 'type' } } - ] + } }); + // FIXME: #1953 Params should be declared with it's correct argument type + if (params.shipped) + params.shipped = new Date(params.shipped); + if (params.landed) + params.landed = new Date(params.landed); + if (!address) throw new UserError(`This address doesn't exist`); From 7fa22da619f130ef8e23c5fe581dd614f017809c Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 19 Dec 2019 12:42:50 +0100 Subject: [PATCH 23/59] Use country code as default language --- print/core/mixins/user-locale.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/print/core/mixins/user-locale.js b/print/core/mixins/user-locale.js index f8001aefc..f30bc0b28 100644 --- a/print/core/mixins/user-locale.js +++ b/print/core/mixins/user-locale.js @@ -13,8 +13,11 @@ const userLocale = { methods: { getLocale(clientId) { return db.findOne(` - SELECT lang FROM account.user - WHERE id = ?`, [clientId]).then(rows => { + SELECT IF(u.lang IS NOT NULL, u.lang, LOWER(ct.code)) lang + FROM client c + JOIN country ct ON ct.id = c.countryFk + JOIN account.user u ON u.id = c.id + WHERE c.id = ?`, [clientId]).then(rows => { if (rows) return rows.lang; else return fallbackLocale; From 8a54da6fd362d51fb535703fc81cb06a40627a3b Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 19 Dec 2019 14:13:24 +0100 Subject: [PATCH 24/59] fixed dms links --- modules/client/front/dms/index/index.html | 4 ++-- modules/ticket/front/dms/index/index.html | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/client/front/dms/index/index.html b/modules/client/front/dms/index/index.html index e45821a4a..e20dbd6f4 100644 --- a/modules/client/front/dms/index/index.html +++ b/modules/client/front/dms/index/index.html @@ -61,7 +61,7 @@ {{::document.dms.file}} + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}">{{::document.dms.file}} @@ -74,7 +74,7 @@ + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> diff --git a/modules/ticket/front/dms/index/index.html b/modules/ticket/front/dms/index/index.html index 278427338..ae2844c73 100644 --- a/modules/ticket/front/dms/index/index.html +++ b/modules/ticket/front/dms/index/index.html @@ -59,7 +59,7 @@ + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> {{::document.dms.file}} @@ -73,7 +73,7 @@ + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> From aa809eea8a4481e2d7d1046a370a17815b4b6fc9 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 19 Dec 2019 14:21:18 +0100 Subject: [PATCH 25/59] trigger build --- modules/client/front/dms/index/index.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/client/front/dms/index/index.html b/modules/client/front/dms/index/index.html index e20dbd6f4..9ecafe887 100644 --- a/modules/client/front/dms/index/index.html +++ b/modules/client/front/dms/index/index.html @@ -61,7 +61,8 @@ {{::document.dms.file}} + href="api/dms/{{::document.dmsFk}}/downloadFile?access_token={{::$ctrl.accessToken}}"> + {{::document.dms.file}} From d5a9a62f73b177443a67e9bf55d5e562ffac511a Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 14:27:29 +0100 Subject: [PATCH 26/59] Deploy with docker swarm --- Jenkinsfile | 62 ++++++++++++++-------------------------------- docker-compose.yml | 4 +++ gulpfile.js | 22 +++++++++++----- 3 files changed, 38 insertions(+), 50 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 0aaba1e93..b888e57bc 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -8,19 +8,17 @@ pipeline { environment { PROJECT_NAME = 'salix' REGISTRY = 'registry.verdnatura.es' - DOCKER_HOST_1 = 'vch1.verdnatura.es' - DOCKER_HOST_2 = 'vch2.verdnatura.es' PORT_MASTER_FRONT = '5002' - PORT_MASTER_BACK = '3001-3002' + PORT_MASTER_BACK = '3001' PORT_TEST_FRONT = '5001' - PORT_TEST_BACK = '4001-4002' + PORT_TEST_BACK = '4001' TAG = "${env.BRANCH_NAME}" } stages { stage('Checkout') { steps { script { - env.COMPOSE_PROJECT_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" + env.STACK_NAME = "${env.PROJECT_NAME}-${env.BRANCH_NAME}" if (!env.GIT_COMMITTER_EMAIL) { env.COMMITTER_EMAIL = sh( @@ -65,18 +63,21 @@ pipeline { } } stage('Test') { - when { not { anyOf { - branch 'test' - branch 'master' - }}} environment { NODE_ENV = "" - FIREFOX_BIN = "/opt/firefox/firefox-bin" } - steps { - nodejs('node-lts') { - sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' - sh 'gulp backTestDockerOnce --junit --random' + parallel { + steps { + stage('Frontend') { + nodejs('node-lts') { + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' + } + } + stage('Backend') { + nodejs('node-lts') { + sh 'gulp backTestDockerOnce --junit --random' + } + } } } } @@ -96,6 +97,7 @@ pipeline { sh 'docker login --username $CREDS_USR --password $CREDS_PSW $REGISTRY' sh 'docker-compose build --parallel' sh 'docker-compose push' + sh 'docker logout $REGISTRY' } } stage('Deploy') { @@ -107,27 +109,8 @@ pipeline { DOCKER_TLS_VERIFY = 1 } parallel { - stage('Host 1') { - environment { - DOCKER_HOST = "tcp://${env.DOCKER_HOST_1}:2376" - } - steps { - withCredentials([dockerCert(credentialsId: 'docker', variable: 'DOCKER_CERT_PATH')]) { - sh 'docker-compose pull' - sh 'docker-compose up -d --scale back=2' - } - } - } - stage('Host 2') { - environment { - DOCKER_HOST = "tcp://${env.DOCKER_HOST_2}:2376" - } - steps { - withCredentials([dockerCert(credentialsId: 'docker', variable: 'DOCKER_CERT_PATH')]) { - sh 'docker-compose pull' - sh 'docker-compose up -d --scale back=2' - } - } + steps { + sh "docker stack deploy --compose-file docker-compose.yml ${env.STACK_NAME}" } } } @@ -147,15 +130,6 @@ pipeline { sh 'db/import-changes.sh -f $NODE_ENV' } } - stage('Cleanup') { - when { anyOf { - branch 'test' - branch 'master' - }} - steps { - sh 'docker logout $REGISTRY' - } - } } post { always { diff --git a/docker-compose.yml b/docker-compose.yml index c0f02273e..b04ecd0fb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -10,6 +10,8 @@ services: - ${PORT_FRONT}:80 links: - back + deploy: + replicas: 3 back: image: registry.verdnatura.es/salix-back:${TAG} restart: unless-stopped @@ -22,3 +24,5 @@ services: - /containers/salix:/etc/salix - /mnt/storage/pdfs:/var/lib/salix/pdfs - /mnt/storage/dms:/var/lib/salix/dms + deploy: + replicas: 6 diff --git a/gulpfile.js b/gulpfile.js index 06c65e451..dcb0aa6f1 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -110,17 +110,27 @@ backTestOnce.description = `Runs the backend tests once, can receive --junit arg async function backTestDockerOnce() { let containerId = await docker(); - await backTestOnce(); - if (argv['random']) - await execP(`docker rm -fv ${containerId}`); + try { + await backTestOnce(); + } catch (e) { + throw e; + } finally { + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + } } backTestDockerOnce.description = `Runs backend tests using in site container once`; async function backTestDocker() { let containerId = await docker(); - await backTest(); - if (argv['random']) - await execP(`docker rm -fv ${containerId}`); + try { + await backTest(); + } catch (e) { + throw e; + } finally { + if (argv['random']) + await execP(`docker rm -fv ${containerId}`); + } } backTestDocker.description = `Runs backend tests restoring fixtures first`; From 4f3e3b41faa09ca45ee1b7531b189b9c133427fc Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 14:28:06 +0100 Subject: [PATCH 27/59] Jenkinsfile fixes --- Jenkinsfile | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index b888e57bc..f77387f83 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -67,16 +67,14 @@ pipeline { NODE_ENV = "" } parallel { - steps { - stage('Frontend') { - nodejs('node-lts') { - sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' - } + stage('Frontend') { + nodejs('node-lts') { + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' } - stage('Backend') { - nodejs('node-lts') { - sh 'gulp backTestDockerOnce --junit --random' - } + } + stage('Backend') { + nodejs('node-lts') { + sh 'gulp backTestDockerOnce --junit --random' } } } From 325d0aa08ed8cc78ce2234fbaf11aa2695c69d38 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 14:29:17 +0100 Subject: [PATCH 28/59] Jenkinsfile fixes --- Jenkinsfile | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index f77387f83..718582630 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -68,13 +68,17 @@ pipeline { } parallel { stage('Frontend') { - nodejs('node-lts') { - sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' + steps { + nodejs('node-lts') { + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' + } } } stage('Backend') { - nodejs('node-lts') { - sh 'gulp backTestDockerOnce --junit --random' + steps { + nodejs('node-lts') { + sh 'gulp backTestDockerOnce --junit --random' + } } } } From 109361a7621754ab464bfc6c3addc111a2278f28 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 14:31:02 +0100 Subject: [PATCH 29/59] Jenkinsfile fixes --- Jenkinsfile | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 718582630..a85b276a0 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -110,10 +110,8 @@ pipeline { environment { DOCKER_TLS_VERIFY = 1 } - parallel { - steps { - sh "docker stack deploy --compose-file docker-compose.yml ${env.STACK_NAME}" - } + steps { + sh "docker stack deploy --compose-file docker-compose.yml ${env.STACK_NAME}" } } stage('Database') { From 441f76a1c162b1ef582b2015c65107b6a7857437 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 14:38:39 +0100 Subject: [PATCH 30/59] Jenkinsfile fixes --- Jenkinsfile | 3 --- 1 file changed, 3 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index a85b276a0..c238e452c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -107,9 +107,6 @@ pipeline { branch 'test' branch 'master' }} - environment { - DOCKER_TLS_VERIFY = 1 - } steps { sh "docker stack deploy --compose-file docker-compose.yml ${env.STACK_NAME}" } From 592b67249383f230185baf7925812946cd8c2a04 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 14:53:17 +0100 Subject: [PATCH 31/59] Compose now configuration is read from shared storage --- docker-compose.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-compose.yml b/docker-compose.yml index b04ecd0fb..c9011bdf4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -21,7 +21,7 @@ services: environment: - NODE_ENV volumes: - - /containers/salix:/etc/salix + - /mnt/storage/containers/salix:/etc/salix - /mnt/storage/pdfs:/var/lib/salix/pdfs - /mnt/storage/dms:/var/lib/salix/dms deploy: From a83ba3049aaeaf8a9c50ab7a37a1451e4d979b8f Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 19 Dec 2019 14:55:05 +0100 Subject: [PATCH 32/59] updated selector --- e2e/helpers/selectors.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index daff34db8..f9d69123f 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -358,7 +358,7 @@ export default { goBackToModuleIndexButton: 'vn-ticket-descriptor a[ui-sref="ticket.index"]', moreMenu: 'vn-ticket-descriptor vn-icon-menu[icon=more_vert]', moreMenuAddStowaway: '.vn-drop-down.shown li[name="Add stowaway"]', - moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Remove stowaway"]', + moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Delete stowaway"]', moreMenuAddToTurn: '.vn-drop-down.shown li[name="Add turn"]', moreMenuDeleteTicket: '.vn-drop-down.shown li[name="Delete ticket"]', moreMenuMakeInvoice: '.vn-drop-down.shown li[name="Make invoice"]', From 42239815e0a5f1e58ab1d5f848da534379032e2b Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 19 Dec 2019 15:01:33 +0100 Subject: [PATCH 33/59] removed fdescribe --- modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js index d5a10ac3b..3c8097e37 100644 --- a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -1,6 +1,6 @@ const app = require('vn-loopback/server/server'); -fdescribe('ticket deleteStowaway()', () => { +describe('ticket deleteStowaway()', () => { const shipId = 16; const stowawayId = 17; From 1407b7b76f96185535da409e71cb56caa30ae952 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 15:45:19 +0100 Subject: [PATCH 34/59] Nginx config fixes --- front/nginx.conf | 4 ---- 1 file changed, 4 deletions(-) diff --git a/front/nginx.conf b/front/nginx.conf index 64f9436f3..22bce2283 100644 --- a/front/nginx.conf +++ b/front/nginx.conf @@ -7,11 +7,7 @@ server { client_max_body_size 250M; root /salix/dist; - error_page 404 = @notfound; - location @notfound { - return 302 /; - } location / { autoindex on; } From 5db65e188a3af56e80b6659511b7102c6580d340 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 16:11:56 +0100 Subject: [PATCH 35/59] Jenkinsfile fixes --- Jenkinsfile | 1 - 1 file changed, 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index c238e452c..b26a55f62 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -99,7 +99,6 @@ pipeline { sh 'docker login --username $CREDS_USR --password $CREDS_PSW $REGISTRY' sh 'docker-compose build --parallel' sh 'docker-compose push' - sh 'docker logout $REGISTRY' } } stage('Deploy') { From 00b103b38919ffddeb852afd2dc90944e26f1745 Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 16:16:54 +0100 Subject: [PATCH 36/59] Jenkinsfile fixes --- Jenkinsfile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index b26a55f62..cebd959e1 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -70,7 +70,7 @@ pipeline { stage('Frontend') { steps { nodejs('node-lts') { - sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2' } } } @@ -107,7 +107,7 @@ pipeline { branch 'master' }} steps { - sh "docker stack deploy --compose-file docker-compose.yml ${env.STACK_NAME}" + sh "docker stack deploy --with-registry-auth --compose-file docker-compose.yml ${env.STACK_NAME}" } } stage('Database') { From fce22f2e3009cd21b9051eb1c672dfdbab361ced Mon Sep 17 00:00:00 2001 From: Juan Ferrer Toribio Date: Thu, 19 Dec 2019 16:23:59 +0100 Subject: [PATCH 37/59] Jenkinsfile fixes --- Jenkinsfile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Jenkinsfile b/Jenkinsfile index cebd959e1..0d56f7476 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -70,7 +70,7 @@ pipeline { stage('Frontend') { steps { nodejs('node-lts') { - sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=2' + sh 'jest --ci --reporters=default --reporters=jest-junit --maxWorkers=1' } } } From 3d21539fb009cfa189f1ecb85236f4c69da66da2 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Fri, 20 Dec 2019 07:55:00 +0100 Subject: [PATCH 38/59] travel index filter --- front/core/components/searchbar/searchbar.js | 1 - modules/travel/back/methods/travel/filter.js | 146 ++++++++++++++++++ .../back/methods/travel/specs/filter.spec.js | 58 +++++++ modules/travel/back/models/travel.js | 1 + modules/travel/front/index/index.html | 20 +-- modules/travel/front/index/index.js | 61 +++----- modules/travel/front/index/index.spec.js | 57 +++++-- modules/travel/front/search-panel/index.html | 2 +- 8 files changed, 283 insertions(+), 63 deletions(-) create mode 100644 modules/travel/back/methods/travel/filter.js create mode 100644 modules/travel/back/methods/travel/specs/filter.spec.js diff --git a/front/core/components/searchbar/searchbar.js b/front/core/components/searchbar/searchbar.js index 98f52ee36..a82324877 100644 --- a/front/core/components/searchbar/searchbar.js +++ b/front/core/components/searchbar/searchbar.js @@ -254,7 +254,6 @@ class AutoSearch { } } } - this.model.applyFilter( where ? {where} : null, hasParams ? userParams : null diff --git a/modules/travel/back/methods/travel/filter.js b/modules/travel/back/methods/travel/filter.js new file mode 100644 index 000000000..6cd0caed4 --- /dev/null +++ b/modules/travel/back/methods/travel/filter.js @@ -0,0 +1,146 @@ + +const ParameterizedSQL = require('loopback-connector').ParameterizedSQL; +const buildFilter = require('vn-loopback/util/filter').buildFilter; +const mergeFilters = require('vn-loopback/util/filter').mergeFilters; + +module.exports = Self => { + Self.remoteMethodCtx('filter', { + description: 'Find all instances of the model matched by filter from the data source.', + accessType: 'READ', + accepts: [ + { + arg: 'filter', + type: 'Object', + description: 'Filter defining where, order, offset, and limit - must be a JSON-encoded string', + http: {source: 'query'} + }, { + arg: 'search', + type: 'String', + description: 'Searchs the travel by id', + http: {source: 'query'} + }, { + arg: 'id', + type: 'Integer', + description: 'The travel id', + http: {source: 'query'} + }, { + arg: 'shippedFrom', + type: 'Date', + description: 'The shipped from date filter', + http: {source: 'query'} + }, { + arg: 'shippedTo', + type: 'Date', + description: 'The shipped to date filter', + http: {source: 'query'} + }, { + arg: 'landedFrom', + type: 'Date', + description: 'The landed from date filter', + http: {source: 'query'} + }, { + arg: 'landedTo', + type: 'Date', + description: 'The landed to date filter', + http: {source: 'query'} + }, { + arg: 'agencyFk', + type: 'Number', + description: 'The agencyModeFk id', + http: {source: 'query'} + }, { + arg: 'm3', + type: 'Number', + description: 'The m3 filter', + http: {source: 'query'} + }, { + arg: 'warehouseOutFk', + type: 'Number', + description: 'The warehouseOutFk filter', + http: {source: 'query'} + }, { + arg: 'warehouseInFk', + type: 'Number', + description: 'The warehouseInFk filter', + http: {source: 'query'} + }, { + arg: 'totalEntries', + type: 'Number', + description: 'The totalEntries filter', + http: {source: 'query'} + } + ], + returns: { + type: ['Object'], + root: true + }, + http: { + path: `/filter`, + verb: 'GET' + } + }); + + Self.filter = async(ctx, filter) => { + let conn = Self.dataSource.connector; + let where = buildFilter(ctx.args, (param, value) => { + switch (param) { + case 'search': + return {'t.id': value}; + case 'ref': + return {[param]: {regexp: value}}; + case 'shippedFrom': + return {'t.shipped': {gte: value}}; + case 'shippedTo': + return {'t.shipped': {lte: value}}; + case 'landedFrom': + return {'t.landed': {gte: value}}; + case 'landedTo': + return {'t.landed': {lte: value}}; + case 'id': + case 'agencyFk': + case 'warehouseOutFk': + case 'warehouseInFk': + case 'totalEntries': + param = `t.${param}`; + return {[param]: value}; + } + }); + + filter = mergeFilters(ctx.args.filter, {where}); + + let stmts = []; + let stmt; + stmt = new ParameterizedSQL( + `SELECT + t.id, + t.shipped, + t.landed, + t.warehouseInFk, + t.warehouseOutFk, + t.agencyFk, + t.ref, + t.isDelivered, + t.isReceived, + t.m3, + t.kg, + t.cargoSupplierFk, + t.totalEntries, + am.name agencyModeName, + win.name warehouseInName, + wout.name warehouseOutName + FROM vn.travel t + JOIN vn.agencyMode am ON am.id = t.agencyFk + JOIN vn.warehouse win ON win.id = t.warehouseInFk + JOIN vn.warehouse wout ON wout.id = t.warehouseOutFk` + ); + + + stmt.merge(conn.makeSuffix(filter)); + let itemsIndex = stmts.push(stmt) - 1; + + let sql = ParameterizedSQL.join(stmts, ';'); + let result = await conn.executeStmt(sql); + return itemsIndex === 0 ? result : result[itemsIndex]; + }; +}; + diff --git a/modules/travel/back/methods/travel/specs/filter.spec.js b/modules/travel/back/methods/travel/specs/filter.spec.js new file mode 100644 index 000000000..f2fe44989 --- /dev/null +++ b/modules/travel/back/methods/travel/specs/filter.spec.js @@ -0,0 +1,58 @@ +const app = require('vn-loopback/server/server'); + +describe('Travel filter()', () => { + it('should return the travel matching "search"', async() => { + let ctx = { + args: { + search: 1 + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(1); + expect(result[0].id).toEqual(1); + }); + + it('should return the travel matching "warehouse out"', async() => { + let ctx = { + args: { + warehouseOutFk: 2 + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(7); + }); + + it('should return the travel matching "total entries"', async() => { + let ctx = { + args: { + totalEntries: 1, + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(5); + }); + + it('should return the routes matching "shipped from" and "shipped to"', async() => { + const from = new Date(); + const to = new Date(); + from.setHours(0, 0, 0, 0); + to.setHours(23, 59, 59, 999); + to.setDate(to.getDate() + 1); + let ctx = { + args: { + shippedFrom: from, + shippedTo: to + } + }; + + let result = await app.models.Travel.filter(ctx); + + expect(result.length).toEqual(1); + }); +}); diff --git a/modules/travel/back/models/travel.js b/modules/travel/back/models/travel.js index 936b68cd9..5fa55a366 100644 --- a/modules/travel/back/models/travel.js +++ b/modules/travel/back/models/travel.js @@ -1,4 +1,5 @@ module.exports = Self => { require('../methods/travel/getTravel')(Self); require('../methods/travel/getEntries')(Self); + require('../methods/travel/filter')(Self); }; diff --git a/modules/travel/front/index/index.html b/modules/travel/front/index/index.html index 044f1ca8f..3af99eb6b 100644 --- a/modules/travel/front/index/index.html +++ b/modules/travel/front/index/index.html @@ -1,17 +1,17 @@ + params="::$ctrl.params" + data="travels" + order="shipped DESC, landed DESC"> + on-search="$ctrl.onSearch($params)"> + class="vn-mb-xl vn-w-xl"> @@ -34,11 +34,11 @@ ui-sref="travel.card.summary({id: {{::travel.id}}})"> {{::travel.id}} {{::travel.ref}} - {{::travel.agency.name}} - {{::travel.warehouseOut.name}} + {{::travel.agencyModeName}} + {{::travel.warehouseOutName}} {{::travel.shipped | date:'dd/MM/yyyy'}} - {{::travel.warehouseIn.name}} + {{::travel.warehouseInName}} {{::travel.landed | date:'dd/MM/yyyy'}} @@ -51,8 +51,8 @@ - + diff --git a/modules/travel/front/index/index.js b/modules/travel/front/index/index.js index a4dd60d77..a1e22d2e7 100644 --- a/modules/travel/front/index/index.js +++ b/modules/travel/front/index/index.js @@ -4,44 +4,6 @@ export default class Controller { constructor($scope) { this.$ = $scope; this.ticketSelected = null; - - this.filter = { - include: [ - { - relation: 'agency', - scope: {fields: ['name']} - }, { - relation: 'warehouseIn', - scope: {fields: ['name']} - }, { - relation: 'warehouseOut', - scope: {fields: ['name']} - } - ] - }; - } - - exprBuilder(param, value) { - switch (param) { - case 'search': - return {id: value}; - case 'ref': - return {[param]: {regexp: value}}; - case 'shippedFrom': - return {shipped: {gte: value}}; - case 'shippedTo': - return {shipped: {lte: value}}; - case 'landedFrom': - return {landed: {gte: value}}; - case 'landedTo': - return {landed: {lte: value}}; - case 'id': - case 'agencyModeFk': - case 'warehouseOutFk': - case 'warehouseInFk': - case 'totalEntries': - return {[param]: value}; - } } preview(event, travel) { @@ -50,6 +12,29 @@ export default class Controller { event.preventDefault(); event.stopImmediatePropagation(); } + + getScopeDates(days) { + const today = new Date(); + today.setHours(0, 0, 0, 0); + const daysOnward = new Date(today); + daysOnward.setDate(today.getDate() + days); + daysOnward.setHours(23, 59, 59, 999); + return {shippedFrom: today, shippedTo: daysOnward}; + } + + onSearch(params) { + if (params) { + let newParams = params; + if (params.scopeDays) { + const scopeDates = this.getScopeDates(params.scopeDays); + Object.assign(newParams, scopeDates); + } else if (Object.entries(params).length == 0) + newParams = this.getScopeDates(1); + + this.$.model.applyFilter(null, newParams); + } else + this.$.model.clear(); + } } Controller.$inject = ['$scope']; diff --git a/modules/travel/front/index/index.spec.js b/modules/travel/front/index/index.spec.js index 321109003..5affc7c1a 100644 --- a/modules/travel/front/index/index.spec.js +++ b/modules/travel/front/index/index.spec.js @@ -3,31 +3,62 @@ import './index.js'; describe('Travel Component vnTravelIndex', () => { let $componentController; let controller; + let $window; + let travels = [{ + id: 1, + warehouseInFk: 1, + totalEntries: 3, + isDelivered: false + }, { + id: 2, + warehouseInFk: 1, + total: 4, + isDelivered: true + }, { + id: 3, + warehouseInFk: 1, + total: 2, + isDelivered: true + }]; beforeEach(angular.mock.module('travel', $translateProvider => { $translateProvider.translations('en', {}); })); - beforeEach(angular.mock.inject(_$componentController_ => { + beforeEach(angular.mock.inject((_$componentController_, $rootScope) => { $componentController = _$componentController_; - controller = $componentController('vnTravelIndex'); + let $scope = $rootScope.$new(); + controller = $componentController('vnTravelIndex', $scope); + controller.$.summary = {show: jasmine.createSpy('show')}; })); - describe('exprBuilder()', () => { - it('should return a formated object with the travel id in case of search', () => { - let param = 'search'; - let value = 2; - let result = controller.exprBuilder(param, value); + describe('preview()', () => { + it('should show the dialog summary', () => { + let event = new MouseEvent('click', { + view: $window, + bubbles: true, + cancelable: true + }); + controller.preview(event, travels[0]); - expect(result).toEqual({id: 2}); + expect(controller.$.summary.show).toHaveBeenCalledWith(); }); + }); - it('should return a formated object with the warehouseInFk in case of warehouseInFk', () => { - let param = 'warehouseInFk'; - let value = 3; - let result = controller.exprBuilder(param, value); + describe('getScopeDates()', () => { + it('should return a range of dates', () => { + let days = 2; // never put 1 or anything higher than 2 + let result = controller.getScopeDates(days); - expect(result).toEqual({warehouseInFk: 3}); + let from = new Date(result.shippedFrom).getTime(); + let to = new Date(result.shippedTo).getTime(); + let range = to - from; + + const dayInMilliseconds = 24 * 60 * 60 * 1000; + + let millisecondsPerAddedDay = dayInMilliseconds - 1; + + expect(range - dayInMilliseconds).toEqual(dayInMilliseconds + millisecondsPerAddedDay); }); }); }); diff --git a/modules/travel/front/search-panel/index.html b/modules/travel/front/search-panel/index.html index bd68fd151..afc041f66 100644 --- a/modules/travel/front/search-panel/index.html +++ b/modules/travel/front/search-panel/index.html @@ -30,7 +30,7 @@ From 9a6c8db1402f63c7d2fe86e06e4df9538f2f93c3 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Fri, 20 Dec 2019 08:32:02 +0100 Subject: [PATCH 39/59] focus on the dialog --- modules/worker/front/department/index.html | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/worker/front/department/index.html b/modules/worker/front/department/index.html index d50d33ace..70932d55b 100644 --- a/modules/worker/front/department/index.html +++ b/modules/worker/front/department/index.html @@ -34,7 +34,8 @@ + ng-model="$ctrl.newChild.name" + vn-focus>
From 81bb9cfc88184d2a04b7fd41b0cb353708081817 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Fri, 20 Dec 2019 08:39:34 +0100 Subject: [PATCH 40/59] refactor travel filter --- modules/travel/back/methods/travel/filter.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/modules/travel/back/methods/travel/filter.js b/modules/travel/back/methods/travel/filter.js index 6cd0caed4..ecf152b0c 100644 --- a/modules/travel/back/methods/travel/filter.js +++ b/modules/travel/back/methods/travel/filter.js @@ -48,11 +48,6 @@ module.exports = Self => { type: 'Number', description: 'The agencyModeFk id', http: {source: 'query'} - }, { - arg: 'm3', - type: 'Number', - description: 'The m3 filter', - http: {source: 'query'} }, { arg: 'warehouseOutFk', type: 'Number', From 61408bdfd576573bcd849c495383fff3d5df2ad5 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 20 Dec 2019 09:30:35 +0100 Subject: [PATCH 41/59] updated tests --- modules/claim/front/action/index.js | 8 ++++-- modules/claim/front/action/index.spec.js | 36 ++++++++++++++++++++++-- 2 files changed, 40 insertions(+), 4 deletions(-) diff --git a/modules/claim/front/action/index.js b/modules/claim/front/action/index.js index 873a783d7..23e69bbe9 100644 --- a/modules/claim/front/action/index.js +++ b/modules/claim/front/action/index.js @@ -141,6 +141,8 @@ class Controller { const query = `GreugeTypes/findOne?${serializedParams}`; return this.$http.get(query).then(res => { this.greugeTypeFreightId = res.data.id; + + return res; }); } @@ -148,6 +150,8 @@ class Controller { const query = `GreugeConfigs/findOne`; return this.$http.get(query).then(res => { this.freightPickUpPrice = res.data.freightPickUpPrice; + + return res; }); } @@ -158,7 +162,7 @@ class Controller { promises.push(this.getGreugeTypeId()); promises.push(this.getGreugeConfig()); - Promise.all(promises).then(() => { + return Promise.all(promises).then(() => { const data = { clientFk: this.claim.clientFk, description: this.$translate.instant('ClaimGreugeDescription', { @@ -168,7 +172,7 @@ class Controller { greugeTypeFk: this.greugeTypeFreightId, ticketFk: this.claim.ticketFk }; - this.$http.post(`Greuges/`, data).then(() => { + return this.$http.post(`Greuges/`, data).then(() => { this.vnApp.showSuccess(this.$translate.instant('Data saved!')); this.vnApp.showMessage(this.$translate.instant('Greuge inserted')); }); diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index dfa680bef..b93809750 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -165,7 +165,7 @@ describe('claim', () => { expect(controller.vnApp.showSuccess).not.toHaveBeenCalledWith('Greuge inserted!'); }); - it('should perform a insert into greuges', () => { + it('should make a query and get the greugeTypeId and greuge config', () => { spyOn(controller.card, 'reload'); spyOn(controller.vnApp, 'showSuccess'); @@ -173,12 +173,44 @@ describe('claim', () => { $httpBackend.expect('GET', `GreugeTypes/findOne?${greugeTypeParams}`).respond({id: 7}); $httpBackend.expect('GET', `GreugeConfigs/findOne`).respond({freightPickUpPrice: 11}); controller.onUpdateGreugeResponse('accept'); - $httpBackend.flush(); expect(controller.greugeTypeFreightId).toEqual(7); expect(controller.freightPickUpPrice).toEqual(11); }); + + // #1957 - Investigate how to test nested httpBackend requests + xit('should perform a insert into greuges', () => { + spyOn(controller.card, 'reload'); + spyOn(controller.vnApp, 'showSuccess'); + + spyOn(controller, 'getGreugeTypeId').and.returnValue(new Promise(resolve => { + return resolve({id: 7}); + })); + spyOn(controller, 'getGreugeConfig').and.returnValue(new Promise(resolve => { + return resolve({freightPickUpPrice: 11}); + })); + + controller.claim.clientFk = 101; + controller.claim.id = 11; + let data = { + clientFk: 101, + description: `claim: ${controller.claim.id}`, + amount: 11, + greugeTypeFk: 7, + ticketFk: controller.claim.ticketFk + }; + $httpBackend.expect('POST', `Greuges/`, data).respond(new Promise(resolve => { + return resolve({id: 11}); + })); + controller.onUpdateGreugeResponse('accept').then(res => { + console.log('asdas'); + }).catch(error => { + console.log('errorrrr!!'); + }); + + $httpBackend.flush(); + }); }); }); }); From b9415c0335b5a556450e1c6d10649f288ee76dcd Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 20 Dec 2019 10:40:12 +0100 Subject: [PATCH 42/59] updated sql --- .../10130-christmas/00-greugeConfig.sql | 2 +- db/dump/fixtures.sql | 1 + modules/claim/front/action/index.spec.js | 20 ++++++++++--------- 3 files changed, 13 insertions(+), 10 deletions(-) diff --git a/db/changes/10130-christmas/00-greugeConfig.sql b/db/changes/10130-christmas/00-greugeConfig.sql index f434c7fd7..c21751f08 100644 --- a/db/changes/10130-christmas/00-greugeConfig.sql +++ b/db/changes/10130-christmas/00-greugeConfig.sql @@ -3,4 +3,4 @@ CREATE TABLE `vn`.`greugeConfig` ( `freightPickUpPrice` DECIMAL(10,2) NOT NULL, PRIMARY KEY (`id`)); -INSERT INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); +INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 53bb9ff23..788f10e5b 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -1979,3 +1979,4 @@ INSERT INTO `vn`.`workerTimeControlParams` (`id`, `dayBreak`, `weekBreak`, `week VALUES (1, 43200, 129600, 734400, 43200, 50400); +INSERT IGNORE INTO `vn`.`greugeConfig` (`id`, `freightPickUpPrice`) VALUES ('1', '11'); diff --git a/modules/claim/front/action/index.spec.js b/modules/claim/front/action/index.spec.js index b93809750..0d10957e7 100644 --- a/modules/claim/front/action/index.spec.js +++ b/modules/claim/front/action/index.spec.js @@ -153,6 +153,8 @@ describe('claim', () => { }); describe('onUpdateGreugeResponse()', () => { + const greugeTypeId = 7; + const freightPickUpPrice = 11; it('should do nothing', () => { spyOn(controller.$http, 'post'); spyOn(controller.card, 'reload'); @@ -170,13 +172,13 @@ describe('claim', () => { spyOn(controller.vnApp, 'showSuccess'); const greugeTypeParams = $httpParamSerializer({filter: {where: {code: 'freightPickUp'}}}); - $httpBackend.expect('GET', `GreugeTypes/findOne?${greugeTypeParams}`).respond({id: 7}); - $httpBackend.expect('GET', `GreugeConfigs/findOne`).respond({freightPickUpPrice: 11}); + $httpBackend.expect('GET', `GreugeTypes/findOne?${greugeTypeParams}`).respond({id: greugeTypeId}); + $httpBackend.expect('GET', `GreugeConfigs/findOne`).respond({freightPickUpPrice}); controller.onUpdateGreugeResponse('accept'); $httpBackend.flush(); - expect(controller.greugeTypeFreightId).toEqual(7); - expect(controller.freightPickUpPrice).toEqual(11); + expect(controller.greugeTypeFreightId).toEqual(greugeTypeId); + expect(controller.freightPickUpPrice).toEqual(freightPickUpPrice); }); // #1957 - Investigate how to test nested httpBackend requests @@ -185,10 +187,10 @@ describe('claim', () => { spyOn(controller.vnApp, 'showSuccess'); spyOn(controller, 'getGreugeTypeId').and.returnValue(new Promise(resolve => { - return resolve({id: 7}); + return resolve({id: greugeTypeId}); })); spyOn(controller, 'getGreugeConfig').and.returnValue(new Promise(resolve => { - return resolve({freightPickUpPrice: 11}); + return resolve({freightPickUpPrice}); })); controller.claim.clientFk = 101; @@ -196,12 +198,12 @@ describe('claim', () => { let data = { clientFk: 101, description: `claim: ${controller.claim.id}`, - amount: 11, - greugeTypeFk: 7, + amount: freightPickUpPrice, + greugeTypeFk: greugeTypeId, ticketFk: controller.claim.ticketFk }; $httpBackend.expect('POST', `Greuges/`, data).respond(new Promise(resolve => { - return resolve({id: 11}); + return resolve({id: freightPickUpPrice}); })); controller.onUpdateGreugeResponse('accept').then(res => { console.log('asdas'); From 72d591e14312293434f1d30225b2b0d663418c33 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 20 Dec 2019 10:59:17 +0100 Subject: [PATCH 43/59] sql changes --- db/changes/10130-christmas/00-greugeType.sql | 1 - db/dump/fixtures.sql | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) delete mode 100644 db/changes/10130-christmas/00-greugeType.sql diff --git a/db/changes/10130-christmas/00-greugeType.sql b/db/changes/10130-christmas/00-greugeType.sql deleted file mode 100644 index 3438ff923..000000000 --- a/db/changes/10130-christmas/00-greugeType.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `vn`.`greugeType` (`id`, `name`, `code`) VALUES ('7', 'Freight Pickup ', 'freightPickUp'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 788f10e5b..c6d7592f9 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -586,7 +586,8 @@ INSERT INTO `vn`.`greugeType`(`id`, `name`, `code`) (3, 'Mana', 'mana'), (4, 'Reclaim', 'reclaim'), (5, 'Heritage', 'heritage'), - (6, 'Miscellaneous', 'miscellaneous'); + (6, 'Miscellaneous', 'miscellaneous'), + (7, 'Freight Pickup', 'freightPickUp'); INSERT INTO `vn`.`greuge`(`id`, `clientFk`, `description`, `amount`, `shipped`, `created`, `greugeTypeFk`, `ticketFk`) VALUES From ec1750476ee1386661d3d038557079ee974e674b Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 20 Dec 2019 12:56:56 +0100 Subject: [PATCH 44/59] Fixed tags --- .../reports/delivery-note/delivery-note.html | 18 ++++++++++++------ .../templates/reports/sepa-core/locale/fr.yml | 2 +- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/print/templates/reports/delivery-note/delivery-note.html b/print/templates/reports/delivery-note/delivery-note.html index 812ef0715..1bad225de 100644 --- a/print/templates/reports/delivery-note/delivery-note.html +++ b/print/templates/reports/delivery-note/delivery-note.html @@ -96,16 +96,22 @@ - {{sale.tag1}} - {{sale.val1}} +
+ {{sale.tag5}} + {{sale.value5}} +
- {{sale.tag2}} - {{sale.val2}} +
+ {{sale.tag6}} + {{sale.value6}} +
- {{sale.tag3}} - {{sale.val3}} +
+ {{sale.tag7}} + {{sale.value7}} +
diff --git a/print/templates/reports/sepa-core/locale/fr.yml b/print/templates/reports/sepa-core/locale/fr.yml index ec6fd11ab..9489fa277 100644 --- a/print/templates/reports/sepa-core/locale/fr.yml +++ b/print/templates/reports/sepa-core/locale/fr.yml @@ -1,4 +1,4 @@ -title: Mandat de domiciliation Européene LCR +title: Mandat de domiciliation Européene description: En signant ce formulaire de mandat, vous autorisez VERDNATURA LEVANTE SL à envoyer des instructions à votre banque pour débiter votre compte, et (B) votre banque à débiter votre compte conformément aux instructions de VERDNATURA LEVANTE SL. From e9d416671de2a5c25f4dbf6a70dd9a937dce26ce Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Fri, 20 Dec 2019 13:51:04 +0100 Subject: [PATCH 45/59] update fixtures and structure db --- .../10080-september/00-catalog_calculate.sql | 117 - db/changes/10081-agency/00-address_getGeo.sql | 27 - db/changes/10081-agency/00-zone.sql | 56 - .../10081-agency/00-zone_getAvailable.sql | 16 - db/changes/10081-agency/00-zone_getEvents.sql | 52 - .../10081-agency/00-zone_getFromGeo.sql | 58 - db/changes/10081-agency/00-zone_getLeaves.sql | 88 - db/changes/10081-agency/01-zone_getAgency.sql | 42 - .../10081-agency/01-zone_getFirstShipped.sql | 2 - db/changes/10081-agency/01-zone_getLanded.sql | 40 - .../01-zone_getShippedWarehouse.sql | 41 - .../10081-agency/01-zone_getWarehouse.sql | 42 - db/changes/10081-agency/02-zoneGetAgency.sql | 22 - .../10081-agency/02-zoneGetFirstShipped__.sql | 3 - db/changes/10081-agency/02-zoneGetLanded.sql | 20 - db/changes/10081-agency/02-zoneGetShipped.sql | 24 - .../02-zoneGetShippedWarehouse.sql | 20 - .../04-zone_getOptionsForLanding.sql | 67 - .../04-zone_getOptionsForShipment.sql | 76 - db/changes/10090-iberflora/00-ACL.sql | 1 - db/changes/10090-iberflora/00-claimState.sql | 2 - db/changes/10090-iberflora/00-component.sql | 15 - db/changes/10091-iberflora/00-department.sql | 2 - .../00-department_calcTree.sql | 37 - .../00-department_calcTreeRec.sql | 75 - .../10091-iberflora/00-department_doCalc.sql | 35 - .../00-department_getLeaves.sql | 84 - db/changes/10091-iberflora/00-route.sql | 10 - db/changes/10100-allSaints/00-ACL.sql | 1 - db/changes/10100-allSaints/00-travelLog.sql | 18 - db/changes/10100-allSaints/00-upperGap.sql | 6 - db/changes/10100-allSaints/00-userLog.sql | 18 - .../10100-allSaints/00-userPhoneType.sql | 9 - db/changes/10100-allSaints/01-userPhone.sql | 23 - .../02-catalog_componentCalculate.sql | 259 - .../10100-allSaints/02-ticketCalculate__.sql | 17 - .../10100-allSaints/03-available_calc.sql | 63 - .../10100-allSaints/03-catalog_calculate.sql | 119 - .../03-order_confirmWithUser.sql | 244 - .../03-ticketCalculateClon.sql | 88 - .../03-ticketComponentCalculate.sql | 262 - .../03-ticketCreateWithUser.sql | 88 - .../03-ticketCreateWithoutZone.sql | 90 - .../05-catalog_calcFromItem.sql | 31 - .../10110-postCampaign/00-chatConfig.sql | 11 - .../00-clientBeforeUpdate.sql | 51 - .../10110-postCampaign/00-clientGetMana.sql | 75 - .../00-clientPackagingOverstock.sql | 97 - .../00-clonTravelComplete.sql | 132 - db/changes/10110-postCampaign/00-country.sql | 10 - .../00-creditClassificationBeforeUpdate.sql | 16 - .../00-creditInsuranceAfterInsert.sql | 13 - .../00-department_doCalc.sql | 3 - .../00-duaInvoicingBooking.sql | 74 - .../00-getItemVisibleAvailable.sql | 17 - .../00-itemGetVisibleAvailable.sql | 17 - .../00-item_getVisibleAvailable.sql | 71 - .../10110-postCampaign/00-payMethod.sql | 7 - .../10110-postCampaign/00-rangeDateInfo.sql | 41 - db/changes/10110-postCampaign/00-sample.sql | 8 - .../10110-postCampaign/00-ticketClosure.sql | 116 - .../10110-postCampaign/00-ticketRequest.sql | 54 - .../00-ticket_recalcComponents.sql | 77 - .../00-ticket_recalcComponentsForcePrice.sql | 77 - .../00-workerTimeControlAdd.sql | 73 - .../00-workerTimeControlCalculate.sql | 41 - db/changes/10110-postCampaign/01-Ordenes.sql | 53 - .../01-bionicCalcReverse.sql | 92 - .../01-ticketBusinessCalculate.sql | 96 - .../10120-december/00-entryBeforeUpdate.sql | 58 - .../00-expedition_beforeInsert.sql | 33 - .../10120-december/00-stowaway_unboarding.sql | 31 - .../10120-december/00-tpvTransaction.sql | 120 - .../10120-december/00-tpvTransaction_undo.sql | 86 - db/dump/dumpedFixtures.sql | 26 +- db/dump/fixtures.sql | 17 + db/dump/structure.sql | 5921 ++++++++++------- .../back/methods/client/updateFiscalData.js | 1 + 78 files changed, 3617 insertions(+), 6408 deletions(-) delete mode 100644 db/changes/10080-september/00-catalog_calculate.sql delete mode 100644 db/changes/10081-agency/00-address_getGeo.sql delete mode 100644 db/changes/10081-agency/00-zone.sql delete mode 100644 db/changes/10081-agency/00-zone_getAvailable.sql delete mode 100644 db/changes/10081-agency/00-zone_getEvents.sql delete mode 100644 db/changes/10081-agency/00-zone_getFromGeo.sql delete mode 100755 db/changes/10081-agency/00-zone_getLeaves.sql delete mode 100644 db/changes/10081-agency/01-zone_getAgency.sql delete mode 100644 db/changes/10081-agency/01-zone_getFirstShipped.sql delete mode 100644 db/changes/10081-agency/01-zone_getLanded.sql delete mode 100644 db/changes/10081-agency/01-zone_getShippedWarehouse.sql delete mode 100644 db/changes/10081-agency/01-zone_getWarehouse.sql delete mode 100644 db/changes/10081-agency/02-zoneGetAgency.sql delete mode 100644 db/changes/10081-agency/02-zoneGetFirstShipped__.sql delete mode 100644 db/changes/10081-agency/02-zoneGetLanded.sql delete mode 100644 db/changes/10081-agency/02-zoneGetShipped.sql delete mode 100644 db/changes/10081-agency/02-zoneGetShippedWarehouse.sql delete mode 100644 db/changes/10081-agency/04-zone_getOptionsForLanding.sql delete mode 100644 db/changes/10081-agency/04-zone_getOptionsForShipment.sql delete mode 100644 db/changes/10090-iberflora/00-ACL.sql delete mode 100644 db/changes/10090-iberflora/00-claimState.sql delete mode 100644 db/changes/10090-iberflora/00-component.sql delete mode 100644 db/changes/10091-iberflora/00-department.sql delete mode 100644 db/changes/10091-iberflora/00-department_calcTree.sql delete mode 100644 db/changes/10091-iberflora/00-department_calcTreeRec.sql delete mode 100644 db/changes/10091-iberflora/00-department_doCalc.sql delete mode 100644 db/changes/10091-iberflora/00-department_getLeaves.sql delete mode 100644 db/changes/10091-iberflora/00-route.sql delete mode 100644 db/changes/10100-allSaints/00-ACL.sql delete mode 100644 db/changes/10100-allSaints/00-travelLog.sql delete mode 100644 db/changes/10100-allSaints/00-upperGap.sql delete mode 100644 db/changes/10100-allSaints/00-userLog.sql delete mode 100644 db/changes/10100-allSaints/00-userPhoneType.sql delete mode 100644 db/changes/10100-allSaints/01-userPhone.sql delete mode 100644 db/changes/10100-allSaints/02-catalog_componentCalculate.sql delete mode 100644 db/changes/10100-allSaints/02-ticketCalculate__.sql delete mode 100644 db/changes/10100-allSaints/03-available_calc.sql delete mode 100644 db/changes/10100-allSaints/03-catalog_calculate.sql delete mode 100644 db/changes/10100-allSaints/03-order_confirmWithUser.sql delete mode 100644 db/changes/10100-allSaints/03-ticketCalculateClon.sql delete mode 100644 db/changes/10100-allSaints/03-ticketComponentCalculate.sql delete mode 100644 db/changes/10100-allSaints/03-ticketCreateWithUser.sql delete mode 100644 db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql delete mode 100644 db/changes/10100-allSaints/05-catalog_calcFromItem.sql delete mode 100644 db/changes/10110-postCampaign/00-chatConfig.sql delete mode 100644 db/changes/10110-postCampaign/00-clientBeforeUpdate.sql delete mode 100644 db/changes/10110-postCampaign/00-clientGetMana.sql delete mode 100644 db/changes/10110-postCampaign/00-clientPackagingOverstock.sql delete mode 100644 db/changes/10110-postCampaign/00-clonTravelComplete.sql delete mode 100644 db/changes/10110-postCampaign/00-country.sql delete mode 100644 db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql delete mode 100644 db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql delete mode 100644 db/changes/10110-postCampaign/00-department_doCalc.sql delete mode 100644 db/changes/10110-postCampaign/00-duaInvoicingBooking.sql delete mode 100644 db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql delete mode 100644 db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql delete mode 100644 db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql delete mode 100644 db/changes/10110-postCampaign/00-payMethod.sql delete mode 100644 db/changes/10110-postCampaign/00-rangeDateInfo.sql delete mode 100644 db/changes/10110-postCampaign/00-sample.sql delete mode 100644 db/changes/10110-postCampaign/00-ticketClosure.sql delete mode 100644 db/changes/10110-postCampaign/00-ticketRequest.sql delete mode 100644 db/changes/10110-postCampaign/00-ticket_recalcComponents.sql delete mode 100644 db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql delete mode 100644 db/changes/10110-postCampaign/00-workerTimeControlAdd.sql delete mode 100644 db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql delete mode 100644 db/changes/10110-postCampaign/01-Ordenes.sql delete mode 100644 db/changes/10110-postCampaign/01-bionicCalcReverse.sql delete mode 100644 db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql delete mode 100644 db/changes/10120-december/00-entryBeforeUpdate.sql delete mode 100644 db/changes/10120-december/00-expedition_beforeInsert.sql delete mode 100644 db/changes/10120-december/00-stowaway_unboarding.sql delete mode 100644 db/changes/10120-december/00-tpvTransaction.sql delete mode 100644 db/changes/10120-december/00-tpvTransaction_undo.sql diff --git a/db/changes/10080-september/00-catalog_calculate.sql b/db/changes/10080-september/00-catalog_calculate.sql deleted file mode 100644 index 4ddb79274..000000000 --- a/db/changes/10080-september/00-catalog_calculate.sql +++ /dev/null @@ -1,117 +0,0 @@ -DROP procedure IF EXISTS `vn`.`catalog_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_calculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/00-address_getGeo.sql b/db/changes/10081-agency/00-address_getGeo.sql deleted file mode 100644 index fca55dfd2..000000000 --- a/db/changes/10081-agency/00-address_getGeo.sql +++ /dev/null @@ -1,27 +0,0 @@ - -DROP FUNCTION IF EXISTS `vn`.`address_getGeo`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`address_getGeo` (vSelf INT) - RETURNS INT - DETERMINISTIC -BEGIN -/** - * Returns the geo for the passed address. - * - * @param vSelf The address id - * @return The geo id - */ - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode - WHERE a.id = vSelf - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - RETURN vGeoFk; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone.sql b/db/changes/10081-agency/00-zone.sql deleted file mode 100644 index 74e482c4c..000000000 --- a/db/changes/10081-agency/00-zone.sql +++ /dev/null @@ -1,56 +0,0 @@ -USE `vn`; - -CREATE TABLE `vn`.`zoneWarehouse` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), - KEY `warehouseFk` (`warehouseFk`), - CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE/*, -CONSTRAINT `zoneWarehouse_ibfk_2` FOREIGN KEY (`warehouseFk`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE*/ -) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8; - -CREATE TABLE `vn`.`zoneEvent` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `from` date DEFAULT NULL, - `to` date DEFAULT NULL, - `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, - `hour` datetime DEFAULT NULL, - `travelingDays` int(11) DEFAULT NULL, - `price` decimal(10,2) DEFAULT NULL, - `bonus` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `zoneFk` (`zoneFk`), - CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8; - -ALTER TABLE `vn`.`zoneEvent` - ADD COLUMN `type` ENUM('day', 'indefinitely', 'range') NOT NULL AFTER `zoneFk`, - ADD COLUMN `dated` DATE NULL DEFAULT NULL AFTER `type`, - CHANGE COLUMN `from` `started` DATE NULL DEFAULT NULL , - CHANGE COLUMN `to` `ended` DATE NULL DEFAULT NULL ; - -CREATE TABLE `vn`.`zoneExclusion` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `zoneFk` int(11) NOT NULL, - `day` date NOT NULL, - PRIMARY KEY (`id`), - UNIQUE KEY `zoneFk_2` (`zoneFk`,`day`), - KEY `zoneFk` (`zoneFk`), - CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; -ALTER TABLE `vn`.`zone` -DROP FOREIGN KEY `fk_zone_1`; -ALTER TABLE `vn`.`zone` -CHANGE COLUMN `warehouseFk` `warehouseFk` SMALLINT(6) UNSIGNED NULL DEFAULT NULL ; -ALTER TABLE `vn`.`zone` -ADD CONSTRAINT `fk_zone_1` - FOREIGN KEY (`warehouseFk`) - REFERENCES `vn`.`warehouse` (`id`) - ON DELETE NO ACTION - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`zoneExclusion` - CHANGE COLUMN `day` `dated` DATE NOT NULL ; diff --git a/db/changes/10081-agency/00-zone_getAvailable.sql b/db/changes/10081-agency/00-zone_getAvailable.sql deleted file mode 100644 index d24816e6e..000000000 --- a/db/changes/10081-agency/00-zone_getAvailable.sql +++ /dev/null @@ -1,16 +0,0 @@ - -DROP PROCEDURE IF EXISTS `vn`.`zone_getAvailable`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getAvailable`(vAddress INT, vLanded DATE) -BEGIN - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - SELECT * FROM tmp.zoneOption; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getEvents.sql b/db/changes/10081-agency/00-zone_getEvents.sql deleted file mode 100644 index be50f602d..000000000 --- a/db/changes/10081-agency/00-zone_getEvents.sql +++ /dev/null @@ -1,52 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getEvents`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( - vProvinceFk INT, - vPostCode VARCHAR(255), - vAgencyModeFk INT) -BEGIN -/** - * Returns available events for the passed province/postcode and agency. - * - * @param vAgencyModeFk The agency mode id - * @param vProvinceFk The province id - * @param vPostCode The postcode or %NULL to use the province - */ - DECLARE vGeoFk INT; - - IF vPostCode IS NOT NULL THEN - SELECT p.geoFk INTO vGeoFk - FROM postCode p - JOIN town t ON t.id = p.townFk - WHERE p.`code` = vPostCode - AND t.provinceFk = vProvinceFk; - ELSE - SELECT geoFk INTO vGeoFk - FROM province - WHERE id = vProvinceFk; - END IF; - - CALL zone_getFromGeo(vGeoFk); - - IF vAgencyModeFk IS NOT NULL THEN - DELETE t FROM tmp.zone t - JOIN zone z ON z.id = t.id - WHERE z.agencyModeFk != vAgencyModeFk; - END IF; - - SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays - FROM tmp.zone t - JOIN zoneEvent e ON e.zoneFk = t.id; - - SELECT e.zoneFk, e.dated - FROM tmp.zone t - JOIN zoneExclusion e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE tmp.zone; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getFromGeo.sql b/db/changes/10081-agency/00-zone_getFromGeo.sql deleted file mode 100644 index 244c73556..000000000 --- a/db/changes/10081-agency/00-zone_getFromGeo.sql +++ /dev/null @@ -1,58 +0,0 @@ - -DROP PROCEDURE IF EXISTS `vn`.`zone_getFromGeo`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getFromGeo`(vGeoFk INT) -BEGIN -/** - * Returns all zones which have the passed geo included. - * - * @param vGeoFk The geo id - * @return tmp.zone(id) The list of zones - */ - DECLARE vChildFk INT DEFAULT vGeoFk; - DECLARE vParentFk INT; - DECLARE vLevel INT DEFAULT 1; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (PRIMARY KEY (id)) - ENGINE = MEMORY - SELECT vGeoFk id, vLevel `level`; - - myLoop: LOOP - SELECT parentFk INTO vParentFk - FROM zoneGeo - WHERE id = vChildFk; - - SET vChildFk = vParentFk; - SET vLevel = vLevel + 1; - - INSERT IGNORE INTO tNodes - SELECT vChildFk, vLevel - FROM DUAL - WHERE vChildFk IS NOT NULL; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - END LOOP; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE tmp.zone - (INDEX (id)) - ENGINE = MEMORY - SELECT id FROM ( - SELECT zoneFk id, isIncluded - FROM ( - SELECT i.zoneFk, i.isIncluded - FROM tNodes n - JOIN zoneIncluded i ON i.geoFk = n.id - ORDER BY zoneFk, n.`level` - ) t - GROUP BY id HAVING isIncluded - ) t; - - DROP TEMPORARY TABLE tNodes; -END$$ -DELIMITER ; - diff --git a/db/changes/10081-agency/00-zone_getLeaves.sql b/db/changes/10081-agency/00-zone_getLeaves.sql deleted file mode 100755 index ee95b3315..000000000 --- a/db/changes/10081-agency/00-zone_getLeaves.sql +++ /dev/null @@ -1,88 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`zone_getLeaves`; -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`zone_getLeaves`( - vSelf INT, - vParentFk INT, - vSearch VARCHAR(255) -) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id FROM zoneGeo - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - ELSEIF vParentFk IS NULL THEN - INSERT INTO tNodes - SELECT geoFk FROM zoneIncluded - WHERE zoneFk = vSelf; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - ENGINE = MEMORY - SELECT id FROM zoneGeo LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM zoneGeo g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE - tChilds, - tParents; - END IF; - - IF !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM zoneGeo - WHERE parentFk <=> vParentFk; - END IF; - - SELECT g.id, - g.`name`, - g.parentFk, - g.sons, - isIncluded selected - FROM zoneGeo g - JOIN tNodes n ON n.id = g.id - LEFT JOIN zoneIncluded i - ON i.geoFk = g.id AND i.zoneFk = vSelf - ORDER BY depth, selected DESC, `name`; - - DROP TEMPORARY TABLE tNodes; -END$$ -DELIMITER ; diff --git a/db/changes/10081-agency/01-zone_getAgency.sql b/db/changes/10081-agency/01-zone_getAgency.sql deleted file mode 100644 index 3d0c86866..000000000 --- a/db/changes/10081-agency/01-zone_getAgency.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT am.name agencyMode, - am.description, - z.agencyModeFk, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - TRUE isIncluded, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - GROUP BY agencyModeFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getFirstShipped.sql b/db/changes/10081-agency/01-zone_getFirstShipped.sql deleted file mode 100644 index 64e853a81..000000000 --- a/db/changes/10081-agency/01-zone_getFirstShipped.sql +++ /dev/null @@ -1,2 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getFirstShipped`; diff --git a/db/changes/10081-agency/01-zone_getLanded.sql b/db/changes/10081-agency/01-zone_getLanded.sql deleted file mode 100644 index a2bbe46a5..000000000 --- a/db/changes/10081-agency/01-zone_getLanded.sql +++ /dev/null @@ -1,40 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getLanded`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia -* @param vWarehouseFk vWarehouseFk -* @table tmp.zoneGetLanded Datos de recepción -*/ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT vWarehouseFk warehouseFk, - TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, - zo.zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN zoneWarehouse zw ON zw.zoneFk = z.id - WHERE agencyModeFk = vAgencyModeFk - AND zw.warehouseFk = vWarehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql b/db/changes/10081-agency/01-zone_getShippedWarehouse.sql deleted file mode 100644 index 017b7d17c..000000000 --- a/db/changes/10081-agency/01-zone_getShippedWarehouse.sql +++ /dev/null @@ -1,41 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - - CALL zone_getFromGeo(address_getGeo(vAddressFk)); - CALL zone_getOptionsForLanding(vLanded); - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT zo.zoneFk, - TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.agencyModeFk - FROM tmp.zoneOption zo - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - JOIN zone z ON z.id = zo.zoneFk - WHERE z.agencyModeFk = vAgencyModeFk - ORDER BY shipped) t - GROUP BY warehouseFk; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/01-zone_getWarehouse.sql b/db/changes/10081-agency/01-zone_getWarehouse.sql deleted file mode 100644 index 28478e2cc..000000000 --- a/db/changes/10081-agency/01-zone_getWarehouse.sql +++ /dev/null @@ -1,42 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha, - * dirección y almacén pasados. - * - * @param vAddress - * @param vWarehouse warehouse - * @param vLanded Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getFromGeo(address_getGeo(vAddress)); - CALL zone_getOptionsForLanding(vLanded); - - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, - zw.warehouseFk, - z.id zoneFk - FROM tmp.zoneOption zo - JOIN zone z ON z.id = zo.zoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk - WHERE zw.warehouseFk - GROUP BY z.agencyModeFk - ORDER BY agencyMode; - - DROP TEMPORARY TABLE - tmp.zone, - tmp.zoneOption; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetAgency.sql b/db/changes/10081-agency/02-zoneGetAgency.sql deleted file mode 100644 index 3a627ba5b..000000000 --- a/db/changes/10081-agency/02-zoneGetAgency.sql +++ /dev/null @@ -1,22 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`zoneGetAgency`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetAgency`(vAddress INT, vLanded DATE) -BEGIN -/** - * Devuelve el listado de agencias disponibles para la fecha - * y dirección pasadas. - * - * @param vAddress Id de dirección de envío, %NULL si es recogida - * @param vDate Fecha de recogida - * @select Listado de agencias disponibles - */ - - CALL zone_getAgency(vAddress,vLanded); -END$$ - -DELIMITER ; -; diff --git a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql b/db/changes/10081-agency/02-zoneGetFirstShipped__.sql deleted file mode 100644 index 9483f309c..000000000 --- a/db/changes/10081-agency/02-zoneGetFirstShipped__.sql +++ /dev/null @@ -1,3 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`zoneGetFirstShipped`; diff --git a/db/changes/10081-agency/02-zoneGetLanded.sql b/db/changes/10081-agency/02-zoneGetLanded.sql deleted file mode 100644 index da8d8a9dd..000000000 --- a/db/changes/10081-agency/02-zoneGetLanded.sql +++ /dev/null @@ -1,20 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetLanded`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) -BEGIN -/** -* Devuelve una tabla temporal con el dia de recepcion para vShipped. -* -* @param vShipped Fecha de preparacion de mercancia -* @param vAddress Id de consignatario, %NULL para recogida -* @param vAgencyMode Id agencia -* @table tmp.zoneGetLanded Datos de recepción -*/ - CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetShipped.sql b/db/changes/10081-agency/02-zoneGetShipped.sql deleted file mode 100644 index 212eb94df..000000000 --- a/db/changes/10081-agency/02-zoneGetShipped.sql +++ /dev/null @@ -1,24 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetShipped`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) -BEGIN -/** - * OBSOLETO usar zone_getShippedWarehouse - * Devuelve la mínima fecha de envía para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql b/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql deleted file mode 100644 index 55f443054..000000000 --- a/db/changes/10081-agency/02-zoneGetShippedWarehouse.sql +++ /dev/null @@ -1,20 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zoneGetShippedWarehouse`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) -BEGIN -/** - * Devuelve la mínima fecha de envío para cada warehouse - * - * @param vLanded La fecha de recepcion - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.zoneGetShipped - */ - CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql b/db/changes/10081-agency/04-zone_getOptionsForLanding.sql deleted file mode 100644 index ae081f14b..000000000 --- a/db/changes/10081-agency/04-zone_getOptionsForLanding.sql +++ /dev/null @@ -1,67 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForLanding`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) -BEGIN -/** - * Gets computed options for the passed zones and delivery date. - * - * @table tmp.zones(id) The zones ids - * @param vLanded The delivery date - * @return tmp.zoneOption The computed options - */ - DECLARE vHour TIME DEFAULT TIME(NOW()); - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.travelingDays, z.travelingDays) travelingDays, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - WHERE ( - e.`type` = 'day' - AND e.dated = vLanded - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(vLanded)) - AND (e.`started` IS NULL OR vLanded >= e.`started`) - AND (e.`ended` IS NULL OR vLanded <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; - - DELETE FROM tTemp - WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() - OR @shipped = CURDATE() AND vHour > `hour`; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE tTemp; -END$$ - -DELIMITER ; - diff --git a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql b/db/changes/10081-agency/04-zone_getOptionsForShipment.sql deleted file mode 100644 index c631f8809..000000000 --- a/db/changes/10081-agency/04-zone_getOptionsForShipment.sql +++ /dev/null @@ -1,76 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `zone_getOptionsForShipment`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) -BEGIN -/** - * Gets computed options for the passed zones and shipping date. - * - * @table tmp.zones(id) The zones ids - * @param vShipped The shipping date - * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options - */ - DROP TEMPORARY TABLE IF EXISTS tLandings; - CREATE TEMPORARY TABLE tLandings - (INDEX (eventFk)) - ENGINE = MEMORY - SELECT e.id eventFk, - @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, - TIMESTAMPADD(DAY, @travelingDays, vShipped) landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id; - - DROP TEMPORARY TABLE IF EXISTS tTemp; - CREATE TEMPORARY TABLE tTemp - ENGINE = MEMORY - SELECT t.id zoneFk, - IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, - IFNULL(e.price, z.price) price, - IFNULL(e.bonus, z.bonus) bonus, - CASE - WHEN e.`type` = 'day' - THEN 1 - WHEN e.`type` = 'range' - THEN 2 - ELSE 3 - END specificity, - l.travelingDays, - l.landed - FROM tmp.zone t - JOIN zone z ON z.id = t.id - JOIN zoneEvent e ON e.zoneFk = t.id - JOIN tLandings l ON l.eventFk = e.id - WHERE ( - e.`type` = 'day' - AND e.`dated` = l.landed - ) OR ( - e.`type` != 'day' - AND e.weekDays & (1 << WEEKDAY(l.landed)) - AND (e.`started` IS NULL OR l.landed >= e.`started`) - AND (e.`ended` IS NULL OR l.landed <= e.`ended`) - ); - - DELETE t FROM tTemp t - JOIN zoneExclusion e - ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; - CREATE TEMPORARY TABLE tmp.zoneOption - ENGINE = MEMORY - SELECT * - FROM ( - SELECT * FROM tTemp - ORDER BY zoneFk, specificity - ) t - GROUP BY zoneFk; - - DROP TEMPORARY TABLE - tTemp, - tLandings; -END$$ - -DELIMITER ; - diff --git a/db/changes/10090-iberflora/00-ACL.sql b/db/changes/10090-iberflora/00-ACL.sql deleted file mode 100644 index 3a20e3ecb..000000000 --- a/db/changes/10090-iberflora/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Claim', 'updateClaimAction', 'WRITE', 'ALLOW', 'ROLE', 'salesAssistant'); diff --git a/db/changes/10090-iberflora/00-claimState.sql b/db/changes/10090-iberflora/00-claimState.sql deleted file mode 100644 index 7a964979b..000000000 --- a/db/changes/10090-iberflora/00-claimState.sql +++ /dev/null @@ -1,2 +0,0 @@ -UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '3'); -UPDATE `vn`.`claimState` SET `roleFk` = '21' WHERE (`id` = '5'); diff --git a/db/changes/10090-iberflora/00-component.sql b/db/changes/10090-iberflora/00-component.sql deleted file mode 100644 index fe5de47fc..000000000 --- a/db/changes/10090-iberflora/00-component.sql +++ /dev/null @@ -1,15 +0,0 @@ -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`component` AS - SELECT - `t`.`Id_Componente` AS `id`, - `t`.`Componente` AS `name`, - `t`.`tarifa_componentes_series_id` AS `typeFk`, - `t`.`tarifa_class` AS `classRate`, - `t`.`tax` AS `tax`, - `t`.`is_renewable` AS `isRenewable`, - `t`.`code` AS `code` - FROM - `bi`.`tarifa_componentes` `t`; diff --git a/db/changes/10091-iberflora/00-department.sql b/db/changes/10091-iberflora/00-department.sql deleted file mode 100644 index 415879485..000000000 --- a/db/changes/10091-iberflora/00-department.sql +++ /dev/null @@ -1,2 +0,0 @@ - -UPDATE vn.department SET lft = NULL, rgt = NULL; diff --git a/db/changes/10091-iberflora/00-department_calcTree.sql b/db/changes/10091-iberflora/00-department_calcTree.sql deleted file mode 100644 index 5f518d2e2..000000000 --- a/db/changes/10091-iberflora/00-department_calcTree.sql +++ /dev/null @@ -1,37 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_calcTree`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTree`() -BEGIN -/** - * Calculates the #path, #lft, #rgt, #sons and #depth columns of - * the #department table. To build the tree, it uses the #parentFk - * column. - */ - DECLARE vIndex INT DEFAULT 0; - DECLARE vSons INT; - - DROP TEMPORARY TABLE IF EXISTS tNestedTree; - CREATE TEMPORARY TABLE tNestedTree - SELECT id, path, lft, rgt, depth, sons - FROM department LIMIT 0; - - SET max_sp_recursion_depth = 5; - CALL department_calcTreeRec(NULL, '/', 0, vIndex, vSons); - SET max_sp_recursion_depth = 0; - - UPDATE department z - JOIN tNestedTree t ON t.id = z.id - SET z.path = t.path, - z.lft = t.lft, - z.rgt = t.rgt, - z.depth = t.depth, - z.sons = t.sons; - - DROP TEMPORARY TABLE tNestedTree; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_calcTreeRec.sql b/db/changes/10091-iberflora/00-department_calcTreeRec.sql deleted file mode 100644 index 1f24270e2..000000000 --- a/db/changes/10091-iberflora/00-department_calcTreeRec.sql +++ /dev/null @@ -1,75 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_calcTreeRec`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_calcTreeRec`( - vSelf INT, - vPath VARCHAR(255), - vDepth INT, - INOUT vIndex INT, - OUT vSons INT -) -BEGIN -/** - * Calculates and sets the #path, #lft, #rgt, #sons and #depth - * columns for all children of the passed node. Once calculated - * the last node rgt index and the number of sons are returned. - * To update it's children, this procedure calls itself recursively - * for each one. - * - * @vSelf The node identifier - * @vPath The initial path - * @vDepth The initial depth - * @vIndex The initial lft index - * @vSons The number of direct sons - */ - DECLARE vChildFk INT; - DECLARE vLft INT; - DECLARE vMySons INT; - DECLARE vDone BOOL; - DECLARE vChildren CURSOR FOR - SELECT id FROM department - WHERE (vSelf IS NULL AND parentFk IS NULL) - OR (vSelf IS NOT NULL AND parentFk = vSelf); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - SET vSons = 0; - - OPEN vChildren; - myLoop: LOOP - SET vDone = FALSE; - FETCH vChildren INTO vChildFk; - - IF vDone THEN - LEAVE myLoop; - END IF; - - SET vIndex = vIndex + 1; - SET vLft = vIndex; - SET vSons = vSons + 1; - - CALL department_calcTreeRec( - vChildFk, - CONCAT(vPath, vChildFk, '/'), - vDepth + 1, - vIndex, - vMySons - ); - - SET vIndex = vIndex + 1; - - INSERT INTO tNestedTree - SET id = vChildFk, - path = vPath, - lft = vLft, - rgt = vIndex, - depth = vDepth, - sons = vMySons; - END LOOP; - CLOSE vChildren; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_doCalc.sql b/db/changes/10091-iberflora/00-department_doCalc.sql deleted file mode 100644 index ba5c16c48..000000000 --- a/db/changes/10091-iberflora/00-department_doCalc.sql +++ /dev/null @@ -1,35 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_doCalc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() -proc: BEGIN -/** - * Recalculates the department tree. - */ - DECLARE vIsChanged BOOL; - - DECLARE CONTINUE HANDLER FOR SQLEXCEPTION - BEGIN - DO RELEASE_LOCK('vn.department_doCalc'); - RESIGNAL; - END; - - IF !GET_LOCK('vn.department_doCalc', 0) THEN - LEAVE proc; - END IF; - - SELECT isChanged INTO vIsChanged - FROM department_recalc; - - IF vIsChanged THEN - UPDATE department_recalc SET isChanged = FALSE; - CALL vn.department_calcTree; - END IF; - - DO RELEASE_LOCK('vn.department_doCalc'); -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-department_getLeaves.sql b/db/changes/10091-iberflora/00-department_getLeaves.sql deleted file mode 100644 index 436f67dbf..000000000 --- a/db/changes/10091-iberflora/00-department_getLeaves.sql +++ /dev/null @@ -1,84 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `department_getLeaves`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( - vParentFk INT, - vSearch VARCHAR(255) -) -BEGIN - DECLARE vIsNumber BOOL; - DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; - - DROP TEMPORARY TABLE IF EXISTS tNodes; - CREATE TEMPORARY TABLE tNodes - (UNIQUE (id)) - ENGINE = MEMORY - SELECT id FROM department LIMIT 0; - - IF vIsSearch THEN - SET vIsNumber = vSearch REGEXP '^[0-9]+$'; - - INSERT INTO tNodes - SELECT id FROM department - WHERE (vIsNumber AND `name` = vSearch) - OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) - LIMIT 1000; - END IF; - - IF vParentFk IS NULL THEN - DROP TEMPORARY TABLE IF EXISTS tChilds; - CREATE TEMPORARY TABLE tChilds - ENGINE = MEMORY - SELECT id FROM tNodes; - - DROP TEMPORARY TABLE IF EXISTS tParents; - CREATE TEMPORARY TABLE tParents - ENGINE = MEMORY - SELECT id FROM department LIMIT 0; - - myLoop: LOOP - DELETE FROM tParents; - INSERT INTO tParents - SELECT parentFk id - FROM department g - JOIN tChilds c ON c.id = g.id - WHERE g.parentFk IS NOT NULL; - - INSERT IGNORE INTO tNodes - SELECT id FROM tParents; - - IF ROW_COUNT() = 0 THEN - LEAVE myLoop; - END IF; - - DELETE FROM tChilds; - INSERT INTO tChilds - SELECT id FROM tParents; - END LOOP; - - DROP TEMPORARY TABLE - tChilds, - tParents; - END IF; - - IF !vIsSearch THEN - INSERT IGNORE INTO tNodes - SELECT id FROM department - WHERE parentFk <=> vParentFk; - END IF; - - SELECT d.id, - d.`name`, - d.parentFk, - d.sons - FROM department d - JOIN tNodes n ON n.id = d.id - ORDER BY depth, `name`; - - DROP TEMPORARY TABLE tNodes; -END$$ - -DELIMITER ; - diff --git a/db/changes/10091-iberflora/00-route.sql b/db/changes/10091-iberflora/00-route.sql deleted file mode 100644 index 5d8b8de62..000000000 --- a/db/changes/10091-iberflora/00-route.sql +++ /dev/null @@ -1,10 +0,0 @@ -ALTER TABLE `vn`.`route` -ADD COLUMN `zoneFk` INT NULL AFTER `description`, -ADD INDEX `fk_route_1_idx` (`zoneFk` ASC); -; -ALTER TABLE `vn`.`route` -ADD CONSTRAINT `fk_route_1` - FOREIGN KEY (`zoneFk`) - REFERENCES `vn`.`zone` (`id`) - ON DELETE RESTRICT - ON UPDATE CASCADE; diff --git a/db/changes/10100-allSaints/00-ACL.sql b/db/changes/10100-allSaints/00-ACL.sql deleted file mode 100644 index 39b52df5d..000000000 --- a/db/changes/10100-allSaints/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('UserPhone', '*', '*', 'ALLOW', 'ROLE', 'employee'); diff --git a/db/changes/10100-allSaints/00-travelLog.sql b/db/changes/10100-allSaints/00-travelLog.sql deleted file mode 100644 index fe9d03274..000000000 --- a/db/changes/10100-allSaints/00-travelLog.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`travelLog` ( - `id` int(11) unsigned NOT NULL AUTO_INCREMENT, - `originFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text CHARACTER SET utf8, - `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `oldInstance` text COLLATE utf8_unicode_ci, - `newInstance` text COLLATE utf8_unicode_ci, - `changedModelId` int(11) DEFAULT NULL, - `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn`.`travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-upperGap.sql b/db/changes/10100-allSaints/00-upperGap.sql deleted file mode 100644 index 6554c47b4..000000000 --- a/db/changes/10100-allSaints/00-upperGap.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE `vn`.`packagingConfig` ( - `id` INT NOT NULL AUTO_INCREMENT, - `upperGap` INT NOT NULL, - PRIMARY KEY (`id`)); - -INSERT INTO `vn`.`packagingConfig` (`upperGap`) VALUES ('10'); diff --git a/db/changes/10100-allSaints/00-userLog.sql b/db/changes/10100-allSaints/00-userLog.sql deleted file mode 100644 index f6972796d..000000000 --- a/db/changes/10100-allSaints/00-userLog.sql +++ /dev/null @@ -1,18 +0,0 @@ -CREATE TABLE `vn`.`userLog` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `originFk` int(10) unsigned NOT NULL, - `userFk` int(10) unsigned DEFAULT NULL, - `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, - `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, - `description` text CHARACTER SET utf8, - `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - `oldInstance` text COLLATE utf8_unicode_ci, - `newInstance` text COLLATE utf8_unicode_ci, - `changedModelId` int(11) DEFAULT NULL, - `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`), - KEY `originFk` (`originFk`), - KEY `userFk` (`userFk`), - CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; \ No newline at end of file diff --git a/db/changes/10100-allSaints/00-userPhoneType.sql b/db/changes/10100-allSaints/00-userPhoneType.sql deleted file mode 100644 index 6bfedcc71..000000000 --- a/db/changes/10100-allSaints/00-userPhoneType.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE `vn`.`userPhoneType` ( - `code` VARCHAR(45) NOT NULL, - `description` VARCHAR(255) NULL, - PRIMARY KEY (`code`)); - - - -INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('businessPhone', 'Telefono de empresa del usuario'); -INSERT INTO `vn`.`userPhoneType` (`code`, `description`) VALUES ('personalPhone', 'Telefono personal del usuario'); diff --git a/db/changes/10100-allSaints/01-userPhone.sql b/db/changes/10100-allSaints/01-userPhone.sql deleted file mode 100644 index 54dfbeb26..000000000 --- a/db/changes/10100-allSaints/01-userPhone.sql +++ /dev/null @@ -1,23 +0,0 @@ -CREATE TABLE `vn`.`userPhone` ( - `id` INT NOT NULL AUTO_INCREMENT, - `userFk` INT(10) UNSIGNED NOT NULL, - `typeFk` VARCHAR(45) NOT NULL, - `phone` VARCHAR(25) NOT NULL, - PRIMARY KEY (`id`), - UNIQUE INDEX `UserFk_Phone` (`userFk` ASC, `typeFk` ASC, `phone` ASC)); - - -ALTER TABLE `vn`.`userPhone` -ADD CONSTRAINT `fgnTypeFk` - FOREIGN KEY (typeFk) - REFERENCES `vn`.`userPhoneType` (code) - ON DELETE RESTRICT - ON UPDATE CASCADE; - -ALTER TABLE `vn`.`userPhone` -ADD CONSTRAINT `fgnUserFk` - FOREIGN KEY (userFk) - REFERENCES `account`.`user` (id) - ON DELETE CASCADE - ON UPDATE CASCADE; - diff --git a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql b/db/changes/10100-allSaints/02-catalog_componentCalculate.sql deleted file mode 100644 index 9d4df64c9..000000000 --- a/db/changes/10100-allSaints/02-catalog_componentCalculate.sql +++ /dev/null @@ -1,259 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_componentCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_componentCalculate`( - vZoneFk INT, - vAddressFk INT, - vShipped DATE) -proc: BEGIN -/** - * Calcula los componentes de los articulos de tmp.ticketLot - * - * @param vZoneFk para calcular el transporte - * @param vAgencyModeFk Id del modo de agencia - * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) - * - * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, - * packing, grouping, groupingMode, buyFk, typeFk) - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) - */ - - DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; - DECLARE vMinimumDensityWeight INT DEFAULT 167; - DECLARE vBoxFreightItem INT DEFAULT 71; - DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; - DECLARE vSpecialPriceComponent INT DEFAULT 10; - DECLARE vDeliveryComponent INT DEFAULT 15; - DECLARE vRecoveryComponent INT DEFAULT 17; - DECLARE vSellByPacketComponent INT DEFAULT 22; - DECLARE vBuyValueComponent INT DEFAULT 28; - DECLARE vMarginComponent INT DEFAULT 29; - DECLARE vDiscountLastItemComponent INT DEFAULT 32; - DECLARE vExtraBaggedComponent INT DEFAULT 38; - DECLARE vManaAutoComponent INT DEFAULT 39; - - SELECT volume INTO vBoxVolume - FROM vn.packaging - WHERE id = '94'; - - SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; - - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, tl.warehouseFk, tl.available, - IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, - IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, - IFNULL(pf.rate3, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk - FROM priceFixed pf - JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) - WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - CREATE TEMPORARY TABLE tmp.ticketComponent ( - `warehouseFk` INT UNSIGNED NOT NULL, - `itemFk` INT NOT NULL, - `componentFk` INT UNSIGNED NOT NULL, - `cost` DECIMAL(10,4) NOT NULL, - INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), - UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vBuyValueComponent, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vMarginComponent, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - GROUP BY tc.itemFk, warehouseFk; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk - WHERE cr.recobro > 0.009; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, - tcb.itemFk, - cr.id, - GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN componentRate cr - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - vDeliveryComponent, - vGeneralInflationCoefficient - * ROUND(( - i.compression - * r.cm3 - * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) - * IFNULL((z.price - z.bonus) - * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 - ) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN zone z ON z.id = vZoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk - AND r.Id_Article = tcc.itemFk - HAVING cost <> 0; - - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = vAddressFk; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN componentRate cr ON cr.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE cr.classRate IS NULL - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate - FROM tmp.ticketComponent tc - JOIN componentRate cr ON cr.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/02-ticketCalculate__.sql b/db/changes/10100-allSaints/02-ticketCalculate__.sql deleted file mode 100644 index 37903f7c3..000000000 --- a/db/changes/10100-allSaints/02-ticketCalculate__.sql +++ /dev/null @@ -1,17 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`ticketCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculate__`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO utilizar catalog_calculate - CALL vn.catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); -END$$ - -DELIMITER ; -; diff --git a/db/changes/10100-allSaints/03-available_calc.sql b/db/changes/10100-allSaints/03-available_calc.sql deleted file mode 100644 index 70416f5df..000000000 --- a/db/changes/10100-allSaints/03-available_calc.sql +++ /dev/null @@ -1,63 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `available_calc`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `available_calc`( - vDate DATE, - vAddress INT, - vAgencyMode INT) -BEGIN -/** - * Calculates the available for all available stores - * according to the given parameters. - * - * @param vDate The delivery date - * @param vAddress The delivery address id - * @param vAgencyMode The shipping agency - * @return tmp.availableCalc(calcFk) The available cache ids - */ - DECLARE vCalcFk INT; - DECLARE vShipment DATE; - DECLARE vWarehouse INT; - DECLARE vDone BOOL; - - DECLARE cWarehouses CURSOR FOR - SELECT warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - -- Establecemos los almacenes y las fechas que van a entrar al disponible - - CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); - - DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; - CREATE TEMPORARY TABLE tmp.availableCalc( - calcFk INT UNSIGNED, - PRIMARY KEY (calcFk) - ) - ENGINE = MEMORY; - - OPEN cWarehouses; - - l: LOOP - SET vDone = FALSE; - FETCH cWarehouses INTO vWarehouse, vShipment; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh(vCalcFk, FALSE, vWarehouse, vShipment); - - INSERT IGNORE INTO tmp.availableCalc - SET calcFk = vCalcFk; - END LOOP; - - CLOSE cWarehouses; - DROP TEMPORARY TABLE tmp.zoneGetShipped; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-catalog_calculate.sql b/db/changes/10100-allSaints/03-catalog_calculate.sql deleted file mode 100644 index e6f4f7375..000000000 --- a/db/changes/10100-allSaints/03-catalog_calculate.sql +++ /dev/null @@ -1,119 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_calculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-order_confirmWithUser.sql b/db/changes/10100-allSaints/03-order_confirmWithUser.sql deleted file mode 100644 index e7b4b2edb..000000000 --- a/db/changes/10100-allSaints/03-order_confirmWithUser.sql +++ /dev/null @@ -1,244 +0,0 @@ -USE `hedera`; -DROP procedure IF EXISTS `order_confirmWithUser`; - -DELIMITER $$ -USE `hedera`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `order_confirmWithUser`(IN `vOrder` INT, IN `vUserId` INT) -BEGIN -/** - * Confirms an order, creating each of its tickets on the corresponding - * date, store and user. - * - * @param vOrder The order identifier - * @param vUser The user identifier - */ - DECLARE vOk BOOL; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vWarehouse INT; - DECLARE vShipment DATETIME; - DECLARE vTicket INT; - DECLARE vNotes VARCHAR(255); - DECLARE vItem INT; - DECLARE vConcept VARCHAR(30); - DECLARE vAmount INT; - DECLARE vPrice DECIMAL(10,2); - DECLARE vSale INT; - DECLARE vRate INT; - DECLARE vRowId INT; - DECLARE vDelivery DATE; - DECLARE vAddress INT; - DECLARE vIsConfirmed BOOL; - DECLARE vClientId INT; - DECLARE vCompanyId INT; - DECLARE vAgencyModeId INT; - - DECLARE TICKET_FREE INT DEFAULT 2; - - DECLARE cDates CURSOR FOR - SELECT zgs.shipped, r.warehouse_id - FROM `order` o - JOIN order_row r ON r.order_id = o.id - LEFT JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = r.warehouse_id - WHERE o.id = vOrder AND r.amount != 0 - GROUP BY r.warehouse_id; - - DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate - FROM order_row r - JOIN vn.item i ON i.id = r.item_id - WHERE r.amount != 0 - AND r.warehouse_id = vWarehouse - AND r.order_id = vOrder - ORDER BY r.rate DESC; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - -- Carga los datos del pedido - - SELECT o.date_send, o.address_id, o.note, - o.confirmed, a.clientFk, o.company_id, o.agency_id - INTO vDelivery, vAddress, vNotes, - vIsConfirmed, vClientId, vCompanyId, vAgencyModeId - FROM hedera.`order` o - JOIN vn.address a ON a.id = o.address_id - WHERE o.id = vOrder; - - -- Comprueba que el pedido no está confirmado - - IF vIsConfirmed THEN - CALL util.throw ('ORDER_ALREADY_CONFIRMED'); - END IF; - - -- Comprueba que el pedido no está vacío - - SELECT COUNT(*) > 0 INTO vOk - FROM order_row WHERE order_id = vOrder AND amount > 0; - - IF !vOk THEN - CALL util.throw ('ORDER_EMPTY'); - END IF; - - -- Carga las fechas de salida de cada almacén - - CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); - - -- Trabajador que realiza la acción - - IF vUserId IS NULL THEN - SELECT employeeFk INTO vUserId FROM orderConfig; - END IF; - - -- Crea los tickets del pedido - - START TRANSACTION; - - OPEN cDates; - - lDates: - LOOP - SET vTicket = NULL; - SET vDone = FALSE; - FETCH cDates INTO vShipment, vWarehouse; - - IF vDone THEN - LEAVE lDates; - END IF; - - -- Busca un ticket existente que coincida con los parametros - - SELECT t.id INTO vTicket - FROM vn.ticket t - LEFT JOIN vn.ticketState tls on tls.ticket = t.id - JOIN `order` o - ON o.address_id = t.addressFk - AND vWarehouse = t.warehouseFk - AND o.agency_id = t.agencyModeFk - AND o.date_send = t.landed - AND vShipment = DATE(t.shipped) - WHERE o.id = vOrder - AND t.invoiceOutFk IS NULL - AND IFNULL(tls.alertLevel,0) = 0 - LIMIT 1; - - -- Crea el ticket en el caso de no existir uno adecuado - - IF vTicket IS NULL - THEN - CALL vn.ticketCreateWithUser( - vClientId, - IFNULL(vShipment, CURDATE()), - vWarehouse, - vCompanyId, - vAddress, - vAgencyModeId, - NULL, - vDelivery, - vUserId, - vTicket - ); - ELSE - INSERT INTO vncontrol.inter - SET Id_Ticket = vTicket, - Id_Trabajador = vUserId, - state_id = TICKET_FREE; - END IF; - - INSERT IGNORE INTO vn.orderTicket - SET orderFk = vOrder, - ticketFk = vTicket; - - -- Añade las notas - - IF vNotes IS NOT NULL AND vNotes != '' - THEN - INSERT INTO vn.ticketObservation SET - ticketFk = vTicket, - observationTypeFk = 4 /* salesperson */ , - `description` = vNotes - ON DUPLICATE KEY UPDATE - `description` = CONCAT(VALUES(`description`),'. ', `description`); - END IF; - - -- Añade los movimientos y sus componentes - - OPEN cRows; - - lRows: - LOOP - SET vDone = FALSE; - FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate; - - IF vDone THEN - LEAVE lRows; - END IF; - - INSERT INTO vn.sale - SET - itemFk = vItem, - ticketFk = vTicket, - concept = vConcept, - quantity = vAmount, - price = vPrice, - priceFixed = 0, - isPriceFixed = TRUE; - - SET vSale = LAST_INSERT_ID(); - - INSERT INTO vn.saleComponent - (saleFk, componentFk, `value`) - SELECT vSale, cm.component_id, cm.price - FROM order_component cm - JOIN bi.tarifa_componentes tc - ON tc.Id_Componente = cm.component_id - WHERE cm.order_row_id = vRowId - GROUP BY vSale, cm.component_id; - - UPDATE order_row SET Id_Movimiento = vSale - WHERE id = vRowId; - - END LOOP; - - CLOSE cRows; - - -- Fija el coste - - DROP TEMPORARY TABLE IF EXISTS tComponents; - CREATE TEMPORARY TABLE tComponents - (INDEX (saleFk)) - ENGINE = MEMORY - SELECT SUM(sc.`value`) valueSum, sc.saleFk - FROM vn.saleComponent sc - JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk - JOIN bi.tarifa_componentes_series tcs - ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id - AND tcs.base - JOIN vn.sale s - ON s.id = sc.saleFk - WHERE s.ticketFk = vTicket - GROUP BY sc.saleFk; - - UPDATE vn.sale s - JOIN tComponents mc ON mc.saleFk = s.id - SET s.priceFixed = valueSum; - - DROP TEMPORARY TABLE tComponents; - END LOOP; - - CLOSE cDates; - - DELETE FROM basketOrder WHERE orderFk = vOrder; - UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() - WHERE id = vOrder; - - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/03-ticketCalculateClon.sql b/db/changes/10100-allSaints/03-ticketCalculateClon.sql deleted file mode 100644 index 86d1c6033..000000000 --- a/db/changes/10100-allSaints/03-ticketCalculateClon.sql +++ /dev/null @@ -1,88 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCalculateClon`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCalculateClon`(IN vTicketNew INT, vTicketOld INT) -BEGIN - /* - * @vTicketNew id del nuevo ticket clonado - * @vTicketOld id ticket original, a partir del qual se clonara el nuevo - * Este procedimiento "rebioniza" una linea, eliminando los componentes existentes e insertandolos de nuevo - */ - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouse SMALLINT; - DECLARE vAgencyMode INT; - DECLARE vAddress INT; - DECLARE vLanded DATE; - DECLARE vAgency INT; - DECLARE vZoneFk INT; - - REPLACE INTO orderTicket(orderFk,ticketFk) - SELECT orderFk, vTicketNew - FROM orderTicket - WHERE ticketFk = vTicketOld; - - SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk - INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk - FROM vn.agencyMode a - JOIN vn.ticket t ON t.agencyModeFk = a.id - WHERE t.id = vTicketNew; - - IF vLanded IS NULL THEN - CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); - UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk - SET t.landed = zgl.landed, - t.zone = zgl.zoneFk - WHERE t.id = vTicketNew; - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - END IF; - - -- rellena la tabla tmp.buyUltimate con la ultima compra - CALL buyUltimate(vWarehouse, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - - CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); - - -- Bionizamos lineas con Preu = 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, vWarehouse warehouseFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew AND s.price = 0; - - CALL ticketComponentUpdateSale(1); - - -- Bionizamos lineas con Preu > 0 - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT s.id saleFk, vWarehouse warehouseFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk WHERE s.ticketFk = vTicketNew - AND s.price > 0; - - CALL ticketComponentUpdateSale(6); - - -- Log - CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); - - -- Limpieza - DROP TEMPORARY TABLE IF EXISTS tmp.buyUltimate; - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; -END$$ - -DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql b/db/changes/10100-allSaints/03-ticketComponentCalculate.sql deleted file mode 100644 index 4547c4c64..000000000 --- a/db/changes/10100-allSaints/03-ticketComponentCalculate.sql +++ /dev/null @@ -1,262 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`ticketComponentCalculate`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN --- OBSOLETO usar catalog_componentCalculate -/** - * Calcula los componentes de un ticket - * - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id del modo de agencia - * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, - * packing, grouping, groupingMode, buyFk, typeFk) - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) - */ - - DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; - DECLARE vMinimumDensityWeight INT DEFAULT 167; - DECLARE vBoxFreightItem INT DEFAULT 71; - DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; - DECLARE vSpecialPriceComponent INT DEFAULT 10; - DECLARE vDeliveryComponent INT DEFAULT 15; - DECLARE vRecoveryComponent INT DEFAULT 17; - DECLARE vSellByPacketComponent INT DEFAULT 22; - DECLARE vBuyValueComponent INT DEFAULT 28; - DECLARE vMarginComponent INT DEFAULT 29; - DECLARE vDiscountLastItemComponent INT DEFAULT 32; - DECLARE vExtraBaggedComponent INT DEFAULT 38; - DECLARE vManaAutoComponent INT DEFAULT 39; - - - - SELECT volume INTO vBoxVolume - FROM vn.packaging - WHERE id = '94'; - - SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; - - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, tl.warehouseFk, tl.available, - IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, - IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, - IFNULL(pf.rate3, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice,b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, aho.warehouseFk - FROM priceFixed pf - JOIN tmp.zoneGetShipped aho ON pf.warehouseFk = aho.warehouseFk OR pf.warehouseFk = 0 - WHERE aho.shipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; - CREATE TEMPORARY TABLE tmp.ticketComponent ( - `warehouseFk` INT UNSIGNED NOT NULL, - `itemFk` INT NOT NULL, - `componentFk` INT UNSIGNED NOT NULL, - `cost` DECIMAL(10,4) NOT NULL, - INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), - UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vBuyValueComponent, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vMarginComponent, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - GROUP BY tc.itemFk, warehouseFk; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk - WHERE cr.recobro > 0.009; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + prices_modifier_rate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - WHERE ms.prices_modifier_activated - HAVING manaAuto <> 0; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, - tcb.itemFk, - cr.id, - GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN componentRate cr - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - vDeliveryComponent, - vGeneralInflationCoefficient - * ROUND(( - i.compression - * r.cm3 - * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) - * IFNULL((z.price - z.bonus) - * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 - ) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN agencyMode am ON am.id = vAgencyModeFk - JOIN `address` a ON a.id = vAddressFk - JOIN tmp.zoneGetShipped zgs ON zgs.warehouseFk = tcc.warehouseFk - JOIN zone z ON z.id = zgs.id - LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk - AND r.Id_Article = tcc.itemFk - HAVING cost <> 0; - - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = vAddressFk; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN componentRate cr ON cr.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE cr.classRate IS NULL - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate - FROM tmp.ticketComponent tc - JOIN componentRate cr ON cr.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) / weightGrouping AS DECIMAL(10,2)) priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; - CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; -END$$ - -DELIMITER ; -; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql b/db/changes/10100-allSaints/03-ticketCreateWithUser.sql deleted file mode 100644 index 8135c72bf..000000000 --- a/db/changes/10100-allSaints/03-ticketCreateWithUser.sql +++ /dev/null @@ -1,88 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithUser`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF vAgencyModeFk IS NOT NULL THEN - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - IF vZoneFk IS NULL OR vZoneFk = 0 THEN - CALL util.throw ('NOT_ZONE_WITH_THIS_PARAMETERS'); - END IF; - END IF; - INSERT INTO ticket ( - clientFk, - shipped, - addressFk, - agencyModeFk, - nickname, - warehouseFk, - routeFk, - companyFk, - landed, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - vAgencyModeFk, - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; diff --git a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql b/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql deleted file mode 100644 index b4840e31d..000000000 --- a/db/changes/10100-allSaints/03-ticketCreateWithoutZone.sql +++ /dev/null @@ -1,90 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketCreateWithoutZone`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( - vClientId INT - ,vShipped DATE - ,vWarehouseFk INT - ,vCompanyFk INT - ,vAddressFk INT - ,vAgencyModeFk INT - ,vRouteFk INT - ,vlanded DATE - ,vUserId INT - ,OUT vNewTicket INT) -BEGIN - - DECLARE vZoneFk INT; - - IF vClientId IS NULL THEN - CALL util.throw ('CLIENT_NOT_ESPECIFIED'); - END IF; - - IF NOT vAddressFk OR vAddressFk IS NULL THEN - SELECT id INTO vAddressFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - IF NOT vAgencyModeFk OR vAgencyModeFk IS NULL THEN - SELECT agencyModeFk INTO vAgencyModeFk - FROM address - WHERE clientFk = vClientId AND isDefaultAddress; - END IF; - - CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - - SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; - - INSERT INTO vn2008.Tickets ( - Id_Cliente, - Fecha, - Id_Consigna, - Id_Agencia, - Alias, - warehouse_id, - Id_Ruta, - empresa_id, - landing, - zoneFk - ) - SELECT - vClientId, - vShipped, - a.id, - IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), - a.nickname, - vWarehouseFk, - IF(vRouteFk,vRouteFk,NULL), - vCompanyFk, - vlanded, - vZoneFk - FROM address a - JOIN agencyMode am ON am.id = a.agencyModeFk - WHERE a.id = vAddressFk; - - SET vNewTicket = LAST_INSERT_ID(); - - INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) - SELECT vNewTicket, ao.observationTypeFk, ao.description - FROM addressObservation ao - JOIN address a ON a.id = ao.addressFk - WHERE a.id = vAddressFk; - - -- CALL logAddWithUser(vNewTicket, vUserId, 'insert', 'ticket', CONCAT('Ha creado el ticket', ' ', vNewTicket)); - INSERT INTO vn.ticketLog - SET originFk = vNewTicket, userFk = vUserId, `action` = 'insert', description = CONCAT('Ha creado el ticket:', ' ', vNewTicket); - - IF (SELECT ct.isCreatedAsServed FROM vn.clientType ct JOIN vn.client c ON c.typeFk = ct.code WHERE c.id = vClientId ) <> FALSE THEN - INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) - SELECT id, vNewTicket, getWorker() - FROM state - WHERE `code` = 'DELIVERED'; - END IF; -END$$ - -DELIMITER ; - diff --git a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql b/db/changes/10100-allSaints/05-catalog_calcFromItem.sql deleted file mode 100644 index 40b2c2eb8..000000000 --- a/db/changes/10100-allSaints/05-catalog_calcFromItem.sql +++ /dev/null @@ -1,31 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `catalog_calcFromItem`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calcFromItem`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT, - vItemFk INT) -BEGIN -/** - * Calculates available and price for a single item. - * - * @param vItemFk The item id - * @return tmp.ticketCalculateItem - * @return tmp.ticketComponentPrice - * @return tmp.ticketComponent - * @return tmp.ticketLot - * @return tmp.zoneGetShipped - */ - DROP TEMPORARY TABLE IF EXISTS tmp.item; - CREATE TEMPORARY TABLE tmp.item - ENGINE = MEMORY - SELECT vItemFk itemFk; - - CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); - DROP TEMPORARY TABLE tmp.item; -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-chatConfig.sql b/db/changes/10110-postCampaign/00-chatConfig.sql deleted file mode 100644 index e0423bb86..000000000 --- a/db/changes/10110-postCampaign/00-chatConfig.sql +++ /dev/null @@ -1,11 +0,0 @@ -USE `vn`; - -CREATE TABLE `vn`.`chatConfig` ( - `id` INT NOT NULL AUTO_INCREMENT, - `uri` VARCHAR(255) NOT NULL, - `user` VARCHAR(50) NOT NULL, - `password` VARCHAR(50) NOT NULL, - PRIMARY KEY (`id`)); - - -INSERT INTO `vn`.`chatConfig` (`uri`, `user`, `password`) VALUES ('https://chat.verdnatura.es/api/v1', 'VnBot', 'Ub606cux7op.'); diff --git a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql b/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql deleted file mode 100644 index 5e69e28ad..000000000 --- a/db/changes/10110-postCampaign/00-clientBeforeUpdate.sql +++ /dev/null @@ -1,51 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`client_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`client_beforeUpdate` - BEFORE UPDATE ON `client` - FOR EACH ROW -BEGIN - DECLARE vText VARCHAR(255) DEFAULT NULL; - -- Comprueba que el formato de los teléfonos es válido - - IF !(NEW.phone <=> OLD.phone) THEN - CALL pbx.phone_isValid(NEW.phone); - END IF; - - IF !(NEW.mobile <=> OLD.mobile) THEN - CALL pbx.phone_isValid(NEW.mobile); - END IF; - - IF !(NEW.fax <=> OLD.fax) THEN - CALL pbx.phone_isValid(NEW.fax); - END IF; - - IF NEW.payMethodFk = 4 AND NEW.dueDay = 0 THEN - SET NEW.dueDay = 5; - END IF; - - -- Avisar al comercial si ha llegado la documentación sepa/core - - IF NEW.hasSepaVnl AND !OLD.hasSepaVnl THEN - SET vText = 'Sepa de VNL'; - END IF; - - IF NEW.hasCoreVnl AND !OLD.hasCoreVnl THEN - SET vText = 'Core de VNL'; - END IF; - - IF vText IS NOT NULL - THEN - INSERT INTO mail(sender, replyTo, `subject`, body) - SELECT - CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), - 'administracion@verdnatura.es', - CONCAT('Cliente ', NEW.id), - CONCAT('Recibida la documentación: ', vText) - FROM worker w - LEFT JOIN account.user u ON w.userFk = u.id AND u.active - LEFT JOIN account.account ac ON ac.id = u.id - WHERE w.id = NEW.salesPersonFk; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-clientGetMana.sql b/db/changes/10110-postCampaign/00-clientGetMana.sql deleted file mode 100644 index dcf9171b2..000000000 --- a/db/changes/10110-postCampaign/00-clientGetMana.sql +++ /dev/null @@ -1,75 +0,0 @@ -DROP function IF EXISTS `vn`.`clientGetMana`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`clientGetMana`(vClient INT) RETURNS decimal(10,2) - DETERMINISTIC -BEGIN -/** - * Devuelve el mana del cliente. - * - * @param vClient Id del cliente - * @return Mana del cliente - */ - DECLARE vMana DECIMAL(10,2); - DECLARE vFromDated DATE; - DECLARE vHasMana BOOLEAN; - DECLARE vManaComponent INT; - DECLARE vAutoManaComponent INT; - DECLARE vManaBank INT; - DECLARE vManaGreugeType INT; - - SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; - SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; - SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; - SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; - - SELECT COUNT(*) INTO vHasMana - FROM `client` c - WHERE c.id = vClient AND c.typeFk = 'normal'; - - IF NOT vHasMana THEN - RETURN 0; - END IF; - - SELECT max(dated) INTO vFromDated - FROM clientManaCache; - - SELECT sum(mana) INTO vMana - FROM - ( - SELECT mana - FROM clientManaCache - WHERE clientFk = vClient - AND dated = vFromDated - UNION ALL - SELECT s.quantity * value - FROM ticket t - JOIN address a ON a.id = t.addressFk - JOIN sale s on s.ticketFk = t.id - JOIN saleComponent sc on sc.saleFk = s.id - WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) - AND t.shipped > vFromDated - AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) - AND a.clientFk = vClient - UNION ALL - SELECT - amountPaid - FROM receipt r - JOIN `client` c ON c.id = r.clientFk - WHERE r.bankFk = vManaBank - AND r.payed > vFromDated - AND r.payed <= CURDATE() - AND c.id = vClient - UNION ALL - SELECT g.amount - FROM greuge g - JOIN `client` c ON c.id = g.clientFk - WHERE g.greugeTypeFk = vManaGreugeType - AND g.shipped > vFromDated - AND g.shipped <= CURDATE() - AND c.id = vClient - ) sub; - RETURN IFNULL(vMana,0); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql b/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql deleted file mode 100644 index a981fd5cb..000000000 --- a/db/changes/10110-postCampaign/00-clientPackagingOverstock.sql +++ /dev/null @@ -1,97 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`clientPackagingOverstock`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) -BEGIN - DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; - CREATE TEMPORARY TABLE tmp.clientPackagingOverstock - ENGINE = MEMORY - SELECT itemFk, - sum(GotfromClient) - sum(SenttoClient) as devueltos, - sum(InvoicedtoClient) - sum(InvoicedfromClient) as facturados, - LEAST( - sum(GotfromClient) - sum(SenttoClient), - sum(InvoicedtoClient) - sum(InvoicedfromClient) - ) as abonables - FROM - ( - SELECT t.*, - IF(@month = month, 0, 1) monthEnd, - @month := month - FROM - ( - SELECT x.id as ticketFk, - date(x.shipped) as shipped, - x.itemFk, - IFNULL(cast(sum(x.InvoicedtoClient) as DECIMAL(10,0)),0) InvoicedtoClient, - IFNULL(cast(sum(x.InvoicedfromClient) as DECIMAL(10,0)),0) InvoicedfromClient, - IFNULL(cast(sum(x.SenttoClient) as DECIMAL(10,0)),0) SenttoClient, - IFNULL(cast(sum(x.GotfromClient) as DECIMAL(10,0)),0) GotfromClient, - i.name as concept, - x.refFk as invoice, - month(shipped) month, - x.companyFk - FROM - ( - SELECT t.id, - t.shipped, - IFNULL(pe.equivalentFk, s.itemFk) itemFk, - IF(s.quantity > 0, s.quantity, NULL) InvoicedtoClient, - IF(s.quantity < 0, -s.quantity, NULL) InvoicedfromClient, - NULL SenttoClient, - NULL GotfromClient, - t.refFk, - @month := 0 month, - t.companyFk - FROM sale s - JOIN ticket t on t.id = s.ticketFk - JOIN packaging p ON p.itemFk = s.itemFk - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk - WHERE t.clientFk = vClientFk - AND t.shipped > '2017-11-30' - AND p.isPackageReturnable - UNION ALL - SELECT NULL, - '2017-11-30', - IFNULL(pe.equivalentFk, tps.itemFk) itemFk, - tps.sent InvoicedtoClient, - tps.returned InvoicedfromClient, - NULL SenttoClient, - NULL GotfromClient, - 'Histórico', - NULL, - NULL - - FROM ticketPackagingStartingStock tps - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk - WHERE tps.clientFk = vClientFk - AND tps.isForgetable = FALSE - UNION ALL - SELECT t.id, - t.shipped, - IFNULL(pe.equivalentFk, p.itemFk) itemFk, - NULL, - NULL, - IF(tp.quantity > 0 AND t.shipped <= TIMESTAMPADD(DAY, - vGraceDays, CURDATE()), tp.quantity, NULL) SenttoClient, - IF(tp.quantity < 0, -tp.quantity, NULL) GotfromClient, - NULL AS refFk, - NULL, - t.companyFk - FROM ticketPackaging tp - JOIN ticket t on t.id = tp.ticketFk - JOIN packaging p ON p.id = tp.packagingFk - LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk - WHERE t.clientFk = vClientFk - AND t.shipped > '2017-11-21' ) x - - JOIN item i ON x.itemFk = i.id - GROUP BY x.id, x.itemFk - ) t - ORDER BY itemFk, shipped DESC - ) t2 - GROUP BY itemFk; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-clonTravelComplete.sql b/db/changes/10110-postCampaign/00-clonTravelComplete.sql deleted file mode 100644 index 9817613f4..000000000 --- a/db/changes/10110-postCampaign/00-clonTravelComplete.sql +++ /dev/null @@ -1,132 +0,0 @@ -DROP procedure IF EXISTS `vn`.`clonTravelComplete`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) -BEGIN - - DECLARE vTravelNew INT; - DECLARE vEntryNew INT; - DECLARE vDone BIT DEFAULT 0; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM entry e - JOIN travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE vRsBuy CURSOR FOR - SELECT b.* - FROM buy b - JOIN entry e - ON b.entryFk = e.id - WHERE e.travelFk = vTravelNew and b.entryFk=entryNew - ORDER BY e.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg - FROM travel - WHERE id = vTravelFk; - - SET vTravelNew = LAST_INSERT_ID(); - SET vDone = 0; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO entry (supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vTravelNew, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - - INSERT INTO buy (entryFk, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked) - SELECT vEntryNew, - itemFk, - quantity, - buyingValue, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isChecked - FROM buy - WHERE entryFk = vAuxEntryFk; - - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - CLOSE vRsEntry; - COMMIT; - END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-country.sql b/db/changes/10110-postCampaign/00-country.sql deleted file mode 100644 index dcc883ab8..000000000 --- a/db/changes/10110-postCampaign/00-country.sql +++ /dev/null @@ -1,10 +0,0 @@ -USE `vn`; - -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 1); -UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 2); -UPDATE `vn`.`country` SET `ibanLength` = '22' WHERE (`id` = 3); -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 4); -UPDATE `vn`.`country` SET `ibanLength` = '18' WHERE (`id` = 5); -UPDATE `vn`.`country` SET `ibanLength` = '25' WHERE (`id` = 8); -UPDATE `vn`.`country` SET `ibanLength` = '27' WHERE (`id` = 19); -UPDATE `vn`.`country` SET `ibanLength` = '24' WHERE (`id` = 30); diff --git a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql b/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql deleted file mode 100644 index 5ca0fd131..000000000 --- a/db/changes/10110-postCampaign/00-creditClassificationBeforeUpdate.sql +++ /dev/null @@ -1,16 +0,0 @@ - -DELIMITER $$ -DROP TRIGGER IF EXISTS `vn`.`creditClassification_BEFORE_UPDATE` $$ - - -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW -BEGIN - IF NEW.client <> OLD.client THEN - CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); - END IF; - IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE `client` c - SET creditInsurance = 0 WHERE c.id = NEW.client; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql b/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql deleted file mode 100644 index 4429b1e97..000000000 --- a/db/changes/10110-postCampaign/00-creditInsuranceAfterInsert.sql +++ /dev/null @@ -1,13 +0,0 @@ - -DELIMITER $$ - -DROP TRIGGER IF EXISTS `vn`.`creditInsurance_AFTER_INSERT` $$ - -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW -BEGIN - UPDATE `client` c - JOIN vn.creditClassification cc ON cc.client = c.id - SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; - -END$$ -DELIMITER ; diff --git a/db/changes/10110-postCampaign/00-department_doCalc.sql b/db/changes/10110-postCampaign/00-department_doCalc.sql deleted file mode 100644 index 7adeb30f0..000000000 --- a/db/changes/10110-postCampaign/00-department_doCalc.sql +++ /dev/null @@ -1,3 +0,0 @@ -USE `vn`; - -CREATE DEFINER=`root`@`%` EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql b/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql deleted file mode 100644 index 091acef43..000000000 --- a/db/changes/10110-postCampaign/00-duaInvoicingBooking.sql +++ /dev/null @@ -1,74 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`duaInvoiceInBooking`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`duaInvoiceInBooking`(vDuaFk INT) -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vInvoiceFk INT; - DECLARE vASIEN BIGINT DEFAULT 0; - DECLARE vCounter INT DEFAULT 0; - - DECLARE rs CURSOR FOR - SELECT e.invoiceInFk - FROM entry e - JOIN duaEntry de ON de.entryFk = e.id - JOIN invoiceIn ii ON ii.id = e.invoiceInFk - WHERE de.duaFk = vDuaFk - AND de.customsValue - AND ii.isBooked = FALSE; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - OPEN rs; - - UPDATE invoiceIn ii - JOIN entry e ON e.invoiceInFk = ii.id - JOIN duaEntry de ON de.entryFk = e.id - JOIN dua d ON d.id = de.duaFk - SET ii.isBooked = TRUE, - 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.isConfirmed = TRUE - WHERE d.id = vDuaFk; - - SELECT IFNULL(ASIEN,0) INTO vASIEN - FROM dua - WHERE id = vDuaFk; - - FETCH rs INTO vInvoiceFk; - - WHILE NOT done DO - - CALL invoiceInBookingMain(vInvoiceFk); - - IF vCounter > 0 OR vASIEN > 0 THEN - - UPDATE XDiario x - JOIN config c ON c.ASIEN = x.ASIEN - SET x.ASIEN = vASIEN; - - ELSE - - SELECT ASIEN INTO vASIEN FROM config; - - END IF; - - SET vCounter = vCounter + 1; - - FETCH rs INTO vInvoiceFk; - - END WHILE; - - CLOSE rs; - - UPDATE dua - SET ASIEN = vASIEN - WHERE id = vDuaFk; - -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql b/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql deleted file mode 100644 index 21b827a75..000000000 --- a/db/changes/10110-postCampaign/00-getItemVisibleAvailable.sql +++ /dev/null @@ -1,17 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `getItemVisibleAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 - CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql b/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql deleted file mode 100644 index 4701e7124..000000000 --- a/db/changes/10110-postCampaign/00-itemGetVisibleAvailable.sql +++ /dev/null @@ -1,17 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `itemGetVisibleAvailable`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 - CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql b/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql deleted file mode 100644 index e6b6df2f9..000000000 --- a/db/changes/10110-postCampaign/00-item_getVisibleAvailable.sql +++ /dev/null @@ -1,71 +0,0 @@ - -USE `vn`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( - vItem INT, - vDate DATE, - vWarehouse TINYINT, - vRefresh BOOL) -BEGIN - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - DECLARE vVisibleAltillo INT; - - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); - CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - - SELECT visible INTO vVisibleAltillo - FROM vn.itemShelvingStock - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - IF vRefresh THEN - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT vItem item_id, 0 stock, 0 visible; - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - vi.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN vn2008.tmp_item v - ON v.item_id = i.id - LEFT JOIN cache.available av - ON av.calc_id = vAvailableCalc AND av.item_id = i.id - LEFT JOIN cache.visible vi - ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id - LEFT JOIN cache.stock st - ON st.warehouse_id = vWarehouse AND st.item_id = i.id - WHERE (vItem IS NULL OR i.id = vItem); - - ELSE - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - v.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = i.id AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = i.id AND av.calc_id = vAvailableCalc - WHERE (vItem IS NULL OR i.id = vItem); - - END IF; - -END$$ - -DELIMITER ; -; diff --git a/db/changes/10110-postCampaign/00-payMethod.sql b/db/changes/10110-postCampaign/00-payMethod.sql deleted file mode 100644 index e2421ee53..000000000 --- a/db/changes/10110-postCampaign/00-payMethod.sql +++ /dev/null @@ -1,7 +0,0 @@ -USE `vn`; - -ALTER TABLE `vn`.`payMethod` -ADD COLUMN `code` VARCHAR(50) CHARACTER SET 'utf8' COLLATE 'utf8_general_ci' NULL AFTER `id`; - -UPDATE `vn`.`payMethod` SET `code` = 'bankDraft' WHERE (`id` = '4'); -UPDATE `vn`.`payMethod` SET `code` = 'card' WHERE (`id` = '5'); diff --git a/db/changes/10110-postCampaign/00-rangeDateInfo.sql b/db/changes/10110-postCampaign/00-rangeDateInfo.sql deleted file mode 100644 index 816269ef9..000000000 --- a/db/changes/10110-postCampaign/00-rangeDateInfo.sql +++ /dev/null @@ -1,41 +0,0 @@ -DROP procedure IF EXISTS `vn`.`rangeDateInfo`; - -DELIMITER $$ -CREATE PROCEDURE `vn`.`rangeDateInfo` (vStarted DATE, vEnded DATE) -BEGIN -/** - * Crea una tabla temporal con las fechas - * desde una fecha inicial a una final - * @param vStarted fecha inicial - * @param vEnded fecha final - */ - DECLARE vDated DATE DEFAULT vStarted; - - DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; - CREATE TEMPORARY TABLE tmp.rangeDate( - `dated` DATE, - `period` INT, - `month` INT, - `year` INT, - `day` INT, - `week` INT, - `yearMonth` INT - ) - ENGINE = MEMORY; - - WHILE vDated <= vEnded DO - INSERT INTO tmp.rangeDate - SET `dated` = vDated, - `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), - `month` = MONTH(vDated), - `year` = YEAR(vDated), - `day` = DAY(vDated), - `week` = WEEK(vDated, 1), - `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); - - SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); - END WHILE; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-sample.sql b/db/changes/10110-postCampaign/00-sample.sql deleted file mode 100644 index 68e9d1a0f..000000000 --- a/db/changes/10110-postCampaign/00-sample.sql +++ /dev/null @@ -1,8 +0,0 @@ -USE `vn`; - -UPDATE `vn`.`sample` SET `description` = 'Bienvenida como nuevo cliente' WHERE (`id` = '12'); -UPDATE `vn`.`sample` SET `description` = 'Instalación y configuración de impresora de coronas' WHERE (`id` = '13'); -UPDATE `vn`.`sample` SET `description` = 'Solicitud de domiciliación bancaria' WHERE (`id` = '14'); -UPDATE `vn`.`sample` SET `description` = 'Aviso inicial por saldo deudor' WHERE (`id` = '15'); -UPDATE `vn`.`sample` SET `description` = 'Aviso reiterado por saldo deudor' WHERE (`id` = '16'); -UPDATE `vn`.`sample` SET `isVisible` = '0' WHERE (`id` = '17'); diff --git a/db/changes/10110-postCampaign/00-ticketClosure.sql b/db/changes/10110-postCampaign/00-ticketClosure.sql deleted file mode 100644 index 07c7ef812..000000000 --- a/db/changes/10110-postCampaign/00-ticketClosure.sql +++ /dev/null @@ -1,116 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticketClosure`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticketClosure`() -BEGIN -/** - * Realiza el cierre de todos los - * tickets de la table ticketClosure. - */ - DECLARE vDone BOOL; - DECLARE vClientFk INT; - DECLARE vTicketFk INT; - DECLARE vIsTaxDataChecked BOOL; - DECLARE vCompanyFk INT; - DECLARE vShipped DATE; - DECLARE vPriority INT DEFAULT 1; - DECLARE vReportDeliveryNote INT DEFAULT 1; - DECLARE vNewInvoiceId INT; - DECLARE vHasDailyInvoice BOOL; - DECLARE vWithPackage BOOL; - - DECLARE cur CURSOR FOR - SELECT ticketFk FROM tmp.ticketClosure; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - RESIGNAL; - END; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; - CREATE TEMPORARY TABLE tmp.ticketClosure2 - SELECT ticketFk FROM tmp.ticketClosure; - INSERT INTO tmp.ticketClosure - SELECT id FROM stowaway s - JOIN tmp.ticketClosure2 tc ON s.shipFk = tc.ticketFk; - OPEN cur; - - proc: LOOP - SET vDone = FALSE; - - FETCH cur INTO vTicketFk; - - IF vDone THEN - LEAVE proc; - END IF; - - -- ticketClosure start - SELECT - c.id, - c.isTaxDataChecked, - t.companyFk, - t.shipped, - co.hasDailyInvoice, - w.isManaged - INTO vClientFk, - vIsTaxDataChecked, - vCompanyFk, - vShipped, - vHasDailyInvoice, - vWithPackage - FROM ticket t - JOIN `client` c ON c.id = t.clientFk - JOIN province p ON p.id = c.provinceFk - JOIN country co ON co.id = p.countryFk - JOIN warehouse w ON w.id = t.warehouseFk - WHERE t.id = vTicketFk; - - INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity) - (SELECT vTicketFk, p.id, COUNT(*) - FROM expedition e - JOIN packaging p ON p.itemFk = e.itemFk - WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable - AND vWithPackage - GROUP BY p.itemFk); - - -- No retornables o no catalogados - INSERT INTO sale (itemFk, ticketFk, concept, quantity, price, isPriceFixed) - (SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 - FROM expedition e - JOIN item i ON i.id = e.itemFk - LEFT JOIN packaging p ON p.itemFk = i.id - WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0 - AND getSpecialPrice(e.itemFk, vClientFk) > 0 - GROUP BY e.itemFk); - - IF(vHasDailyInvoice) THEN - - -- Facturacion rapida - CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); - -- Facturar si está contabilizado - IF vIsTaxDataChecked THEN - CALL invoiceOut_newFromClient( - vClientFk, - (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), - vShipped, - vCompanyFk, - NULL, - vNewInvoiceId); - END IF; - ELSE - -- Albaran_print - CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - END IF; - - -- ticketClosure end - END LOOP; - - CLOSE cur; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure2; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-ticketRequest.sql b/db/changes/10110-postCampaign/00-ticketRequest.sql deleted file mode 100644 index cae9e09ce..000000000 --- a/db/changes/10110-postCampaign/00-ticketRequest.sql +++ /dev/null @@ -1,54 +0,0 @@ - -ALTER TABLE `vn`.`ticketRequest` -DROP FOREIGN KEY `fgnAtender`; -ALTER TABLE `vn`.`ticketRequest` -CHANGE COLUMN `atenderFk` `attenderFk` INT(11) NULL DEFAULT NULL ; -ALTER TABLE `vn`.`ticketRequest` -ADD CONSTRAINT `fgnAtender` - FOREIGN KEY (`attenderFk`) - REFERENCES `vn`.`worker` (`id`) - ON UPDATE CASCADE; - - - - -DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeInsert`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW -BEGIN - IF NEW.ticketFk IS NULL THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.requesterFk IS NULL THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; - - IF NEW.attenderFk IS NULL THEN - SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; -END$$ -DELIMITER ; - - -DROP TRIGGER IF EXISTS `vn`.`ticketRequest_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW -BEGIN - IF NEW.saleFk <> OLD.saleFk THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.salesPersonCode <> OLD.salesPersonCode THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; - - IF NEW.buyerCode <> OLD.buyerCode THEN - SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; -END$$ -DELIMITER ; - - diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql deleted file mode 100644 index 885e2998a..000000000 --- a/db/changes/10110-postCampaign/00-ticket_recalcComponents.sql +++ /dev/null @@ -1,77 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponents`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponents`(IN vTicketFk BIGINT ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vIsTicketEditable BOOLEAN; - DECLARE vZoneFk INTEGER; - - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql b/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql deleted file mode 100644 index 90d65fcc1..000000000 --- a/db/changes/10110-postCampaign/00-ticket_recalcComponentsForcePrice.sql +++ /dev/null @@ -1,77 +0,0 @@ -USE `vn`; -DROP procedure IF EXISTS `ticket_recalcComponentsForcePrice`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `ticket_recalcComponentsForcePrice`(IN vTicketFk BIGINT, vIsTicketEditable BOOLEAN ) -proc: BEGIN - -/** - * Este procedimiento trata de "rebionizar" un ticket, - * eliminando los componentes existentes e insertandolos de nuevo - * - * @param vTicketFk Id del ticket - * @return tmp.buyUltimate - */ - DECLARE vShipped DATE; - DECLARE vWarehouseFk SMALLINT; - DECLARE vAgencyModeFk INT; - DECLARE vAddressFk INT; - DECLARE vLanded DATE; - DECLARE vZoneFk INTEGER; - - IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk - INTO vIsTicketEditable, vZoneFk - FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket - WHERE id = vTicketFk; - END IF; - SELECT warehouseFk, date(shipped), addressFk, agencyModeFk, landed - INTO vWarehouseFk, vShipped, vAddressFk, vAgencyModeFk, vLanded - FROM ticket - WHERE id = vTicketFk; - - CALL zoneGetShippedWarehouse(vLanded, vAddressFk , vAgencyModeFk); - - CALL vn.buyUltimate (vWarehouseFk, vShipped); -- rellena la tabla buyUltimate con la ultima compra - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouseFk warehouseFk, NULL available, - s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketFk - GROUP BY s.itemFk; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (saleFk)) ENGINE = MEMORY - SELECT id saleFk, vWarehouseFk warehouseFk - FROM sale s - WHERE s.ticketFk = vTicketFk; - - CALL vn.ticketComponentUpdateSale(IF(vIsTicketEditable,1,6)); -- si el ticket esta facturado, respeta los precios - - IF vLanded IS NULL THEN - - CALL zoneGetLanded(vShipped, vAddressFk, vAgencyModeFk, vWarehouseFk); - - UPDATE vn2008.Tickets t - SET t.landing = (SELECT landed FROM tmp.zoneGetLanded) - WHERE Id_Ticket = vTicketFk; - - DROP TEMPORARY TABLE tmp.zoneGetLanded; - - END IF; - - DROP TEMPORARY TABLE tmp.buyUltimate; - DROP TEMPORARY TABLE tmp.ticketComponentPrice; - DROP TEMPORARY TABLE tmp.ticketComponent; - DROP TEMPORARY TABLE tmp.sale; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql b/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql deleted file mode 100644 index c2091ff83..000000000 --- a/db/changes/10110-postCampaign/00-workerTimeControlAdd.sql +++ /dev/null @@ -1,73 +0,0 @@ -DROP function IF EXISTS `vn`.`workerTimeControl_add`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`workerTimeControl_add`( vUserFk INT, vWarehouseFk INT, vTimed DATETIME, vIsManual BOOL) RETURNS int(11) - DETERMINISTIC -BEGIN - DECLARE vDirection VARCHAR(6); - DECLARE vLastIn DATETIME; - DECLARE vDayStayMax INT; - DECLARE vHasDirectionOut INT; - DECLARE vLastInsertedId INT; - - SELECT dayStayMax INTO vDayStayMax - FROM workerTimeControlParams; - - SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; - - IF vDirection = 'out' THEN - - SELECT MAX(timed) INTO vLastIn - FROM workerTimeControl - WHERE userFk = vUserFk - AND direction = 'in' - AND timed < vTimed; - - UPDATE workerTimeControl wtc - SET wtc.direction = 'middle' - WHERE userFk = vUserFk - AND direction = 'out' - AND timed BETWEEN vLastIn AND vTimed; - - ELSE IF vDirection = 'in' THEN - - SELECT COUNT(*) INTO vHasDirectionOut - FROM workerTimeControl wtc - WHERE userFk = vUserFk - AND direction = 'out' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - - UPDATE workerTimeControl wtc - SET wtc.direction = IF (vHasDirectionOut,'middle','out') - WHERE userFk = vUserFk - AND direction = 'in' - AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - - END IF; - END IF; - - INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) - VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - - SET vLastInsertedId = LAST_INSERT_ID(); - - CALL workerTimeControlSOWP(vUserFk, vTimed); - - RETURN vLastInsertedId; -END$$ - -DELIMITER ; - - - -DROP procedure IF EXISTS `vn`.`workerTimeControl_add`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) -BEGIN - - - SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql b/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql deleted file mode 100644 index 8e8c7471b..000000000 --- a/db/changes/10110-postCampaign/00-workerTimeControlCalculate.sql +++ /dev/null @@ -1,41 +0,0 @@ -DROP procedure IF EXISTS `vn`.`timeControl_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - SET @vIsOdd := TRUE; - SET @vUser := NULL; - SET @vDated := NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - - CREATE TEMPORARY TABLE tmp.timeControlCalculate - SELECT userFk, - dated, - IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, - SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, - @timeWork / 3600 timeWorkDecimal - FROM (SELECT SUM(timeWork) timeWork, - userFk, - dated - FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), - IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), - IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), - IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), - IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, - IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, - wtc.userFk, - wtc.timed timed, - direction - FROM workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo - ORDER BY userFk, timed - ) sub - GROUP BY userFk, dated - ORDER BY userFk, dated - )sub2; - -END$$ - -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-Ordenes.sql b/db/changes/10110-postCampaign/01-Ordenes.sql deleted file mode 100644 index b2b2f7d35..000000000 --- a/db/changes/10110-postCampaign/01-Ordenes.sql +++ /dev/null @@ -1,53 +0,0 @@ - -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn2008`.`Ordenes` AS - SELECT - `tr`.`id` AS `Id_ORDEN`, - `tr`.`description` AS `ORDEN`, - `tr`.`requesterFk` AS `requesterFk`, - `tr`.`attenderFk` AS `attenderFk`, - `tr`.`quantity` AS `CANTIDAD`, - `tr`.`itemFk` AS `Id_ARTICLE`, - `tr`.`price` AS `PRECIOMAX`, - `tr`.`isOk` AS `isOk`, - `tr`.`saleFk` AS `Id_Movimiento`, - `tr`.`ticketFk` AS `ticketFk`, - `tr`.`response` AS `COMENTARIO`, - `tr`.`created` AS `odbc_date`, - `tr`.`ordered` AS `datORDEN`, - `tr`.`shipped` AS `datTICKET`, - `tr`.`salesPersonCode` AS `CodVENDEDOR`, - `tr`.`buyerCode` AS `CodCOMPRADOR`, - `tr`.`price__` AS `PREU`, - `tr`.`clientFk` AS `Id_CLIENTE`, - `tr`.`ok__` AS `OK`, - `tr`.`total` AS `TOTAL`, - `tr`.`buyed` AS `datCOMPRA`, - `tr`.`ko__` AS `KO` - FROM - `vn`.`ticketRequest` `tr`; - - -CREATE - OR REPLACE ALGORITHM = UNDEFINED - DEFINER = `root`@`%` - SQL SECURITY DEFINER -VIEW `vn`.`ticketRequest__` AS - SELECT - `t`.`Id_ORDEN` AS `id`, - `t`.`ORDEN` AS `description`, - `t`.`requesterFk` AS `requesterFk`, - `t`.`attenderFk` AS `attenderFk`, - `t`.`CANTIDAD` AS `quantity`, - `t`.`Id_ARTICLE` AS `itemFk`, - `t`.`PRECIOMAX` AS `price`, - `t`.`isOk` AS `isOk`, - `t`.`Id_Movimiento` AS `saleFk`, - `t`.`ticketFk` AS `ticketFk`, - `t`.`COMENTARIO` AS `response`, - `t`.`odbc_date` AS `created` - FROM - `vn2008`.`Ordenes` `t`; \ No newline at end of file diff --git a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql b/db/changes/10110-postCampaign/01-bionicCalcReverse.sql deleted file mode 100644 index e3f6b1387..000000000 --- a/db/changes/10110-postCampaign/01-bionicCalcReverse.sql +++ /dev/null @@ -1,92 +0,0 @@ -DROP function IF EXISTS `vn`.`bionicCalcReverse`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` FUNCTION `vn`.`bionicCalcReverse`(vWarehouse INT, - vMargin DECIMAL(10,3), - vRetailedPrice DECIMAL(10,3), - vM3 DECIMAL(10,3), - vAddress INT, - vAgencyMode INT) RETURNS decimal(10,3) - DETERMINISTIC -BEGIN - DECLARE vGeneralInflationCoeficient INT; - DECLARE vVerdnaturaVolumeBox BIGINT; - DECLARE vClientFk INT; - DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; - DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; - DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; - DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; - DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; - DECLARE vComponentCostValue DECIMAL(10,2); - DECLARE vItem INT DEFAULT 98; - DECLARE vItemCarryBox INT; - - SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox - INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox - FROM bionicConfig; - - SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; - - -- Creamos la tabla tmp.bionicComponent - DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; - CREATE TEMPORARY TABLE tmp.bionicComponent( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `componentFk` int(10) unsigned NOT NULL, - `value` decimal(10,4) NOT NULL, - UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, - KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE - ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; - - -- Margin - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, id, vMargin - FROM component - WHERE code = vComponentMargin; - - -- Recobro - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) - FROM bi.claims_ratio cr - JOIN component c ON c.code = vComponentRecovery - WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; - - -- Componente de maná automático, en función del maná acumulado por el comercial. - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) - FROM client c - JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador - JOIN component co ON co.code = vComponentMana - WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; - - -- Reparto - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient - * ROUND( - vM3 - * az.price - * az.inflation - / vVerdnaturaVolumeBox, 4 - ) - FROM agencyMode ag - JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode - JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk - AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk - JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode - AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse - JOIN component co ON co.code = vComponentPort; - - -- Coste - SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue - FROM tmp.bionicComponent; - - INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) - SELECT vWarehouse, vItem, id,vComponentCostValue - FROM component - WHERE code = vComponentCost; - - RETURN vComponentCostValue; -END$$ - -DELIMITER ; - diff --git a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql b/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql deleted file mode 100644 index 97249bd8a..000000000 --- a/db/changes/10110-postCampaign/01-ticketBusinessCalculate.sql +++ /dev/null @@ -1,96 +0,0 @@ - -DROP procedure IF EXISTS `vn`.`timeBusiness_calculate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) -BEGIN - -/** - * Horas que debe trabajar un empleado según contrato y día. - * @param vDatedFrom workerTimeControl - * @param vDatedTo workerTimeControl - * @table tmp.user(userFk) - * @return tmp.timeBusinessCalculate - */ - DECLARE vHoursFullTime INT DEFAULT 40; - - DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; - DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; - - CALL rangeDateInfo(vDatedFrom, vDatedTo); - - CREATE TEMPORARY TABLE tmp.timeBusinessCalculate - SELECT dated, - businessFk, - userFk, - departmentFk, - hourStart, - hourEnd, - timeWorkSeconds, - SEC_TO_TIME(timeWorkSeconds) timeWorkSexagesimal, - timeWorkSeconds / 3600 timeWorkDecimal, - timeWorkSeconds timeBusinessSeconds, - SEC_TO_TIME(timeWorkSeconds) timeBusinessSexagesimal, - timeWorkSeconds / 3600 timeBusinessDecimal, - type, - permissionrate, - hoursWeek - FROM(SELECT rd.dated, - b.business_id businessFk, - w.userFk, - bl.department_id departmentFk, - IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.start,2) ORDER BY j.start ASC SEPARATOR '-')) hourStart , - IF(cl.hours_week = vHoursFullTime, NULL, GROUP_CONCAT(DISTINCT LEFT(j.end,2) ORDER BY j.end ASC SEPARATOR '-')) hourEnd, - IF(cl.hours_week = vHoursFullTime, 0, IFNULL(SUM(TIME_TO_SEC(j.end)) - SUM(TIME_TO_SEC(j.start)),0)) timeWorkSeconds, - cs.type, - cs.permissionRate, - cl.hours_week hoursWeek - FROM tmp.rangeDate rd - LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) - LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id - LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id - LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id - JOIN tmp.`user` u ON u.userFK = w.userFK - JOIN postgresql.business_labour AS bl ON b.business_id = bl.business_id - LEFT JOIN postgresql.business_labour_payroll AS bp ON bl.business_id = bp.business_id - LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id - LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id - LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id - LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 - LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated - LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id - WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo - GROUP BY w.userFk,dated - )sub; - - - UPDATE tmp.timeBusinessCalculate t - SET t.timeWorkSeconds = vHoursFullTime / 5 * 3600, - t.timeWorkSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), - t.timeWorkDecimal = vHoursFullTime / 5, - t.timeBusinessSeconds = vHoursFullTime / 5 * 3600, - t.timeBusinessSexagesimal = SEC_TO_TIME( vHoursFullTime / 5 * 3600), - t.timeBusinessDecimal = vHoursFullTime / 5 - WHERE DAYOFWEEK(t.dated) IN(2,3,4,5,6) AND hoursWeek = vHoursFullTime ; - - UPDATE tmp.timeBusinessCalculate t - SET t.timeWorkSeconds = t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate) , - t.timeWorkSexagesimal = SEC_TO_TIME(t.timeWorkSeconds - (t.timeWorkSeconds * permissionrate)), - t.timeWorkDecimal = t.timeWorkDecimal - (t.timeWorkDecimal * permissionrate) - WHERE permissionrate <> 0; - - UPDATE tmp.timeBusinessCalculate t - JOIN postgresql.calendar_labour cl ON cl.day = t.dated - JOIN postgresql.business_labour bl ON bl.business_id = t.businessFk AND bl.workcenter_id = cl.workcenter_id - SET t.timeWorkSeconds = 0, - t.timeWorkSexagesimal = 0, - t.timeWorkDecimal = 0, - t.permissionrate = 1, - t.type = 'Festivo' - WHERE t.type IS NULL; - -DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; -END$$ - -DELIMITER ; - diff --git a/db/changes/10120-december/00-entryBeforeUpdate.sql b/db/changes/10120-december/00-entryBeforeUpdate.sql deleted file mode 100644 index 088ea9328..000000000 --- a/db/changes/10120-december/00-entryBeforeUpdate.sql +++ /dev/null @@ -1,58 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`entry_beforeUpdate`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`entry_beforeUpdate` - BEFORE UPDATE ON `entry` - FOR EACH ROW -BEGIN - DECLARE vIsVirtual BOOL; - DECLARE vPrintedCount INT; - DECLARE vHasDistinctWarehouses BOOL; - - IF !(NEW.travelFk <=> OLD.travelFk) THEN - SELECT COUNT(*) > 0 INTO vIsVirtual - FROM entryVirtual WHERE entryFk = NEW.id; - - SELECT !(o.warehouseInFk <=> n.warehouseInFk) - OR !(o.warehouseOutFk <=> n.warehouseOutFk) - INTO vHasDistinctWarehouses - FROM travel o, travel n - WHERE o.id = OLD.travelFk - AND n.id = NEW.travelFk; - - IF vIsVirtual AND vHasDistinctWarehouses THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; - END IF; - - IF NEW.travelFk IS NULL THEN - SELECT COUNT(*) INTO vPrintedCount - FROM buy - WHERE entryFk = OLD.id - AND printedStickers > 0; - - IF vPrintedCount > 0 THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'An entry that contains lines with printed labels cannot be deleted'; - END IF; - END IF; - END IF; - - IF !(NEW.supplierFk <=> OLD.supplierFk) THEN - SET NEW.currencyFk = entry_getCurrency(NEW.currencyFk, NEW.supplierFk); - END IF; - - IF !(NEW.travelFk <=> OLD.travelFk) - OR !(NEW.currencyFk <=> OLD.currencyFk) THEN - SET NEW.commission = entry_getCommission(NEW.travelFk, NEW.currencyFk,NEW.supplierFk); - END IF; - - IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN - INSERT INTO entryLog SET - action = 'update', - description = 'Cambia a Contabilizada', - userFk = myWorker_getId(), - originFk = NEW.id; - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10120-december/00-expedition_beforeInsert.sql b/db/changes/10120-december/00-expedition_beforeInsert.sql deleted file mode 100644 index 819cd7a7f..000000000 --- a/db/changes/10120-december/00-expedition_beforeInsert.sql +++ /dev/null @@ -1,33 +0,0 @@ -DROP TRIGGER IF EXISTS `vn`.`expedition_beforeInsert`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` TRIGGER `vn`.`expedition_beforeInsert` - BEFORE INSERT ON `expedition` FOR EACH ROW -BEGIN - DECLARE intcounter INT; - DECLARE vShipFk INT; - - IF NEW.isBox > 0 THEN - - UPDATE ticket SET packages = nz(packages) + 1 WHERE id = NEW.ticketFk; - - SELECT IFNULL(MAX(counter),0) +1 INTO intcounter - FROM expedition e - INNER JOIN ticket t1 ON e.ticketFk = t1.id - LEFT JOIN ticketState ts ON ts.ticket = t1.id - INNER JOIN ticket t2 ON t2.addressFk = t1.addressFk AND DATE(t2.shipped) = DATE(t1.shipped) - AND t1.warehouseFk = t2.warehouseFk - WHERE t2.id = NEW.ticketFk AND ts.alertLevel < 3 AND t1.companyFk = t2.companyFk - AND t1.agencyModeFk = t2.agencyModeFk; - - SET NEW.`counter` = intcounter; - END IF; - - SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; - - IF vShipFk THEN - CALL stowaway_unboarding(vShipFk, NEW.ticketFk); - END IF; -END$$ -DELIMITER ; diff --git a/db/changes/10120-december/00-stowaway_unboarding.sql b/db/changes/10120-december/00-stowaway_unboarding.sql deleted file mode 100644 index 271baba6c..000000000 --- a/db/changes/10120-december/00-stowaway_unboarding.sql +++ /dev/null @@ -1,31 +0,0 @@ - -USE `vn`; -DROP procedure IF EXISTS `vn`.`stowawayUnBoarding`; - -DELIMITER $$ -USE `vn`$$ -CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) -BEGIN - DECLARE vWorker VARCHAR(255); - - DELETE FROM stowaway - WHERE shipFk = vShipFk AND id = vStowawayFk; - - DELETE tt FROM ticketTracking tt - JOIN state s ON s.id = tt.stateFk - WHERE code = 'BOARDING' AND ticketFk = vShipFk; - - DELETE FROM sale - WHERE ticketFk = vShipFk - AND itemFk = 98 - AND concept = CONCAT('POLIZÓN! ',vStowawayFk); - - SELECT u.`name` INTO vWorker - FROM account.user u JOIN worker w ON w.userFk = u.id - WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); - - SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; -END$$ - -DELIMITER ; -; diff --git a/db/changes/10120-december/00-tpvTransaction.sql b/db/changes/10120-december/00-tpvTransaction.sql deleted file mode 100644 index 10ec8082c..000000000 --- a/db/changes/10120-december/00-tpvTransaction.sql +++ /dev/null @@ -1,120 +0,0 @@ - -DROP procedure IF EXISTS `hedera`.`tpvTransaction_confirm`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_confirm`( - vAmount INT - ,vOrder INT - ,vMerchant INT - ,vCurrency INT - ,vResponse INT - ,vErrorCode VARCHAR(10) -) -BEGIN -/** - * Confirma una transacción previamente iniciada, reescribiendo - * sus datos por los confirmados por el banco (solo si estos difieren). - * Genera el recibo y su correspondiente entrada en caja. - * - * @param vAmount Cantidad confirmada - * @param vOrder Identificador de transacción - * @param vMerchant Identificador de comercio - * @param vCurrency Identificador de moneda - * @param vResponse Identificador de respuesta del banco - * @param vErrorCode Código de error del banco, si lo hubiera - */ - DECLARE vReceipt INT; - DECLARE vStatus VARCHAR(10); - DECLARE vCustomer INT; - DECLARE vBank INT; - DECLARE vCompany INT; - DECLARE vEmployee INT; - DECLARE vIsDuplicated BOOLEAN; - DECLARE vDate DATE; - DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web'; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT COUNT(*) > 0 INTO vIsDuplicated - FROM tpvTransaction - WHERE id = vOrder AND response IS NOT NULL - FOR UPDATE; - - IF vIsDuplicated - THEN - CALL util.throw ('TRANSACTION_DUPLICATED'); - END IF; - - IF vResponse BETWEEN 0 AND 99 - THEN - SELECT - t.clientFk - ,m.bankFk - ,m.companyFk - ,c.employeeFk - ,DATE(t.created) - INTO - vCustomer - ,vBank - ,vCompany - ,vEmployee - ,vDate - FROM tpvMerchant m - JOIN tpvConfig c - LEFT JOIN tpvTransaction t ON t.id = vOrder - WHERE m.id = vMerchant; - - INSERT INTO vn.receipt - SET - amountPaid = vAmount / 100 - ,payed = vDate - ,workerFk = vEmployee - ,bankFk = vBank - ,clientFk = vCustomer - ,companyFk = vCompany - ,invoiceFk = vConcept - ,isConciliate = TRUE; - - SET vReceipt = LAST_INSERT_ID(); - SET vStatus = 'ok'; - - -- Código redundante - - DO vn.till_new - ( - vCustomer - ,vBank - ,vAmount / 100 - ,vConcept - ,vDate - ,'A' - ,TRUE - ,vCustomer - ,vCompany - ,vEmployee - ); - ELSE - SET vReceipt = NULL; - SET vStatus = 'ko'; - END IF; - - UPDATE tpvTransaction - SET - merchantFk = vMerchant - ,receiptFk = vReceipt - ,amount = vAmount - ,response = vResponse - ,errorCode = vErrorCode - ,status = vStatus - WHERE id = vOrder; - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/changes/10120-december/00-tpvTransaction_undo.sql b/db/changes/10120-december/00-tpvTransaction_undo.sql deleted file mode 100644 index ee7bcc5d1..000000000 --- a/db/changes/10120-december/00-tpvTransaction_undo.sql +++ /dev/null @@ -1,86 +0,0 @@ - -DROP procedure IF EXISTS `hedera`.`tpvTransaction_undo`; - -DELIMITER $$ -CREATE DEFINER=`root`@`%` PROCEDURE `hedera`.`tpvTransaction_undo`(vSelf INT) -BEGIN - DECLARE vCustomer INT; - DECLARE vAmount DOUBLE; - DECLARE vReceipt INT; - DECLARE vDate DATE; - DECLARE vBank INT; - DECLARE vAccount VARCHAR(12); - DECLARE vSubaccount VARCHAR(12); - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - SELECT - t.clientFk - ,t.amount / 100 - ,t.receiptFk - ,DATE(t.created) - ,m.bankFk - INTO - vCustomer - ,vAmount - ,vReceipt - ,vDate - ,vBank - FROM tpvTransaction t - JOIN tpvMerchant m ON m.id = t.merchantFk - JOIN tpvConfig c - WHERE t.id = vSelf - FOR UPDATE; - - -- Elimina el recibo - - DELETE FROM vn.receipt - WHERE id = vReceipt LIMIT 1; - - -- Elimina la entrada de cajas - - DELETE FROM vn.till - WHERE bankFk = vBank - AND DATE(dated) = vDate - AND `in` = vAmount - LIMIT 1; - - -- Elimina los asientos contables - - SELECT accountingAccount INTO vSubaccount - FROM vn.`client` WHERE id = vCustomer; - - SELECT account INTO vAccount - FROM vn.bank WHERE id = vBank; - - DELETE FROM vn.XDiario - WHERE SUBCTA = vSubaccount - AND CONTRA = vAccount - AND DATE(FECHA) = vDate - AND EUROHABER = vAmount - LIMIT 1; - - DELETE FROM vn.XDiario - WHERE CONTRA = vSubaccount - AND SUBCTA = vAccount - AND DATE(FECHA) = vDate - AND EURODEBE = vAmount - LIMIT 1; - - -- Actualiza la transaccion - - UPDATE tpvTransaction - SET response = NULL, status = 'started' - WHERE id = vSelf; - - COMMIT; -END$$ - -DELIMITER ; - diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 05171dbfa..687f05518 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -23,7 +23,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10080',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10120',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -36,7 +36,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `account`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -94,7 +94,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `salix`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -119,7 +119,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','WRITE','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -142,7 +142,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `vn`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -287,7 +287,7 @@ UNLOCK TABLES; LOCK TABLES `state` WRITE; /*!40000 ALTER TABLE `state` DISABLE KEYS */; -INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0),(3,'OK',3,0,'OK',3,28,1,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1),(9,'Encajando',9,1,'PACKING',NULL,9,0,1),(10,'Encajado',10,2,'PACKED',NULL,10,0,1),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0),(2,'Libre',1,0,'FREE',NULL,2,0,0,0),(3,'OK',3,0,'OK',3,28,1,0,0),(4,'Impreso',4,1,'PRINTED',2,29,1,0,1),(5,'Preparación',5,1,'ON_PREPARATION',7,5,0,0,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0),(7,'Sin Acabar',2,0,'NOT_READY',NULL,7,0,0,0),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0),(9,'Encajando',9,1,'PACKING',NULL,9,0,1,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0),(11,'Facturado',0,0,'INVOICED',NULL,11,0,1,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0),(17,'Eliminado',14,3,'ERASED',NULL,17,0,0,0),(20,'Asignado',4,1,'PICKER_DESIGNED',NULL,20,1,0,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0),(23,'URGENTE',2,0,'LAST_CALL',NULL,23,1,0,0),(24,'Encadenado',3,0,'CHAINED',4,24,0,0,0),(25,'Embarcando',3,0,'BOARDING',5,25,0,0,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,1,0,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,1,0,1); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -297,7 +297,7 @@ UNLOCK TABLES; LOCK TABLES `sample` WRITE; /*!40000 ALTER TABLE `sample` DISABLE KEYS */; -INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Email de bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Email de instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Email de solicitud de datos bancarios core',1,'1'),(15,'letter-debtor-st','Email de aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Email de aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',1,'1'); +INSERT INTO `sample` VALUES (1,'Carta_1','Aviso inicial por saldo deudor',0,'0'),(2,'Carta_2','Reiteracion de aviso por saldo deudor',0,'0'),(3,'Cred_Up','Notificación de aumento de crédito',0,'0'),(4,'Cred_down','Notificación de reducción de crédito',0,'0'),(5,'Pet_CC','Petición de datos bancarios B2B',0,'0'),(6,'SolCredito','Solicitud de crédito',0,'0'),(7,'LeyPago','Ley de pagos',0,'0'),(8,'Pet_CC_Core','Petición de datos bancarios CORE',0,'0'),(9,'nueva_alta','Documento de nueva alta de cliente',0,'0'),(10,'client_welcome','Email de bienvenida para nuevo cliente',0,'0'),(11,'setup_printer','Email de instalación de impresora',0,'0'),(12,'client-welcome','Bienvenida como nuevo cliente',1,'0'),(13,'printer-setup','Instalación y configuración de impresora de coronas',1,'0'),(14,'sepa-core','Solicitud de domiciliación bancaria',1,'1'),(15,'letter-debtor-st','Aviso inicial por saldo deudor',1,'1'),(16,'letter-debtor-nd','Aviso reiterado por saldo deudor',1,'1'),(17,'client-lcr','Email de solicitud de datos bancarios LCR',0,'1'); /*!40000 ALTER TABLE `sample` ENABLE KEYS */; UNLOCK TABLES; @@ -307,7 +307,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,'VERDNATURA',1,78,763,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(22,'COMPRAS',65,66,NULL,72,596,2,5,0,0,1,0,NULL,NULL),(23,'CAMARA',41,42,NULL,72,604,2,6,1,0,0,0,NULL,NULL),(31,'INFORMATICA',11,12,NULL,72,127,3,9,0,0,0,0,NULL,NULL),(34,'CONTABILIDAD',4,5,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(35,'FINANZAS',6,7,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(36,'LABORAL',8,9,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,0,NULL,NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,0,0,NULL,NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,0,0,NULL,NULL),(41,'ADMINISTRACION',3,10,NULL,72,599,3,8,0,0,0,0,NULL,NULL),(43,'VENTAS',51,64,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(44,'GERENCIA',2,25,NULL,72,300,2,7,0,0,0,0,NULL,NULL),(45,'LOGISTICA',26,37,NULL,72,596,3,19,0,0,0,0,NULL,NULL),(46,'REPARTO',38,39,NULL,72,659,3,10,0,0,0,0,NULL,NULL),(48,'ALMACENAJE',40,47,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(49,'PROPIEDAD',48,75,NULL,72,1008,1,1,0,0,0,0,NULL,NULL),(52,'CARGA AEREA',27,28,NULL,72,163,4,28,0,0,0,0,NULL,NULL),(53,'MARKETING Y COMUNICACIÓN',60,61,NULL,72,1238,0,0,0,0,0,0,NULL,NULL),(54,'ORNAMENTALES',76,77,NULL,72,433,3,21,0,0,0,0,NULL,NULL),(55,'TALLER NATURAL',68,69,NULL,72,695,2,23,0,0,0,0,NULL,NULL),(56,'TALLER ARTIFICIAL',70,71,NULL,72,1780,2,24,0,0,0,0,NULL,NULL),(58,'CAMPOS',73,74,NULL,72,225,2,2,0,0,0,0,NULL,NULL),(59,'MANTENIMIENTO',49,50,NULL,72,1907,4,16,0,0,0,0,NULL,NULL),(60,'RECLAMACIONES',58,59,NULL,72,563,3,20,0,0,0,0,NULL,NULL),(61,'VNH',35,36,NULL,73,1297,3,17,0,0,0,0,NULL,NULL),(63,'VENTAS FRANCIA',62,63,NULL,72,277,2,27,0,0,0,0,NULL,NULL),(66,'VERDNAMADRID',31,32,NULL,72,163,3,18,0,0,0,0,NULL,NULL),(68,'COMPLEMENTOS',43,44,NULL,72,617,3,26,1,0,0,0,NULL,NULL),(69,'VERDNABARNA',33,34,NULL,74,432,3,22,0,0,0,0,NULL,NULL),(77,'PALETIZADO',18,19,NULL,72,230,4,15,1,0,0,0,NULL,NULL),(80,'EQUIPO J VALLES',56,57,NULL,72,693,3,4,0,0,0,0,NULL,NULL),(86,'LIMPIEZA',13,14,NULL,72,599,0,0,0,0,0,0,NULL,NULL),(89,'COORDINACION',16,17,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(90,'TRAILER',29,30,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(91,'ARTIFICIAL',45,46,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,NULL),(92,'EQUIPO SILVERIO',54,55,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(93,'CONFECCION',67,72,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,NULL),(94,'EQUIPO J BROCAL',52,53,NULL,0,NULL,NULL,NULL,0,0,1,0,NULL,NULL); +INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/'),(23,'CAMARA',5,6,NULL,72,604,2,6,1,0,0,0,NULL,'/'),(31,'INFORMATICA',7,8,NULL,72,127,3,9,0,0,0,0,NULL,'/'),(34,'CONTABILIDAD',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(35,'FINANZAS',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(36,'LABORAL',13,14,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(37,'PRODUCCION',15,24,NULL,72,230,3,11,0,0,0,4,NULL,'/'),(38,'SACADO',16,17,NULL,72,230,4,14,1,0,1,0,37,'/37/'),(39,'ENCAJADO',18,19,NULL,72,230,4,12,1,0,1,0,37,'/37/'),(41,'ADMINISTRACION',25,26,NULL,72,599,3,8,0,0,0,0,NULL,'/'),(43,'VENTAS',27,38,NULL,0,NULL,NULL,NULL,0,0,0,5,NULL,'/'),(44,'GERENCIA',39,40,NULL,72,300,2,7,0,0,0,0,NULL,'/'),(45,'LOGISTICA',41,42,NULL,72,596,3,19,0,0,0,0,NULL,'/'),(46,'REPARTO',20,21,NULL,72,659,3,10,0,0,1,0,37,'/37/'),(48,'ALMACENAJE',43,44,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(49,'PROPIEDAD',45,46,NULL,72,1008,1,1,0,0,0,0,NULL,'/'),(52,'CARGA AEREA',47,48,NULL,72,163,4,28,0,0,0,0,NULL,'/'),(53,'MARKETING Y COMUNICACIÓN',49,50,NULL,72,1238,0,0,0,0,0,0,NULL,'/'),(54,'ORNAMENTALES',51,52,NULL,72,433,3,21,0,0,0,0,NULL,'/'),(55,'TALLER NATURAL',53,54,NULL,72,695,2,23,0,0,0,0,NULL,'/'),(56,'TALLER ARTIFICIAL',55,56,NULL,72,1780,2,24,0,0,0,0,NULL,'/'),(58,'CAMPOS',57,58,NULL,72,225,2,2,0,0,0,0,NULL,'/'),(59,'MANTENIMIENTO',59,60,NULL,72,1907,4,16,0,0,0,0,NULL,'/'),(60,'RECLAMACIONES',61,62,NULL,72,563,3,20,0,0,0,0,NULL,'/'),(61,'VNH',63,64,NULL,73,1297,3,17,0,0,0,0,NULL,'/'),(63,'VENTAS FRANCIA',28,29,NULL,72,277,2,27,0,0,1,0,43,'/43/'),(66,'VERDNAMADRID',65,66,NULL,72,163,3,18,0,0,0,0,NULL,'/'),(68,'COMPLEMENTOS',67,68,NULL,72,617,3,26,1,0,0,0,NULL,'/'),(69,'VERDNABARNA',69,70,NULL,74,432,3,22,0,0,0,0,NULL,'/'),(77,'PALETIZADO',22,23,NULL,72,230,4,15,1,0,1,0,37,'/37/'),(80,'EQUIPO J VALLES',30,31,NULL,72,693,3,4,0,0,1,0,43,'/43/'),(86,'LIMPIEZA',71,72,NULL,72,599,0,0,0,0,0,0,NULL,'/'),(89,'COORDINACION',73,74,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/'),(90,'TRAILER',75,76,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(91,'ARTIFICIAL',77,78,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/'),(92,'EQUIPO SILVERIO',32,33,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'),(93,'CONFECCION',79,80,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/'),(94,'EQUIPO J BROCAL',34,35,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'),(95,'EQUIPO C ZAMBRANO',36,37,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/'); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -320,7 +320,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `bi`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -368,7 +368,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:14 USE `cache`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -406,7 +406,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:57 +-- Dump completed on 2019-12-20 11:02:15 USE `hedera`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -464,7 +464,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:58 +-- Dump completed on 2019-12-20 11:02:15 USE `postgresql`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -552,4 +552,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-13 12:42:58 +-- Dump completed on 2019-12-20 11:02:15 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index c6d7592f9..85d510f28 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -20,6 +20,18 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo VALUES (1.30, 167.00, 138000, 71); +INSERT INTO `vn`.`chatConfig` (`uri`) + VALUES + ('https://chat.verdnatura.es/api/v1'); + +INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) + VALUES + ('1', '11'); + +INSERT INTO `vn`.`packagingConfig`(`upperGap`) + VALUES + ('10'); + UPDATE `account`.`role` SET id = 100 WHERE id = 0; INSERT INTO `account`.`user`(`id`,`name`, `nickname`, `password`,`role`,`active`,`email`, `lang`) @@ -1914,6 +1926,11 @@ INSERT INTO `vn`.`queuePriority`(`id`, `priority`) (2, 'Normal'), (3, 'Baja'); +INSERT INTO `vn`.`userPhoneType` (`code`, `description`) + VALUES + ('businessPhone', 'Telefono de empresa del usuario'), + ('personalPhone', 'Telefono personal del usuario'); + INSERT INTO `vn`.`userPhone`(`id`, `userFk`, `typeFk`, `phone`) VALUES (1, 101, 'personalPhone', 1111111111), diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 3554c9db6..901153a58 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -2919,55 +2919,55 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - tp.Tipo AS Familia, - r.reino AS Reino, - tr.CodigoTrabajador AS Comercial, - tr2.CodigoTrabajador AS Comprador, - p.name AS Provincia, - w.name AS almacen, - tm.year AS Año, - tm.month AS Mes, - tm.week AS Semana, - v.vista AS Vista, - bt.importe AS Importe - FROM bs.ventas bt - LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador - LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador - JOIN vn2008.time tm ON tm.date = bt.fecha - JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento - LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista - LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - LEFT JOIN vn2008.province p ON p.province_id = cs.province_id - LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE bt.fecha >= vLastMonth AND r.mercancia; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + tp.Tipo AS Familia, + r.reino AS Reino, + tr.CodigoTrabajador AS Comercial, + tr2.CodigoTrabajador AS Comprador, + p.name AS Provincia, + w.name AS almacen, + tm.year AS Año, + tm.month AS Mes, + tm.week AS Semana, + v.vista AS Vista, + bt.importe AS Importe + FROM bs.ventas bt + LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador + LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador + JOIN vn2008.time tm ON tm.date = bt.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento + LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista + LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna + LEFT JOIN vn2008.province p ON p.province_id = cs.province_id + LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE bt.fecha >= vLastMonth AND r.mercancia; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2985,33 +2985,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `call_add`() -BEGIN - DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; - - -- Seleccionamos la ultima fecha introducida - SELECT MAX(Fecha) INTO datSTART FROM `call`; - - -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos - DELETE FROM `call` WHERE Fecha = datSTART; - - INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) - SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, - dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone - FROM ( - SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, - hour(calldate) as Hora,src as phone - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') - WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration - UNION ALL - SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.src = T.extension - WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration - ) ll - JOIN vn2008.Permisos USING(Id_Trabajador) - LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone - WHERE Id_Grupo = 6; +BEGIN + DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; + + -- Seleccionamos la ultima fecha introducida + SELECT MAX(Fecha) INTO datSTART FROM `call`; + + -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos + DELETE FROM `call` WHERE Fecha = datSTART; + + INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) + SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, + dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone + FROM ( + SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, + hour(calldate) as Hora,src as phone + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') + WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration + UNION ALL + SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.src = T.extension + WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration + ) ll + JOIN vn2008.Permisos USING(Id_Trabajador) + LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone + WHERE Id_Grupo = 6; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3029,205 +3029,205 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 - */ - - -- descuentos comerciales COD 11 - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) - SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * - Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01' - HAVING nz(Importe) <> 0; - - DELETE mc.* - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - UPDATE vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - SET Concepte = CONCAT('$ ',Concepte) - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01'; - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe, Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim ',cm.id,' : ', m.Concepte) - ,round( -1 * ((sensib -1)/4) * Cantidad * - Preu * (100 - Descuento) / 100, 2) AS Reclamaciones - , 4 - , m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe , Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim_mana ',cm.id,' : ', m.Concepte) - ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) - AS Reclamaciones - ,3 - ,m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3 - AND cm.mana; - - -- Marcamos para no repetir - UPDATE vn2008.cl_act ca - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - SET greuge = 1 - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.Id_Ticket - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN vn2008.state s ON s.id = i.state_id - WHERE mc.Id_Componente = 17 - AND mc.greuge = 0 - AND t.Fecha >= '2016-10-01' - AND t.Fecha < CURDATE() - AND s.alert_level >= 3; - - DELETE g.* - FROM vn2008.Greuges g - JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket - WHERE Greuges_type_id = 2; - - INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, - Greuges_type_id, Id_Ticket) - SELECT Id_Cliente - ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) - AS dif - ,date(t.Fecha) - , 2 - ,tt.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc - ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 - GROUP BY t.Id_Ticket - HAVING ABS(dif) > 1; - - UPDATE vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket - SET greuge = 1 - WHERE Id_Componente = 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_Cliente, 0,0,0,0 - FROM vn2008.Clientes; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * - Cantidad * Preu * (100 - Descuento) / 100)) - AS Reclamaciones - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca - ON ca.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND cm.cl_est_id = 3 - AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) - GROUP BY cm.Id_Cliente - ) claims ON claims.Id_Cliente = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge - FROM vn2008.Greuges - WHERE Fecha <= CURDATE() - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(nz(Greuge) / - (nz(Consumo) * vMonthToRefund / 12 ) ,3)); - - -- 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,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 +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 + */ + + -- descuentos comerciales COD 11 + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) + SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * + Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01' + HAVING nz(Importe) <> 0; + + DELETE mc.* + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) + SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + UPDATE vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + SET Concepte = CONCAT('$ ',Concepte) + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01'; + + -- Reclamaciones demasiado sensibles + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe, Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim ',cm.id,' : ', m.Concepte) + ,round( -1 * ((sensib -1)/4) * Cantidad * + Preu * (100 - Descuento) / 100, 2) AS Reclamaciones + , 4 + , m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Reclamaciones que pasan a Maná + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe , Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim_mana ',cm.id,' : ', m.Concepte) + ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) + AS Reclamaciones + ,3 + ,m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3 + AND cm.mana; + + -- Marcamos para no repetir + UPDATE vn2008.cl_act ca + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + SET greuge = 1 + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Recobros + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT DISTINCT t.Id_Ticket + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket + JOIN vncontrol.inter i ON i.inter_id = ts.inter_id + JOIN vn2008.state s ON s.id = i.state_id + WHERE mc.Id_Componente = 17 + AND mc.greuge = 0 + AND t.Fecha >= '2016-10-01' + AND t.Fecha < CURDATE() + AND s.alert_level >= 3; + + DELETE g.* + FROM vn2008.Greuges g + JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket + WHERE Greuges_type_id = 2; + + INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, + Greuges_type_id, Id_Ticket) + SELECT Id_Cliente + ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) + AS dif + ,date(t.Fecha) + , 2 + ,tt.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc + ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 + GROUP BY t.Id_Ticket + HAVING ABS(dif) > 1; + + UPDATE vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket + SET greuge = 1 + WHERE Id_Componente = 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_Cliente, 0,0,0,0 + FROM vn2008.Clientes; + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, + round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 + FROM bi.facturacion_media_anual fm + LEFT JOIN( + SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * + Cantidad * Preu * (100 - Descuento) / 100)) + AS Reclamaciones + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca + ON ca.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND cm.cl_est_id = 3 + AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) + GROUP BY cm.Id_Cliente + ) claims ON claims.Id_Cliente = fm.Id_Cliente; + + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE bi.claims_ratio cr + JOIN ( + SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge + FROM vn2008.Greuges + WHERE Fecha <= CURDATE() + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = cr.Id_Cliente + SET recobro = GREATEST(0,round(nz(Greuge) / + (nz(Consumo) * vMonthToRefund / 12 ) ,3)); + + -- 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,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); + 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 */ ; @@ -3245,23 +3245,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); - - -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); + + -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3739,18 +3739,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bi.facturacion_media_anual; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bi.facturacion_media_anual; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3870,116 +3870,116 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`() -BEGIN -/* - Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, - así como las ventas acumuladas en los ultimos 365 dias, para poder controlar - su evolucion. -*/ - DECLARE datFEC DATE; - DECLARE datFEC_TOMORROW DATE; - DECLARE datFEC_LASTYEAR DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - - END; - - SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; +BEGIN +/* + Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, + así como las ventas acumuladas en los ultimos 365 dias, para poder controlar + su evolucion. +*/ + DECLARE datFEC DATE; + DECLARE datFEC_TOMORROW DATE; + DECLARE datFEC_LASTYEAR DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + + END; + + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,CURDATE()); - - SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), - TIMESTAMPADD(DAY,2,MAX(Fecha)) - INTO datFEC, - datFEC_TOMORROW - FROM bi.Greuge_Evolution; - - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; - - CREATE TEMPORARY TABLE maxInvoice - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha - FROM vn2008.Facturas - GROUP BY Id_Cliente - HAVING maxFecha < timestampadd(month,-2,datFEC); - - WHILE datFEC < CURDATE() DO - - REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) - - SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 - FROM ( - SELECT Id_Cliente, sum(Importe) as Greuge - FROM vn2008.Greuges - where Fecha <= datFEC - group by Id_Cliente - ) sub - RIGHT JOIN - - ( - - SELECT Id_Cliente, sum(Ventas) as Ventas - FROM - ( - - SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas - FROM bs.ventas - WHERE fecha = datFEC or fecha = datFEC_LASTYEAR - - UNION ALL - - SELECT Id_Cliente, Ventas - FROM bi.Greuge_Evolution - WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) - - ) sub - group by Id_Cliente - - ) v using(Id_Cliente) - ; - - -- Ahora calcularemos el greuge muerto - - UPDATE bi.Greuge_Evolution ge - JOIN maxInvoice m using(Id_Cliente) - SET FOSIL = GREUGE - WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); - - -- Recobro - - UPDATE bi.Greuge_Evolution ge - JOIN ( - SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE t.Fecha >= datFEC - AND t.Fecha < datFEC_TOMORROW - AND mc.Id_Componente = 17 -- Recobro - GROUP BY cs.Id_Cliente - ) sub using(Id_Cliente) - SET Recobro = Importe - WHERE ge.Fecha = datFEC; - - SET datFEC = datFEC_TOMORROW; - SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - - END WHILE; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), + TIMESTAMPADD(DAY,2,MAX(Fecha)) + INTO datFEC, + datFEC_TOMORROW + FROM bi.Greuge_Evolution; + + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + CREATE TEMPORARY TABLE maxInvoice + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha + FROM vn2008.Facturas + GROUP BY Id_Cliente + HAVING maxFecha < timestampadd(month,-2,datFEC); + + WHILE datFEC < CURDATE() DO + + REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) + + SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 + FROM ( + SELECT Id_Cliente, sum(Importe) as Greuge + FROM vn2008.Greuges + where Fecha <= datFEC + group by Id_Cliente + ) sub + RIGHT JOIN + + ( + + SELECT Id_Cliente, sum(Ventas) as Ventas + FROM + ( + + SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas + FROM bs.ventas + WHERE fecha = datFEC or fecha = datFEC_LASTYEAR + + UNION ALL + + SELECT Id_Cliente, Ventas + FROM bi.Greuge_Evolution + WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) + + ) sub + group by Id_Cliente + + ) v using(Id_Cliente) + ; + + -- Ahora calcularemos el greuge muerto + + UPDATE bi.Greuge_Evolution ge + JOIN maxInvoice m using(Id_Cliente) + SET FOSIL = GREUGE + WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); + + -- Recobro + + UPDATE bi.Greuge_Evolution ge + JOIN ( + SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE t.Fecha >= datFEC + AND t.Fecha < datFEC_TOMORROW + AND mc.Id_Componente = 17 -- Recobro + GROUP BY cs.Id_Cliente + ) sub using(Id_Cliente) + SET Recobro = Importe + WHERE ge.Fecha = datFEC; + + SET datFEC = datFEC_TOMORROW; + SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4063,10 +4063,10 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`() -BEGIN - CALL analisis_ventas_update; - CALL analisis_ventas_simple; - CALL analisis_ventas_evolution_add; +BEGIN + CALL analisis_ventas_update; + CALL analisis_ventas_simple; + CALL analisis_ventas_evolution_add; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5518,6 +5518,10 @@ CREATE TABLE `vendedores` ( `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', `comisionNuevos` decimal(10,2) DEFAULT NULL, + `sustitucionArrendada` decimal(10,2) DEFAULT NULL, + `sustitucionCedida` decimal(10,2) DEFAULT NULL, + `itemTypeLended` decimal(10,2) DEFAULT NULL, + `itemTypeBorrowed` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -6808,16 +6812,16 @@ BEGIN * La tabla mana_spellers es una caché * */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - + + UPDATE mana_spellers me + JOIN + (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual + FROM bs.vendedores + WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) + GROUP BY Id_Trabajador + ) lastYearSales USING(Id_Trabajador) + SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8859,9 +8863,9 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - DELETE FROM cache_calc WHERE expires < vCleanTime; +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8879,27 +8883,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8917,88 +8921,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires - INTO v_cache_id, v_calc, v_expires - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires + INTO v_cache_id, v_calc, v_expires + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9016,24 +9020,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - DELETE FROM cache_calc WHERE id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + DELETE FROM cache_calc WHERE id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9052,9 +9056,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() NO SQL -BEGIN - CALL available_clean; - CALL visible_clean; +BEGIN + CALL available_clean; + CALL visible_clean; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9072,13 +9076,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10542,158 +10546,158 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - DECLARE vForceToPacking INT DEFAULT 2; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM ekt e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vSelf; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - ELSE - INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) - SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) - FROM bucket WHERE bucket_id = vPackage; - - IF ROW_COUNT() > 0 - THEN - INSERT INTO vn2008.mail SET - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vSelf - AND l.id != vSelf - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vSelf; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,`grouping` - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vSelf - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.`grouping`, e.pac) - ,vForceToPacking - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vSelf - LIMIT 1; +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10743,154 +10747,154 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` INT) -BEGIN +BEGIN /** * Adds a new exchange, generates it's barcode and * inserts/updates the transaction. When the referenced * transaction exists as provisional, updates it with - * the new values. - */ - DECLARE vEkt INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOL; + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; - DECLARE duplicateKey CONDITION FOR 1062; - - DECLARE CONTINUE HANDLER FOR duplicateKey - SET vIsDuplicated = TRUE; - - -- Generates the barcode - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Rewrites the kop parameter - - IF vKop IS NULL THEN - SELECT defaultKop INTO vKop FROM exchangeConfig; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mailSender e - JOIN mail m ON m.senderFk = e.id - WHERE m.id = vMailFk; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserts the new transaction + DECLARE duplicateKey CONDITION FOR 1062; - SET vIsDuplicated = FALSE; - INSERT INTO ekt SET - barcode = IFNULL(vBarcode, barcode) - ,deliveryNumber = vDeliveryNumber - ,entryYear = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk; - - -- If it exists duplicado updates it - - IF NOT vIsDuplicated - THEN - SET vEkt = LAST_INSERT_ID(); - CALL ekt_load (vEkt); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEkt - FROM ekt - WHERE deliveryNumber = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM ekt t - JOIN `exchange` b ON b.ektFk = t.id - JOIN exchangeConfig c - WHERE t.deliveryNumber = vDeliveryNumber - AND t.entryYear = YEAR(vDate) - AND b.typeFk != c.presaleFk; - END IF; - - IF vUpdateExistent - THEN - UPDATE ekt SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk - WHERE id = vEkt; - END IF; - - -- Registers the exchange - - INSERT INTO `exchange` SET - mailFk = vMailFk - ,typeFk = vType - ,ektFk = vEkt; + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction + + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12966,30 +12970,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -14242,9 +14246,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -14288,9 +14292,9 @@ BEGIN GROUP BY r.warehouse_id; DECLARE cRows CURSOR FOR - SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate + SELECT r.id, r.item_id, i.name, r.amount, r.price, r.rate FROM order_row r - JOIN vn2008.Articles a ON a.Id_Article = r.item_id + JOIN vn.item i ON i.id = r.item_id WHERE r.amount != 0 AND r.warehouse_id = vWarehouse AND r.order_id = vOrder @@ -14308,12 +14312,12 @@ BEGIN -- Carga los datos del pedido SELECT o.date_send, o.address_id, o.note, - o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id + o.confirmed, a.clientFk, o.company_id, o.agency_id INTO vDelivery, vAddress, vNotes, vIsConfirmed, vClientId, vCompanyId, vAgencyModeId FROM hedera.`order` o - JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id - WHERE id = vOrder; + JOIN vn.address a ON a.id = o.address_id + WHERE o.id = vOrder; -- Comprueba que el pedido no está confirmado @@ -14332,7 +14336,7 @@ BEGIN -- Carga las fechas de salida de cada almacén - CALL vn.zoneGetShippedWarehouse (vDelivery, vAddress, vAgencyModeId); + CALL vn.zone_getShippedWarehouse (vDelivery, vAddress, vAgencyModeId); -- Trabajador que realiza la acción @@ -14358,19 +14362,18 @@ BEGIN -- Busca un ticket existente que coincida con los parametros - SELECT Id_Ticket INTO vTicket - FROM vn2008.Tickets t - LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket + SELECT t.id INTO vTicket + FROM vn.ticket t + LEFT JOIN vn.ticketState tls on tls.ticket = t.id JOIN `order` o - ON o.address_id = t.Id_Consigna - AND vWarehouse = t.warehouse_id - AND o.agency_id = t.Id_Agencia - AND t.landing = o.date_send - AND vShipment = DATE(t.Fecha) + ON o.address_id = t.addressFk + AND vWarehouse = t.warehouseFk + AND o.agency_id = t.agencyModeFk + AND o.date_send = t.landed + AND vShipment = DATE(t.shipped) WHERE o.id = vOrder - AND t.Factura IS NULL + AND t.invoiceOutFk IS NULL AND IFNULL(tls.alertLevel,0) = 0 - AND t.Id_Cliente <> 1118 LIMIT 1; -- Crea el ticket en el caso de no existir uno adecuado @@ -14392,23 +14395,24 @@ BEGIN ELSE INSERT INTO vncontrol.inter SET Id_Ticket = vTicket, + Id_Trabajador = vUserId, state_id = TICKET_FREE; END IF; - INSERT IGNORE INTO vn2008.order_Tickets - SET order_id = vOrder, - Id_Ticket = vTicket; + INSERT IGNORE INTO vn.orderTicket + SET orderFk = vOrder, + ticketFk = vTicket; -- Añade las notas IF vNotes IS NOT NULL AND vNotes != '' THEN - INSERT INTO vn2008.ticket_observation SET - Id_Ticket = vTicket, - observation_type_id = 4 /* salesperson */ , - `text` = vNotes + INSERT INTO vn.ticketObservation SET + ticketFk = vTicket, + observationTypeFk = 4 /* salesperson */ , + `description` = vNotes ON DUPLICATE KEY UPDATE - `text` = CONCAT(VALUES(`text`),'. ', `text`); + `description` = CONCAT(VALUES(`description`),'. ', `description`); END IF; -- Añade los movimientos y sus componentes @@ -14424,20 +14428,20 @@ BEGIN LEAVE lRows; END IF; - INSERT INTO vn2008.Movimientos + INSERT INTO vn.sale SET - Id_Article = vItem, - Id_Ticket = vTicket, - Concepte = vConcept, - Cantidad = vAmount, - Preu = vPrice, - CostFixat = 0, - PrecioFijado = TRUE; + itemFk = vItem, + ticketFk = vTicket, + concept = vConcept, + quantity = vAmount, + price = vPrice, + priceFixed = 0, + isPriceFixed = TRUE; SET vSale = LAST_INSERT_ID(); - INSERT INTO vn2008.Movimientos_componentes - (Id_Movimiento, Id_Componente, Valor) + INSERT INTO vn.saleComponent + (saleFk, componentFk, `value`) SELECT vSale, cm.component_id, cm.price FROM order_component cm JOIN bi.tarifa_componentes tc @@ -14458,20 +14462,20 @@ BEGIN CREATE TEMPORARY TABLE tComponents (INDEX (saleFk)) ENGINE = MEMORY - SELECT SUM(mc.Valor) valueSum, mc.Id_Movimiento saleFk - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc USING(Id_Componente) + SELECT SUM(sc.`value`) valueSum, sc.saleFk + FROM vn.saleComponent sc + JOIN bi.tarifa_componentes tc ON tc.Id_Componente = sc.componentFk JOIN bi.tarifa_componentes_series tcs ON tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base - JOIN vn2008.Movimientos m - ON m.Id_Movimiento = mc.Id_Movimiento - WHERE m.Id_Ticket = vTicket - GROUP BY mc.Id_Movimiento; + JOIN vn.sale s + ON s.id = sc.saleFk + WHERE s.ticketFk = vTicket + GROUP BY sc.saleFk; - UPDATE vn2008.Movimientos m - JOIN tComponents mc ON mc.saleFk = m.Id_Movimiento - SET m.CostFixat = valueSum; + UPDATE vn.sale s + JOIN tComponents mc ON mc.saleFk = s.id + SET s.priceFixed = valueSum; DROP TEMPORARY TABLE tComponents; END LOOP; @@ -15148,9 +15152,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -15218,7 +15222,7 @@ BEGIN ,vEmployee ,vDate FROM tpvMerchant m - JOIN tpvConfig c ON c.id = 1 + JOIN tpvConfig c LEFT JOIN tpvTransaction t ON t.id = vOrder WHERE m.id = vMerchant; @@ -15238,7 +15242,7 @@ BEGIN -- Código redundante - DO vn2008.till_entry + DO vn.till_new ( vCustomer ,vBank @@ -15265,7 +15269,6 @@ BEGIN ,errorCode = vErrorCode ,status = vStatus WHERE id = vOrder; - COMMIT; END ;; DELIMITER ; @@ -15370,9 +15373,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -15414,33 +15417,33 @@ BEGIN -- Elimina el recibo - DELETE FROM vn2008.Recibos - WHERE Id = vReceipt LIMIT 1; + DELETE FROM vn.receipt + WHERE id = vReceipt LIMIT 1; -- Elimina la entrada de cajas - DELETE FROM vn2008.Cajas - WHERE Id_Banco = vBank - AND DATE(CajaFecha) = vDate - AND Entrada = vAmount + DELETE FROM vn.till + WHERE bankFk = vBank + AND DATE(dated) = vDate + AND `in` = vAmount LIMIT 1; -- Elimina los asientos contables - SELECT Cuenta INTO vSubaccount - FROM vn2008.Clientes WHERE Id_Cliente = vCustomer; + SELECT accountingAccount INTO vSubaccount + FROM vn.`client` WHERE id = vCustomer; - SELECT Cuenta INTO vAccount - FROM vn2008.Bancos WHERE Id_Banco = vBank; + SELECT account INTO vAccount + FROM vn.bank WHERE id = vBank; - DELETE FROM vn2008.XDiario + DELETE FROM vn.XDiario WHERE SUBCTA = vSubaccount AND CONTRA = vAccount AND DATE(FECHA) = vDate AND EUROHABER = vAmount LIMIT 1; - DELETE FROM vn2008.XDiario + DELETE FROM vn.XDiario WHERE CONTRA = vSubaccount AND SUBCTA = vAccount AND DATE(FECHA) = vDate @@ -17897,7 +17900,7 @@ CREATE TABLE `log` ( `tableId` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `tableName` (`tableName`,`tableId`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8; +) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -18292,28 +18295,98 @@ DELIMITER ; /*!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 collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) -proc: BEGIN - -- XXX: Disabled while testing - LEAVE proc; - - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vOldId, - operation = 'delete'; - END IF; - - IF vNewId IS NOT NULL THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vNewId, - operation = 'insert'; - END IF; +proc: BEGIN + -- XXX: Disabled while testing + LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; + 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 DROP PROCEDURE IF EXISTS `log_add_beta` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) +proc: BEGIN + -- XXX: Disabled while testing + DECLARE vLanded DATE; + DECLARE vWarehouseFk INT; + DECLARE vBuyerFk INT; + DECLARE vEntryFk INT; + DECLARE vItemFk INT; + DECLARE vItemName VARCHAR(50); + + -- LEAVE proc; + + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; + END IF; + + IF vTableName = 'buy' THEN + + SELECT IFNULL(tr.landed,'2000-01-01') + INTO vLanded + FROM vn.travel tr + JOIN vn.entry e ON e.travelFk = tr.id + JOIN vn.buy b ON b.entryFk = e.id + JOIN vn.warehouse w ON w.id = tr.warehouseInFk + WHERE b.id = vNewId + AND w.isBuyerToBeEmailed; + + IF vLanded = CURDATE() THEN + + SELECT it.workerFk, b.entryFk, i.id, i.longName + INTO vBuyerFk, vEntryFk, vItemFk, vItemName + FROM vn.itemType it + JOIN vn.item i ON i.typeFk = it.id + JOIN vn.buy b ON b.itemFk = i.id + WHERE b.id = vNewId; + + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E-',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName), + 'Este email se ha generado automáticamente'); + + END IF; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18581,29 +18654,29 @@ CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, ABS(m.quantity) quantity, m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk + m.isPicked OR s.alertLevel > 1 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.itemType tp ON tp.id = i.typeFk WHERE ( - vTableId IS NULL - OR (vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId) - ) - AND t.shipped >= vn.getInventoryDate() + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() AND m.quantity != 0; REPLACE INTO inbound ( @@ -18636,7 +18709,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20955,6 +21028,22 @@ CREATE TABLE `chain` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Grupos de clientes'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `chatConfig` +-- + +DROP TABLE IF EXISTS `chatConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `chatConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `uri` varchar(255) COLLATE utf8_unicode_ci NOT NULL, + `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `password` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `claim` -- @@ -21373,9 +21462,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -21383,9 +21472,7 @@ DELIMITER ;; BEFORE UPDATE ON `client` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE DECLARE vText VARCHAR(255) DEFAULT NULL; - -- Comprueba que el formato de los teléfonos es válido IF !(NEW.phone <=> OLD.phone) THEN @@ -21395,7 +21482,7 @@ BEGIN IF !(NEW.mobile <=> OLD.mobile) THEN CALL pbx.phone_isValid(NEW.mobile); END IF; - + IF !(NEW.fax <=> OLD.fax) THEN CALL pbx.phone_isValid(NEW.fax); END IF; @@ -21416,7 +21503,7 @@ BEGIN IF vText IS NOT NULL THEN - INSERT INTO vn2008.mail(`to`, reply_to, subject, text) + INSERT INTO mail(sender, replyTo, `subject`, body) SELECT CONCAT(IF(ac.id,u.name, 'jgallego'), '@verdnatura.es'), 'administracion@verdnatura.es', @@ -21862,6 +21949,22 @@ SET character_set_client = utf8; 1 AS `level`*/; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `collectionVolumetry` +-- + +DROP TABLE IF EXISTS `collectionVolumetry`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `collectionVolumetry` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `level` int(10) unsigned NOT NULL DEFAULT '0', + `lines` int(10) unsigned NOT NULL DEFAULT '1', + `liters` int(10) unsigned NOT NULL DEFAULT '0', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `company` -- @@ -21931,7 +22034,8 @@ SET character_set_client = utf8; 1 AS `typeFk`, 1 AS `classRate`, 1 AS `tax`, - 1 AS `isRenewable`*/; + 1 AS `isRenewable`, + 1 AS `code`*/; SET character_set_client = @saved_cs_client; -- @@ -22334,21 +22438,20 @@ CREATE TABLE `creditClassification` ( /*!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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditClassification_beforeUpdate` BEFORE UPDATE ON `creditClassification` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE IF NEW.client <> OLD.client THEN CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT'); END IF; IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN - UPDATE vn2008.Clientes c - SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client; + UPDATE `client` c + SET creditInsurance = 0 WHERE c.id = NEW.client; END IF; END */;; DELIMITER ; @@ -22378,17 +22481,16 @@ CREATE TABLE `creditInsurance` ( /*!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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`creditInsurance_afterInsert` AFTER INSERT ON `creditInsurance` FOR EACH ROW BEGIN - -- BERNAT: WORKING IN THIS FILE - UPDATE vn2008.Clientes c - JOIN vn.creditClassification cc ON cc.client = c.Id_Cliente + UPDATE `client` c + JOIN vn.creditClassification cc ON cc.client = c.id SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification; END */;; @@ -22737,13 +22839,18 @@ CREATE TABLE `dms` ( `contentType` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, `file` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `hasFile` tinyint(4) NOT NULL DEFAULT '0', - `workerFk` int(11) NOT NULL, + `workerFk` int(11) DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `warehouseFk` smallint(5) unsigned NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `emp_id` (`companyFk`,`hardCopyNumber`,`warehouseFk`), KEY `trabajador_id` (`workerFk`), - KEY `warehouse_id` (`warehouseFk`) + KEY `warehouse_id` (`warehouseFk`), + KEY `dms_dmsTypeFk_idx` (`dmsTypeFk`), + CONSTRAINT `dms_companyFk` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_dmsTypeFk` FOREIGN KEY (`dmsTypeFk`) REFERENCES `dmsType` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_warehouseFk` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON UPDATE CASCADE, + CONSTRAINT `dms_workerFk` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='document managment system'; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -23117,24 +23224,23 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `entry_beforeUpdate` +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`entry_beforeUpdate` BEFORE UPDATE ON `entry` FOR EACH ROW BEGIN - -- Bernat: working in this file - DECLARE vIsClone BOOL; + DECLARE vIsVirtual BOOL; DECLARE vPrintedCount INT; DECLARE vHasDistinctWarehouses BOOL; IF !(NEW.travelFk <=> OLD.travelFk) THEN - SELECT COUNT(*) > 0 INTO vIsClone - FROM vn2008.Entradas_Auto WHERE Id_Entrada = NEW.id; + SELECT COUNT(*) > 0 INTO vIsVirtual + FROM entryVirtual WHERE entryFk = NEW.id; SELECT !(o.warehouseInFk <=> n.warehouseInFk) OR !(o.warehouseOutFk <=> n.warehouseOutFk) @@ -23143,7 +23249,7 @@ BEGIN WHERE o.id = OLD.travelFk AND n.id = NEW.travelFk; - IF vIsClone AND vHasDistinctWarehouses THEN + IF vIsVirtual AND vHasDistinctWarehouses THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'A cloned entry cannot be moved to a travel with different warehouses'; END IF; @@ -23171,12 +23277,11 @@ BEGIN END IF; IF !(ABS(NEW.isBooked) <=> ABS(OLD.isBooked)) THEN - INSERT INTO vn2008.Entradas_dits SET - idaccion_dits = 105, - Id_Trabajador = myWorker_getId(), - Id_Ticket = NEW.id, - value_old = OLD.isBooked, - value_new = NEW.isBooked; + INSERT INTO entryLog SET + action = 'update', + description = 'Cambia a Contabilizada', + userFk = myWorker_getId(), + originFk = NEW.id; END IF; END */;; DELIMITER ; @@ -23476,7 +23581,6 @@ CREATE TABLE `expedition` ( DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`expedition_beforeInsert` BEFORE INSERT ON `expedition` FOR EACH ROW --- Edit trigger body code below this line. Do not edit lines above this one BEGIN DECLARE intcounter INT; DECLARE vShipFk INT; @@ -23497,11 +23601,10 @@ BEGIN SET NEW.`counter` = intcounter; END IF; - -- JGF 14/01/19 si existe un polizon queda anulado SELECT shipFk INTO vShipFk FROM stowaway WHERE id = NEW.ticketFk; IF vShipFk THEN - CALL stowawayUnBoarding(vShipFk, NEW.ticketFk); + CALL stowaway_unboarding(vShipFk, NEW.ticketFk); END IF; END */;; DELIMITER ; @@ -25902,6 +26005,20 @@ CREATE TABLE `packaging` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `packagingConfig` +-- + +DROP TABLE IF EXISTS `packagingConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `packagingConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `upperGap` int(11) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `parking` -- @@ -25986,6 +26103,7 @@ DROP TABLE IF EXISTS `payMethod`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `payMethod` ( `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, + `code` varchar(50) CHARACTER SET utf8 DEFAULT NULL, `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL, `solution` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, `outstandingDebt` tinyint(3) unsigned zerofill NOT NULL DEFAULT '000', @@ -26422,6 +26540,36 @@ CREATE TABLE `printServerQueue` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `printServerQueue2` +-- + +DROP TABLE IF EXISTS `printServerQueue2`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `printServerQueue2` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `printerFk` tinyint(3) unsigned DEFAULT NULL, + `priorityFk` tinyint(3) unsigned DEFAULT NULL, + `reportFk` tinyint(3) unsigned DEFAULT '0', + `statusFk` tinyint(3) unsigned DEFAULT '1', + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, + `param1` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `workerFk` int(11) DEFAULT '20', + `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `param3` text COLLATE utf8_unicode_ci, + `error` text COLLATE utf8_unicode_ci, + PRIMARY KEY (`id`), + UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`), + KEY `Id_estado` (`statusFk`), + KEY `Id_Impresora` (`printerFk`), + KEY `Id_Informe` (`reportFk`), + KEY `Id_Prioridad` (`priorityFk`), + KEY `Id_Trabajador` (`workerFk`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `printingQueueCheck` -- @@ -26848,11 +26996,14 @@ CREATE TABLE `route` ( `cost` double unsigned DEFAULT NULL, `m3` decimal(10,1) unsigned DEFAULT NULL, `description` text COLLATE utf8_unicode_ci, + `zoneFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `Id_Agencia` (`agencyModeFk`), KEY `Fecha` (`created`), KEY `gestdoc_id` (`gestdocFk`), KEY `route_ibfk_2_idx` (`workerFk`), + KEY `fk_route_1_idx` (`zoneFk`), + CONSTRAINT `fk_route_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON UPDATE CASCADE, CONSTRAINT `route_ibfk_1` FOREIGN KEY (`gestdocFk`) REFERENCES `dms` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, CONSTRAINT `route_ibfk_2` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -27412,6 +27563,7 @@ CREATE TABLE `sector` ( `code` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `pickingPlacement` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, `path` int(11) DEFAULT NULL, + `isPreviousPrepared` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -27768,6 +27920,7 @@ CREATE TABLE `state` ( `nextStateFk` tinyint(4) NOT NULL COMMENT 'Estado al que tiene que cambiar el ticket despues de preparacion previa', `isPreviousPreparable` tinyint(1) NOT NULL DEFAULT '0', `isPicked` tinyint(1) NOT NULL DEFAULT '0', + `isPreparable` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `code_UNIQUE` (`code`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -28674,7 +28827,7 @@ CREATE TABLE `ticketRequest` ( `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `isOk` tinyint(1) DEFAULT NULL, `requesterFk` int(11) DEFAULT NULL, - `atenderFk` int(11) DEFAULT NULL, + `attenderFk` int(11) DEFAULT NULL, `ticketFk` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `Id_Movimiento_UNIQUE` (`saleFk`), @@ -28684,10 +28837,10 @@ CREATE TABLE `ticketRequest` ( KEY `Id_Movimiento` (`saleFk`), KEY `Id_Vendedor` (`salesPersonCode`), KEY `fgnRequester_idx` (`requesterFk`), - KEY `fgnAtender_idx` (`atenderFk`), + KEY `fgnAtender_idx` (`attenderFk`), KEY `fgnTicket_idx` (`ticketFk`), CONSTRAINT `fgbMovimiento` FOREIGN KEY (`saleFk`) REFERENCES `sale` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, - CONSTRAINT `fgnAtender` FOREIGN KEY (`atenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `fgnAtender` FOREIGN KEY (`attenderFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fgnRequester` FOREIGN KEY (`requesterFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `fgnTicket` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -28695,25 +28848,25 @@ CREATE TABLE `ticketRequest` ( /*!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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeInsert` BEFORE INSERT ON `ticketRequest` FOR EACH ROW BEGIN - IF NEW.ticketFk IS NULL THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.requesterFk IS NULL THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; + IF NEW.ticketFk IS NULL THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; - IF NEW.atenderFk IS NULL THEN - SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; + IF NEW.requesterFk IS NULL THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.attenderFk IS NULL THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -28723,25 +28876,25 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`ticketRequest_beforeUpdate` BEFORE UPDATE ON `ticketRequest` FOR EACH ROW BEGIN - IF NEW.saleFk <> OLD.saleFk THEN - SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); - END IF; - - IF NEW.salesPersonCode <> OLD.salesPersonCode THEN - SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); - END IF; + IF NEW.saleFk <> OLD.saleFk THEN + SET NEW.ticketFk = (SELECT s.ticketFk FROM sale s WHERE s.id = NEW.saleFk); + END IF; - IF NEW.buyerCode <> OLD.buyerCode THEN - SET NEW.atenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); - END IF; + IF NEW.salesPersonCode <> OLD.salesPersonCode THEN + SET NEW.requesterFk = (SELECT w.id FROM worker w WHERE w.code = NEW.salesPersonCode); + END IF; + + IF NEW.buyerCode <> OLD.buyerCode THEN + SET NEW.attenderFk = (SELECT w.id FROM worker w WHERE w.code = NEW.buyerCode); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29248,6 +29401,33 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `travelLog` +-- + +DROP TABLE IF EXISTS `travelLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `travelLog` ( + `id` int(11) unsigned NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `travelLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `travel` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `travelLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `travelObservation` -- @@ -29340,6 +29520,67 @@ CREATE TABLE `userConfig` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuración de usuario en Salix'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `userLog` +-- + +DROP TABLE IF EXISTS `userLog`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userLog` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `originFk` int(10) unsigned NOT NULL, + `userFk` int(10) unsigned DEFAULT NULL, + `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, + `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `originFk` (`originFk`), + KEY `userFk` (`userFk`), + CONSTRAINT `userLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `userLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPhone` +-- + +DROP TABLE IF EXISTS `userPhone`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userPhone` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `userFk` int(10) unsigned NOT NULL, + `typeFk` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `phone` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `UserFk_Phone` (`userFk`,`typeFk`,`phone`), + KEY `fgnTypeFk` (`typeFk`), + CONSTRAINT `fgnTypeFk` FOREIGN KEY (`typeFk`) REFERENCES `userPhoneType` (`code`) ON UPDATE CASCADE, + CONSTRAINT `fgnUserFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `userPhoneType` +-- + +DROP TABLE IF EXISTS `userPhoneType`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userPhoneType` ( + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `vehicle` -- @@ -29394,6 +29635,7 @@ CREATE TABLE `warehouse` ( `hasStowaway` tinyint(1) NOT NULL DEFAULT '0', `hasDms` tinyint(1) NOT NULL DEFAULT '0', `pickUpAgencyModeFk` int(11) DEFAULT NULL, + `isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `Id_Paises` (`countryFk`), @@ -30236,7 +30478,7 @@ CREATE TABLE `zone` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, `hour` datetime NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL, + `warehouseFk__` smallint(6) unsigned DEFAULT NULL, `agencyModeFk` int(11) NOT NULL, `travelingDays` int(11) NOT NULL DEFAULT '1', `price` double NOT NULL DEFAULT '0', @@ -30244,10 +30486,10 @@ CREATE TABLE `zone` ( `isVolumetric` tinyint(1) NOT NULL DEFAULT '0', `inflation` decimal(5,2) NOT NULL DEFAULT '1.00', PRIMARY KEY (`id`), - KEY `fk_zone_1_idx` (`warehouseFk`), + KEY `fk_zone_1_idx` (`warehouseFk__`), KEY `fk_zone_2_idx` (`agencyModeFk`), KEY `zone_name_idx` (`name`), - CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, + CONSTRAINT `fk_zone_1` FOREIGN KEY (`warehouseFk__`) REFERENCES `warehouse` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE, CONSTRAINT `fk_zone_2` FOREIGN KEY (`agencyModeFk`) REFERENCES `agencyMode` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDBDEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; @@ -30269,6 +30511,49 @@ CREATE TABLE `zoneCalendar` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `zoneEvent` +-- + +DROP TABLE IF EXISTS `zoneEvent`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneEvent` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `type` enum('day','indefinitely','range') NOT NULL, + `dated` date DEFAULT NULL, + `started` date DEFAULT NULL, + `ended` date DEFAULT NULL, + `weekDays` set('mon','tue','wed','thu','fri','sat','sun') NOT NULL, + `hour` datetime DEFAULT NULL, + `travelingDays` int(11) DEFAULT NULL, + `price` decimal(10,2) DEFAULT NULL, + `bonus` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneEvent_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `zoneExclusion` +-- + +DROP TABLE IF EXISTS `zoneExclusion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneExclusion` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `dated` date NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk_2` (`zoneFk`,`dated`), + KEY `zoneFk` (`zoneFk`), + CONSTRAINT `zoneExclusion_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `zoneGeo` -- @@ -30366,11 +30651,47 @@ CREATE TABLE `zoneIncluded` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `zoneWarehouse` +-- + +DROP TABLE IF EXISTS `zoneWarehouse`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `zoneWarehouse` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `zoneFk` int(11) NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL, + PRIMARY KEY (`id`), + UNIQUE KEY `zoneFk` (`zoneFk`,`warehouseFk`), + KEY `warehouseFk` (`warehouseFk`), + CONSTRAINT `zoneWarehouse_ibfk_1` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Dumping events for database 'vn' -- /*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `envialiaThreHoldChecker` */; +/*!50106 DROP EVENT IF EXISTS `department_doCalc` */; +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 = utf8 */ ;; +/*!50003 SET character_set_results = utf8 */ ;; +/*!50003 SET collation_connection = utf8_general_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `department_doCalc` ON SCHEDULE EVERY 15 SECOND STARTS '2019-11-15 00:00:00' ON COMPLETION PRESERVE ENABLE DO CALL vn.department_doCalc */ ;; +/*!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 `envialiaThreHoldChecker` */;; DELIMITER ;; /*!50003 SET @saved_cs_client = @@character_set_client */ ;; /*!50003 SET @saved_cs_results = @@character_set_results */ ;; @@ -30426,90 +30747,90 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN - - DECLARE vCurrentCount INT; - DECLARE vCheckSum INT; - DECLARE vIsAlreadyNotified BOOLEAN; - DECLARE vTableQueue TEXT; - DECLARE vLineQueue TEXT; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCur CURSOR FOR - SELECT CONCAT(' - ', IFNULL(pq.id, ''), ' - ', IFNULL(p.path, ''),' - ', IFNULL(i.Informe, ''),' - ', IFNULL(e.Estado, ''),' - ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' - ', IFNULL(pq.`error`, ''),' - ') - FROM vn.printingQueue pq - LEFT JOIN vn.worker w ON w.id = pq.worker - LEFT JOIN vn.printer p ON p.id = pq.printer - LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report - JOIN vn2008.Estados e ON e.Id_Estado = pq.state - LIMIT 30; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum - FROM vn.printingQueue WHERE state = 1; - - SELECT isAlreadyNotified INTO vIsAlreadyNotified - FROM printingQueueCheck; - - IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND - (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND - vIsAlreadyNotified = FALSE AND vCurrentCount > 0 - THEN - - SELECT ' - - - - - - - - ' INTO vTableQueue; - - OPEN vCur; - - l: LOOP - - SET vDone = FALSE; - - FETCH vCur INTO vLineQueue; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - - END LOOP; - - CLOSE vCur; - - INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es', - 'servidor de impresion parado', - CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); - - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; - END IF; - - IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND - vIsAlreadyNotified = TRUE - THEN - UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; - END IF; - - UPDATE printingQueueCheck - SET lastCount = vCurrentCount, - lastCheckSum = vCheckSum; - +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -30634,6 +30955,42 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `address_getGeo` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `address_getGeo`(vSelf INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Returns the geo for the passed address. + * + * @param vSelf The address id + * @return The geo id + */ + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.`code` = a.postalCode + WHERE a.id = vSelf + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + RETURN vGeoFk; +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 DROP FUNCTION IF EXISTS `barcodeToItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -30678,6 +31035,107 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `bionicCalcReverse` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `bionicCalcReverse`(vWarehouse INT, + vMargin DECIMAL(10,3), + vRetailedPrice DECIMAL(10,3), + vM3 DECIMAL(10,3), + vAddress INT, + vAgencyMode INT) RETURNS decimal(10,3) + DETERMINISTIC +BEGIN + DECLARE vGeneralInflationCoeficient INT; + DECLARE vVerdnaturaVolumeBox BIGINT; + DECLARE vClientFk INT; + DECLARE vComponentRecovery VARCHAR(50) DEFAULT 'debtCollection'; + DECLARE vComponentMana VARCHAR(50) DEFAULT 'autoMana'; + DECLARE vComponentPort VARCHAR(50) DEFAULT 'delivery'; + DECLARE vComponentMargin VARCHAR(50) DEFAULT 'margin'; + DECLARE vComponentCost VARCHAR(50) DEFAULT 'purchaseValue'; + DECLARE vComponentCostValue DECIMAL(10,2); + DECLARE vItem INT DEFAULT 98; + DECLARE vItemCarryBox INT; + + SELECT generalInflationCoeFicient, verdnaturaVolumeBox, itemCarryBox + INTO vGeneralInflationCoeficient, vVerdnaturaVolumeBox, vItemCarryBox + FROM bionicConfig; + + SELECT clientFk INTO vClientFk FROM address WHERE id = vAddress; + + -- Creamos la tabla tmp.bionicComponent + DROP TEMPORARY TABLE IF EXISTS tmp.bionicComponent; + CREATE TEMPORARY TABLE tmp.bionicComponent( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `componentFk` int(10) unsigned NOT NULL, + `value` decimal(10,4) NOT NULL, + UNIQUE KEY `itemWarehouseComponent` (`itemFk`,`warehouseFk`,`componentFk`) USING HASH, + KEY `itemWarehouse` (`itemFk`,`warehouseFk`) USING BTREE + ) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; + + -- Margin + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id, vMargin + FROM component + WHERE code = vComponentMargin; + + -- Recobro + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, c.id, ROUND(LEAST(cr.recobro,0.25), 3) + FROM bi.claims_ratio cr + JOIN component c ON c.code = vComponentRecovery + WHERE cr.Id_Cliente = vClientFk AND cr.recobro > 0.009; + + -- Componente de maná automático, en función del maná acumulado por el comercial. + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, ROUND(ms.prices_modifier_rate, 3) + FROM client c + JOIN bs.mana_spellers ms ON c.salesPersonFk = ms.Id_Trabajador + JOIN component co ON co.code = vComponentMana + WHERE ms.prices_modifier_activated AND c.id = vClientFk LIMIT 1; + + -- Reparto + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, co.id, vGeneralInflationCoeficient + * ROUND( + vM3 + * az.price + * az.inflation + / vVerdnaturaVolumeBox, 4 + ) + FROM agencyMode ag + JOIN address a ON a.id = vAddress AND ag.id = vAgencyMode + JOIN agencyProvince ap ON ap.agencyFk = ag.agencyFk + AND ap.warehouseFk = vWarehouse AND ap.provinceFk = a.provinceFk + JOIN agencyModeZone az ON az.agencyModeFk = vAgencyMode + AND az.zone = ap.zone AND az.itemFk = 71 AND az.warehouseFk = vWarehouse + JOIN component co ON co.code = vComponentPort; + + -- Coste + SELECT vRetailedPrice - SUM(`value`) INTO vComponentCostValue + FROM tmp.bionicComponent; + + INSERT INTO tmp.bionicComponent (warehouseFk, itemFk, componentFk, `value`) + SELECT vWarehouse, vItem, id,vComponentCostValue + FROM component + WHERE code = vComponentCost; + + RETURN vComponentCostValue; +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 DROP FUNCTION IF EXISTS `bionicCalcReverse__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -31112,27 +31570,34 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` FUNCTION `clientGetMana`(vClient INT) RETURNS decimal(10,2) - READS SQL DATA + DETERMINISTIC BEGIN /** - * BERNAT: WORKING IN THIS FILE - * Devuelve el maná del cliente. - * + * Devuelve el mana del cliente. + * * @param vClient Id del cliente - * @return Maná del cliente + * @return Mana del cliente */ - DECLARE vMana DECIMAL(10,2); DECLARE vFromDated DATE; DECLARE vHasMana BOOLEAN; - + DECLARE vManaComponent INT; + DECLARE vAutoManaComponent INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vManaGreugeType FROM greugeType WHERE code = 'mana'; + SELECT id INTO vManaBank FROM bank WHERE code = 'mana'; + SELECT id INTO vManaComponent FROM component WHERE code = 'mana'; + SELECT id INTO vAutoManaComponent FROM component WHERE code = 'autoMana'; + SELECT COUNT(*) INTO vHasMana FROM `client` c WHERE c.id = vClient AND c.typeFk = 'normal'; @@ -31142,52 +31607,43 @@ BEGIN END IF; SELECT max(dated) INTO vFromDated - FROM vn.clientManaCache; + FROM clientManaCache; SELECT sum(mana) INTO vMana FROM ( SELECT mana - FROM vn.clientManaCache + FROM clientManaCache WHERE clientFk = vClient - AND dated = vFromDated - + AND dated = vFromDated UNION ALL - - SELECT s.quantity * Valor - FROM vn.ticket t - JOIN vn.address a ON a.id = t.addressFk - JOIN vn.sale s on s.ticketFk = t.id - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id - WHERE Id_Componente IN (37, 39) + SELECT s.quantity * value + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN sale s on s.ticketFk = t.id + JOIN saleComponent sc on sc.saleFk = s.id + WHERE sc.componentFk IN (vManaComponent, vAutoManaComponent) AND t.shipped > vFromDated AND t.shipped < TIMESTAMPADD(DAY,1,CURDATE()) AND a.clientFk = vClient - UNION ALL - - SELECT - Entregado - FROM vn2008.Recibos r - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE r.Id_Banco = 66 - AND r.Fechacobro > vFromDated - AND r.Fechacobro <= CURDATE() - AND c.Id_Cliente = vClient - + SELECT - amountPaid + FROM receipt r + JOIN `client` c ON c.id = r.clientFk + WHERE r.bankFk = vManaBank + AND r.payed > vFromDated + AND r.payed <= CURDATE() + AND c.id = vClient UNION ALL - - SELECT g.Importe - FROM vn2008.Greuges g - JOIN vn2008.Clientes c using(Id_Cliente) - WHERE g.Greuges_type_id = 3 -- Maná - AND g.Fecha > vFromDated - AND g.Fecha <= CURDATE() - AND c.Id_Cliente = vClient - + SELECT g.amount + FROM greuge g + JOIN `client` c ON c.id = g.clientFk + WHERE g.greugeTypeFk = vManaGreugeType + AND g.shipped > vFromDated + AND g.shipped <= CURDATE() + AND c.id = vClient ) sub; - RETURN IFNULL(vMana,0); - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -31590,9 +32046,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -31606,26 +32062,50 @@ BEGIN DECLARE vCommission INT; DECLARE vCurrentCommission INT; DECLARE vIsCurrencyUsd INT; + DECLARE vLastEntryFk INT; SELECT count(*) INTO vIsCurrencyUsd FROM currency c WHERE c.code = 'USD' AND id = vCurrencyFk; IF NOT vIsCurrencyUsd THEN - SELECT commission INTO vCurrentCommission - FROM supplier s - WHERE s.id = vSupplierFk; - RETURN vCurrentCommission; - END IF; - - SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission - FROM travel t - LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped - WHERE t.id = vTravelFk - ORDER BY r.`dated` DESC - LIMIT 1; + + SELECT e.id INTO vLastEntryFk + FROM vn.entry e + JOIN vn.travel tr ON tr.id = e.travelFk + WHERE e.supplierFk = vSupplierFk + ORDER BY tr.landed DESC + LIMIT 1; - RETURN IFNULL(vCommission, 0); + IF vLastEntryFk THEN + + SELECT commission INTO vCurrentCommission + FROM vn.entry + WHERE id = vLastEntryFk; + + ELSE + + SELECT commission INTO vCurrentCommission + FROM supplier s + WHERE s.id = vSupplierFk; + + END IF; + + RETURN vCurrentCommission; + + ELSE + + SELECT ROUND(-100 * (1 - (1 / r.value))) INTO vCommission + FROM travel t + LEFT JOIN referenceCurrent r ON r.currencyFk = vCurrencyFk AND r.`dated` <= t.shipped + WHERE t.id = vTravelFk + ORDER BY r.`dated` DESC + LIMIT 1; + + RETURN IFNULL(vCommission, 0); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33735,9 +34215,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -33748,21 +34228,22 @@ BEGIN DECLARE vLastIn DATETIME; DECLARE vDayStayMax INT; DECLARE vHasDirectionOut INT; + DECLARE vLastInsertedId INT; SELECT dayStayMax INTO vDayStayMax - FROM vn.workerTimeControlParams; + FROM workerTimeControlParams; - SELECT vn.timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; + SELECT timeWorkerControl_getDirection(vUserFk,vTimed) INTO vDirection; IF vDirection = 'out' THEN SELECT MAX(timed) INTO vLastIn - FROM vn.workerTimeControl + FROM workerTimeControl WHERE userFk = vUserFk AND direction = 'in' AND timed < vTimed; - UPDATE vn.workerTimeControl wtc + UPDATE workerTimeControl wtc SET wtc.direction = 'middle' WHERE userFk = vUserFk AND direction = 'out' @@ -33771,25 +34252,28 @@ BEGIN ELSE IF vDirection = 'in' THEN SELECT COUNT(*) INTO vHasDirectionOut - FROM vn.workerTimeControl wtc + FROM workerTimeControl wtc WHERE userFk = vUserFk AND direction = 'out' AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - UPDATE vn.workerTimeControl wtc + UPDATE workerTimeControl wtc SET wtc.direction = IF (vHasDirectionOut,'middle','out') WHERE userFk = vUserFk AND direction = 'in' AND timed BETWEEN vTimed AND TIMESTAMPADD(SECOND, 50400, vTimed); - + END IF; END IF; INSERT INTO workerTimeControl(userFk, timed, warehouseFk, direction, manual) VALUES(vUserFk, vTimed, vWarehouseFk, vDirection, vIsManual); - -RETURN LAST_INSERT_ID(); + SET vLastInsertedId = LAST_INSERT_ID(); + + CALL workerTimeControlSOWP(vUserFk, vTimed); + + RETURN vLastInsertedId; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34218,7 +34702,7 @@ BEGIN -- Establecemos los almacenes y las fechas que van a entrar al disponible - CALL vn.zoneGetShippedWarehouse(vDate, vAddress, vAgencyMode); + CALL vn.zone_getShippedWarehouse(vDate, vAddress, vAgencyMode); DROP TEMPORARY TABLE IF EXISTS tmp.availableCalc; CREATE TEMPORARY TABLE tmp.availableCalc( @@ -34371,23 +34855,28 @@ BEGIN DECLARE vWarehouseOut INT; DECLARE vIsMerchandise BOOL; DECLARE vIsFeedStock BOOL; - + DECLARE vLanded DATE; + DECLARE vBuyerFk INT; + DECLARE vItemName VARCHAR(50); + SELECT entryFk, itemFk, stickers, packing INTO vEntryFk, vItemFk, vStickers, vPacking FROM buy WHERE id = vSelf; - SELECT t.warehouseInFk, t.warehouseOutFk - INTO vWarehouse, vWarehouseOut + SELECT t.warehouseInFk, t.warehouseOutFk, t.landed + INTO vWarehouse, vWarehouseOut, vLanded FROM entry e JOIN travel t ON t.id = e.travelFk WHERE e.id = vEntryFk; - SELECT k.merchandise INTO vIsMerchandise + SELECT k.merchandise, it.workerFk, i.longName + INTO vIsMerchandise, vBuyerFk, vItemName FROM itemCategory k JOIN itemType it ON it.categoryFk = k.id JOIN item i ON i.typeFk = it.id WHERE i.id = vItemFk; + IF vIsMerchandise THEN REPLACE bi.rotacion SET Id_Article = vItemFk, @@ -34410,6 +34899,20 @@ BEGIN CALL vn.buy_notifyPassport(vSelf, vItemFk, vStickers, vPacking); END IF; END IF; + + -- Aviso al comprador de modificacion de entrada en Barajas + IF (SELECT isBuyerToBeEmailed FROM warehouse WHERE id = vWarehouse) + AND vLanded = CURDATE() + AND vBuyerFk != account.myUserGetId() + THEN + + CALL vn.mail_insert(CONCAT(account.userGetNameFromId(vBuyerFk),'@verdnatura.es'), + CONCAT(account.myUserGetName(),'@verdnatura.es'), + CONCAT('E ',vEntryFk,' Se ha modificado item ', vItemFk, ' ',vItemName), + 'Este email se ha generado automáticamente'); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34860,7 +35363,7 @@ BEGIN ENGINE = MEMORY SELECT vItemFk itemFk; - CALL ticketCalculate(vLanded, vAddressFk, vAgencyModeFk); + CALL catalog_calculate(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE tmp.item; END ;; DELIMITER ; @@ -34886,7 +35389,7 @@ proc: BEGIN /** * Calcula los articulos disponibles y sus precios * - * @table tmp.item(itemFk) Listado de artículos a calcular + * @table tmp.item(itemFk) Listado de artículos a calcular * @param vLanded Fecha de recepcion de mercancia * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id de la agencia @@ -34906,7 +35409,7 @@ proc: BEGIN DECLARE vZoneFk INT; DECLARE vDone BOOL; DECLARE cTravelTree CURSOR FOR - SELECT id, warehouseFk, shipped FROM tmp.zoneGetShipped; + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; @@ -34915,7 +35418,7 @@ proc: BEGIN SELECT clientFk INTO vClient FROM address WHERE id = vAddressFk; - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot( @@ -34982,7 +35485,7 @@ proc: BEGIN LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible JOIN origin o ON o.id = i.originFk JOIN ( - SELECT MIN(price) price, itemFk, MIN(priceKg) priceKg + SELECT MIN(price) price, itemFk, priceKg FROM tmp.ticketComponentPrice GROUP BY itemFk ) bl ON bl.itemFk = b.itemFk @@ -34998,9 +35501,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -35020,6 +35523,7 @@ proc: BEGIN * packing, grouping, groupingMode, buyFk, typeFk) * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) */ + DECLARE vClientFk INT; DECLARE vGeneralInflationCoefficient INT DEFAULT 1; DECLARE vMinimumDensityWeight INT DEFAULT 167; @@ -35069,9 +35573,9 @@ proc: BEGIN LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk LEFT JOIN ( SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, z.warehouseFk + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk FROM priceFixed pf - JOIN zone z ON z.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0 + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC ) tpf GROUP BY tpf.itemFk, tpf.warehouseFk @@ -35351,27 +35855,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE oneYearAgo DATE; - DECLARE twoYearsAgo DATE; - DECLARE fourYearsAgo DATE; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); - SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); - SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; - DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; - DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); - CALL shelving_clean; - +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + CALL vn.ticketPackagingRecovery; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -35938,15 +36442,14 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientPackagingOverstock`(vClientFk INT, vGraceDays INT ) BEGIN - -- Bernat: WORKING IN THIS FILE DROP TEMPORARY TABLE IF EXISTS tmp.clientPackagingOverstock; CREATE TEMPORARY TABLE tmp.clientPackagingOverstock ENGINE = MEMORY @@ -35957,10 +36460,8 @@ BEGIN sum(GotfromClient) - sum(SenttoClient), sum(InvoicedtoClient) - sum(InvoicedfromClient) ) as abonables - - FROM - ( - + FROM + ( SELECT t.*, IF(@month = month, 0, 1) monthEnd, @month := month @@ -35977,10 +36478,8 @@ BEGIN x.refFk as invoice, month(shipped) month, x.companyFk - FROM ( - SELECT t.id, t.shipped, IFNULL(pe.equivalentFk, s.itemFk) itemFk, @@ -35991,16 +36490,14 @@ BEGIN t.refFk, @month := 0 month, t.companyFk - FROM vn.sale s - JOIN vn.ticket t on t.id = s.ticketFk - JOIN vn2008.Cubos c ON c.item_id = s.itemFk - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = s.itemFk + FROM sale s + JOIN ticket t on t.id = s.ticketFk + JOIN packaging p ON p.itemFk = s.itemFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = s.itemFk WHERE t.clientFk = vClientFk AND t.shipped > '2017-11-30' - AND c.Retornable - + AND p.isPackageReturnable UNION ALL - SELECT NULL, '2017-11-30', IFNULL(pe.equivalentFk, tps.itemFk) itemFk, @@ -36012,13 +36509,11 @@ BEGIN NULL, NULL - FROM vn.ticketPackagingStartingStock tps - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = tps.itemFk + FROM ticketPackagingStartingStock tps + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = tps.itemFk WHERE tps.clientFk = vClientFk AND tps.isForgetable = FALSE - UNION ALL - SELECT t.id, t.shipped, IFNULL(pe.equivalentFk, p.itemFk) itemFk, @@ -36029,22 +36524,19 @@ BEGIN NULL AS refFk, NULL, t.companyFk - FROM vn.ticketPackaging tp - JOIN vn.ticket t on t.id = tp.ticketFk - JOIN vn.packaging p ON p.id = tp.packagingFk - LEFT JOIN vn.packageEquivalentItem pe ON pe.itemFk = p.itemFk + FROM ticketPackaging tp + JOIN ticket t on t.id = tp.ticketFk + JOIN packaging p ON p.id = tp.packagingFk + LEFT JOIN packageEquivalentItem pe ON pe.itemFk = p.itemFk WHERE t.clientFk = vClientFk AND t.shipped > '2017-11-21' ) x - JOIN vn.item i ON x.itemFk = i.id + JOIN item i ON x.itemFk = i.id GROUP BY x.id, x.itemFk - ) t ORDER BY itemFk, shipped DESC ) t2 - GROUP BY itemFk - -; + GROUP BY itemFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36171,54 +36663,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.risk,0) = 0; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk - FROM bs.clientDied cd - LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id - JOIN vn.client c ON c.id = cd.id - JOIN vn.province p ON p.id = c.provinceFk - JOIN vn.country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' - AND cp.clientFk IS NULL - AND co.country NOT IN ('Portugal','Francia','España exento') - AND c.salesPersonFk IS NOT NULL; - - CALL vn.clientGetDebt(curdate()); - - DROP TEMPORARY TABLE IF EXISTS tmp.contador; - CREATE TEMPORARY TABLE tmp.contador (id INT) - ENGINE = MEMORY; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO - INSERT INTO tmp.contador SET id = vClientFk; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; INSERT INTO vn.clientLog (originFk, userFk, `action`, description) VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); - + REPLACE bs.clientNewBorn(clientFk, shipped) - VALUES(vClientFk, CURDATE()); - FETCH rs INTO vClientFk; - END WHILE; - - CLOSE rs; + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36229,183 +36721,137 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clonTravelComplete`(IN `vTravelFk` INT, IN `vDateStart` DATE, IN `vDateEnd` DATE, IN `vRef` VARCHAR(255)) -BEGIN - -- BERNAT: WORKING IN THIS FILE - DECLARE vTravelNew INT; - DECLARE vEntryNew INT; - DECLARE vDone BIT DEFAULT 0; - DECLARE vAuxEntryFk INT; - DECLARE vRsEntry CURSOR FOR - SELECT e.id - FROM vn.entry e - JOIN vn.travel t - ON t.id = e.travelFk - WHERE e.travelFk = vTravelFk; - - DECLARE vRsBuy CURSOR FOR - SELECT b.* - FROM vn.buy b - JOIN vn.entry e - ON b.entryFk = e.id - WHERE e.travelFk = vTravelNew and b.entryFk=entryNew - ORDER BY e.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - ROLLBACK; - RESIGNAL; - END; - - START TRANSACTION; - - INSERT INTO vn.travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) - SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg - FROM vn.travel - WHERE id = vTravelFk; - - SET vTravelNew = LAST_INSERT_ID(); - SET vDone = 0; - OPEN vRsEntry ; - FETCH vRsEntry INTO vAuxEntryFk; - - WHILE NOT vDone DO - INSERT INTO vn.entry (supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - travelFk, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk) - SELECT supplierFk, - ref, - isInventory, - isConfirmed, - isOrdered, - isRaid, - commission, - created, - evaNotes, - vTravelNew, - currencyFk, - companyFk, - gestDocFk, - invoiceInFk - FROM vn.entry - WHERE id = vAuxEntryFk; - - SET vEntryNew = LAST_INSERT_ID(); - - /* INSERT INTO vn.buy ( - entryFk, - itemFk, - amount, - buyingValue, - quantity, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isCkecked) - SELECT - vEntryNew, - itemFk, - amount, - buyingValue, - quantity, - packageFk, - stickers, - freightValue, - packageValue, - comissionValue, - packing, - `grouping`, - groupingMode, - location, - price1, - price2, - price3, - minPrice, - producer, - printedStickers, - isCkecked - FROM buy - WHERE entryFk = vAuxEntryFk;*/ - - INSERT INTO vn2008.Compres (Id_Entrada, - Id_Article, - Cantidad, - Costefijo, - Id_Cubo, - Etiquetas, - Portefijo, - Embalajefijo, - Comisionfija, - Packing, - `grouping`, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP, - Productor, - Vida, - punteo) - SELECT vEntryNew, - Id_Article, - Cantidad, - Costefijo, - Id_Cubo, - Etiquetas, - Portefijo, - Embalajefijo, - Comisionfija, - Packing, - `grouping`, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP, - Productor, - Vida, - punteo - FROM vn2008.Compres - WHERE Id_Entrada = vAuxEntryFk; - - - FETCH vRsEntry INTO vAuxEntryFk; - END WHILE; - CLOSE vRsEntry; - COMMIT; +BEGIN + + DECLARE vTravelNew INT; + DECLARE vEntryNew INT; + DECLARE vDone BIT DEFAULT 0; + DECLARE vAuxEntryFk INT; + DECLARE vRsEntry CURSOR FOR + SELECT e.id + FROM entry e + JOIN travel t + ON t.id = e.travelFk + WHERE e.travelFk = vTravelFk; + + DECLARE vRsBuy CURSOR FOR + SELECT b.* + FROM buy b + JOIN entry e + ON b.entryFk = e.id + WHERE e.travelFk = vTravelNew and b.entryFk=entryNew + ORDER BY e.id; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + ROLLBACK; + RESIGNAL; + END; + + START TRANSACTION; + + INSERT INTO travel (shipped,landed, warehouseInFk, warehouseOutFk, agencyFk, ref, isDelivered, isReceived, m3, kg) + SELECT vDateStart, vDateEnd,warehouseInFk, warehouseOutFk, agencyFk, vRef, isDelivered, isReceived, m3, kg + FROM travel + WHERE id = vTravelFk; + + SET vTravelNew = LAST_INSERT_ID(); + SET vDone = 0; + OPEN vRsEntry ; + FETCH vRsEntry INTO vAuxEntryFk; + + WHILE NOT vDone DO + INSERT INTO entry (supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + travelFk, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk) + SELECT supplierFk, + ref, + isInventory, + isConfirmed, + isOrdered, + isRaid, + commission, + created, + evaNotes, + vTravelNew, + currencyFk, + companyFk, + gestDocFk, + invoiceInFk + FROM entry + WHERE id = vAuxEntryFk; + + SET vEntryNew = LAST_INSERT_ID(); + + + INSERT INTO buy (entryFk, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked) + SELECT vEntryNew, + itemFk, + quantity, + buyingValue, + packageFk, + stickers, + freightValue, + packageValue, + comissionValue, + packing, + `grouping`, + groupingMode, + location, + price1, + price2, + price3, + minPrice, + producer, + printedStickers, + isChecked + FROM buy + WHERE entryFk = vAuxEntryFk; + + + FETCH vRsEntry INTO vAuxEntryFk; + END WHILE; + CLOSE vRsEntry; + COMMIT; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36435,6 +36881,175 @@ BEGIN FROM vn.ticketCollection tc WHERE tc.collectionFk = vCollectionFk; +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 DROP PROCEDURE IF EXISTS `collection_new` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_new`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vTicketLiters INT; + DECLARE vTicketLines INT; + DECLARE vTicketFk INT; + DECLARE vIsTicketCollected BOOLEAN; + DECLARE vMaxTickets INT; + DECLARE vStateFk INT; + DECLARE vVolumetryLiters INT; + DECLARE vVolumetryLines INT; + DECLARE vVolumetryFk INT; + DECLARE vVolumetryLevel INT; + DECLARE vVolumetryLitersMax INT; + DECLARE vVolumetryLinesMax INT; + DECLARE vDone BOOLEAN DEFAULT FALSE; + + DECLARE cVolumetry CURSOR FOR + SELECT level, liters, `lines` + FROM vn.collectionVolumetry + ORDER BY `level`; + + DECLARE cTicket CURSOR FOR + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE pb.problems = 0 + AND tc.ticketFk IS NULL + AND s.isPreparable + ORDER BY pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC + LIMIT vMaxTickets; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + SELECT COUNT(*), sum(liters), sum(`lines`) + INTO vMaxTickets, vVolumetryLitersMax, vVolumetryLinesMax + FROM vn.collectionVolumetry; + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + -- Empieza el bucle + OPEN cVolumetry; + OPEN cTicket; + + DROP TEMPORARY TABLE IF EXISTS tmp.kk; + CREATE TEMPORARY TABLE tmp.kk + SELECT pb.Id_Ticket ticketFk,pb.Hora, pb.Minuto, + pb.lines, + pb.m3 * 1000 liters + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + LEFT JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE pb.problems = 0 + AND tc.ticketFk IS NULL + AND s.isPreparable + ORDER BY pb.Hora, pb.Minuto, m3 DESC, pb.lines DESC + LIMIT vMaxTickets; + + FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters; + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + IF NOT vDone THEN + + INSERT INTO vn.collection + SET workerFk = account.myUserGetId(); + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + END IF; + + bucle:WHILE NOT vDone DO + + IF (vVolumetryLitersMax < vTicketLiters OR vVolumetryLinesMax < vTicketLines) AND vVolumetryLevel > 1 THEN + LEAVE bucle; + END IF; + + SELECT COUNT(*) INTO vIsTicketCollected + FROM vn.ticketCollection + WHERE ticketFk = vTicketFk + AND collectionFk = vCollectionFk; + + IF vIsTicketCollected THEN + + UPDATE vn.ticketCollection + SET level = CONCAT(level, vVolumetryLevel) + WHERE ticketFk = vTicketFk + AND collectionFk = vCollectionFk; + + ELSE + + INSERT INTO vn.ticketCollection + SET collectionFk = vCollectionFk, + ticketFk = vTicketFk, + level = vVolumetryLevel; + + INSERT INTO vncontrol.inter + SET state_id = vStateFk, + Id_Ticket = vTicketFk, + Id_Trabajador = account.myUserGetId(); + + END IF; + + SET vVolumetryLitersMax = GREATEST(0,vVolumetryLitersMax - vVolumetryLiters); + SET vVolumetryLinesMax = GREATEST(0,vVolumetryLinesMax - vVolumetryLines); + SET vTicketLiters = GREATEST(0,vTicketLiters - vVolumetryLiters); + SET vTicketLines = GREATEST(0,vTicketLines - vVolumetryLines); + + IF vVolumetryLitersMax = 0 OR vVolumetryLinesMax = 0 THEN + LEAVE bucle; + END IF; + + IF vTicketLiters > 0 OR vTicketLines > 0 THEN + + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + ELSE + + FETCH cTicket INTO vTicketFk, vTicketLines, vTicketLiters; + FETCH cVolumetry INTO vVolumetryLevel, vVolumetryLiters, vVolumetryLines; + + END IF; + + END WHILE; + + SELECT vCollectionFk; + + CLOSE cVolumetry; + CLOSE cTicket; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36852,9 +37467,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36896,9 +37511,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -36974,6 +37589,139 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `department_doCalc` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_doCalc`() +proc: BEGIN +/** + * Recalculates the department tree. + */ + DECLARE vIsChanged BOOL; + + DECLARE CONTINUE HANDLER FOR SQLEXCEPTION + BEGIN + DO RELEASE_LOCK('vn.department_doCalc'); + RESIGNAL; + END; + + IF !GET_LOCK('vn.department_doCalc', 0) THEN + LEAVE proc; + END IF; + + SELECT isChanged INTO vIsChanged + FROM department_recalc; + + IF vIsChanged THEN + UPDATE department_recalc SET isChanged = FALSE; + CALL vn.department_calcTree; + END IF; + + DO RELEASE_LOCK('vn.department_doCalc'); +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 DROP PROCEDURE IF EXISTS `department_getLeaves` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `department_getLeaves`( + vParentFk INT, + vSearch VARCHAR(255) +) +BEGIN + DECLARE vIsNumber BOOL; + DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (UNIQUE (id)) + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + IF vIsSearch THEN + SET vIsNumber = vSearch REGEXP '^[0-9]+$'; + + INSERT INTO tNodes + SELECT id FROM department + WHERE (vIsNumber AND `name` = vSearch) + OR (!vIsNumber AND `name` LIKE CONCAT('%', vSearch, '%')) + LIMIT 1000; + END IF; + + IF vParentFk IS NULL THEN + DROP TEMPORARY TABLE IF EXISTS tChilds; + CREATE TEMPORARY TABLE tChilds + ENGINE = MEMORY + SELECT id FROM tNodes; + + DROP TEMPORARY TABLE IF EXISTS tParents; + CREATE TEMPORARY TABLE tParents + ENGINE = MEMORY + SELECT id FROM department LIMIT 0; + + myLoop: LOOP + DELETE FROM tParents; + INSERT INTO tParents + SELECT parentFk id + FROM department g + JOIN tChilds c ON c.id = g.id + WHERE g.parentFk IS NOT NULL; + + INSERT IGNORE INTO tNodes + SELECT id FROM tParents; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + + DELETE FROM tChilds; + INSERT INTO tChilds + SELECT id FROM tParents; + END LOOP; + + DROP TEMPORARY TABLE + tChilds, + tParents; + END IF; + + IF !vIsSearch THEN + INSERT IGNORE INTO tNodes + SELECT id FROM department + WHERE parentFk <=> vParentFk; + END IF; + + SELECT d.id, + d.`name`, + d.parentFk, + d.sons + FROM department d + JOIN tNodes n ON n.id = d.id + ORDER BY depth, `name`; + + DROP TEMPORARY TABLE tNodes; +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 DROP PROCEDURE IF EXISTS `duaEntryValueUpdate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -37027,8 +37775,6 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) BEGIN - - -- BERNAT: WORKING IN THIS FILE DECLARE done BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vASIEN BIGINT DEFAULT 0; @@ -37071,13 +37817,13 @@ BEGIN IF vCounter > 0 OR vASIEN > 0 THEN - UPDATE vn2008.XDiario x - JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN + UPDATE XDiario x + JOIN config c ON c.ASIEN = x.ASIEN SET x.ASIEN = vASIEN; ELSE - SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; + SELECT ASIEN INTO vASIEN FROM config; END IF; @@ -37580,216 +38326,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37851,62 +38597,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id =i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.merchandise IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38254,32 +39000,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `getItemVisibleAvailable`( vWarehouse TINYINT, vRefresh BOOL) BEGIN - - /*deprecated usar vn.itemGetVisibleAvailable - jgf 2019/09/10 */ - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - - -- FIXME: Android app is always passing %TRUE for #vRefresh, this leads to DB performance issues - CALL cache.visible_refresh(vVisibleCalc, FALSE /*vRefresh*/, vWarehouse); - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); - - SELECT a.Id_Article, a.Article, a.Medida, a.Tallos, - a.caja, O.Abreviatura AS origen, a.Color, tipo_id, - an.Nicho, a.Categoria, p.`name` AS producer, - v.visible, av.available, an.reserve - FROM vn2008.Articles a - LEFT JOIN vn2008.Articles_nicho an - ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = a.Id_Article AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = a.Id_Article AND av.calc_id = vAvailableCalc - LEFT JOIN vn2008.Origen O - ON O.id = a.id_origen - LEFT JOIN vn2008.producer p - ON p.producer_id = a.producer_id - WHERE (vItem IS NULL OR a.Id_Article = vItem); + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39299,11 +40021,11 @@ BEGIN FECREGCON, empresa_id ) - SELECT vBookNumber ASIEN, + SELECT vBookNumber ASIEN, n.bookEntried FECHA, tc.code SUBCTA, s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE, + ROUND(tc.rate/100 * SUM(it.taxableBase) + 0.0001, 2) EURODEBE, SUM(it.taxableBase) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -41508,65 +42230,8 @@ CREATE DEFINER=`root`@`%` PROCEDURE `itemGetVisibleAvailable`( vWarehouse TINYINT, vRefresh BOOL) BEGIN - - DECLARE vVisibleCalc INT; - DECLARE vAvailableCalc INT; - DECLARE vVisibleAltillo INT; - - CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/, vWarehouse, vDate); - CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); - - - - SELECT visible INTO vVisibleAltillo - FROM vn.itemShelvingStock - WHERE itemFk = vItem - AND warehouseFk = vWarehouse; - - IF vRefresh THEN - - DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; - CREATE TEMPORARY TABLE vn2008.tmp_item - (PRIMARY KEY (item_id)) - ENGINE = MEMORY - SELECT vItem item_id, 0 stock, 0 visible; - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - vi.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN vn2008.tmp_item v - ON v.item_id = i.id - LEFT JOIN cache.available av - ON av.calc_id = vAvailableCalc AND av.item_id = i.id - LEFT JOIN cache.visible vi - ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id - LEFT JOIN cache.stock st - ON st.warehouse_id = vWarehouse AND st.item_id = i.id - WHERE (vItem IS NULL OR i.id = vItem); - - ELSE - - SELECT i.id, i.longName, i.box, i.typeFk, - i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, - ip.code, ip.reserve, - v.visible - IFNULL(vVisibleAltillo,0) AS visible, - av.available - FROM vn.item i - LEFT JOIN vn.itemPlacement ip - ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse - LEFT JOIN cache.visible v - ON v.item_id = i.id AND v.calc_id = vVisibleCalc - LEFT JOIN cache.available av - ON av.item_id = i.id AND av.calc_id = vAvailableCalc - WHERE (vItem IS NULL OR i.id = vItem); - - END IF; - + -- DEPRECADO - UTILIZAR vn.item_getVisibleAvailable() - JSB - 2019-11-20 + CALL item_getVisibleAvailable(vItem, vDate, vWarehouse, vRefresh); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -41584,38 +42249,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) -BEGIN - SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.`grouping`, - b.groupingMode, - i.stems, - b.quantity, - b.buyingValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() - ORDER BY tr.landed DESC , b.id DESC; +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43485,6 +44150,84 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `item_getVisibleAvailable` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `item_getVisibleAvailable`( + vItem INT, + vDate DATE, + vWarehouse TINYINT, + vRefresh BOOL) +BEGIN + DECLARE vVisibleCalc INT; + DECLARE vAvailableCalc INT; + DECLARE vVisibleAltillo INT; + + CALL cache.available_refresh(vAvailableCalc, FALSE /*vRefresh*/ , vWarehouse, vDate); + CALL cache.visible_refresh(vVisibleCalc, FALSE,vWarehouse); + + SELECT visible INTO vVisibleAltillo + FROM vn.itemShelvingStock + WHERE itemFk = vItem + AND warehouseFk = vWarehouse; + + IF vRefresh THEN + + DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item; + CREATE TEMPORARY TABLE vn2008.tmp_item + (PRIMARY KEY (item_id)) + ENGINE = MEMORY + SELECT vItem item_id, 0 stock, 0 visible; + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + vi.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN vn2008.tmp_item v + ON v.item_id = i.id + LEFT JOIN cache.available av + ON av.calc_id = vAvailableCalc AND av.item_id = i.id + LEFT JOIN cache.visible vi + ON vi.calc_id = vVisibleCalc AND vi.item_id = i.id + LEFT JOIN cache.stock st + ON st.warehouse_id = vWarehouse AND st.item_id = i.id + WHERE (vItem IS NULL OR i.id = vItem); + + ELSE + + SELECT i.id, i.longName, i.box, i.typeFk, + i.tag5,i.value5,i.tag6,i.value6,i.tag7,i.value7,i.tag8,i.value8, + ip.code, ip.reserve, + v.visible - IFNULL(vVisibleAltillo,0) AS visible, + av.available + FROM vn.item i + LEFT JOIN vn.itemPlacement ip + ON i.id = ip.itemFk AND ip.warehouseFk = vWarehouse + LEFT JOIN cache.visible v + ON v.item_id = i.id AND v.calc_id = vVisibleCalc + LEFT JOIN cache.available av + ON av.item_id = i.id AND av.calc_id = vAvailableCalc + WHERE (vItem IS NULL OR i.id = vItem); + + 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 DROP PROCEDURE IF EXISTS `ledger_next` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -43612,6 +44355,48 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mail_insert` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mail_insert`( + vSender VARCHAR(50), + vReplyTo VARCHAR(50), + vSubject VARCHAR(50), + vBody VARCHAR(255)) +BEGIN + + DECLARE vIsRepeated BOOLEAN; + + SELECT COUNT(*) INTO vIsRepeated + FROM vn.mail + WHERE creationDate >= CURDATE() + AND sender = vSender + AND `replyTo` = vReplyTo + AND `subject` = vSubject; + + IF NOT vIsRepeated THEN + + INSERT INTO vn.mail SET + `sender` = vSender, + `replyTo` = vReplyTo, + `subject` = vSubject, + `body` = vBody; + + 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 DROP PROCEDURE IF EXISTS `makeNewItem` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44764,6 +45549,56 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `rangeDateInfo` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `rangeDateInfo`(vStarted DATE, vEnded DATE) +BEGIN +/** + * Crea una tabla temporal con las fechas + * desde una fecha inicial a una final + * @param vStarted fecha inicial + * @param vEnded fecha final + */ + DECLARE vDated DATE DEFAULT vStarted; + + DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; + CREATE TEMPORARY TABLE tmp.rangeDate( + `dated` DATE, + `period` INT, + `month` INT, + `year` INT, + `day` INT, + `week` INT, + `yearMonth` INT + ) + ENGINE = MEMORY; + + WHILE vDated <= vEnded DO + INSERT INTO tmp.rangeDate + SET `dated` = vDated, + `period` = YEAR(vDated) * 100 + WEEK(vDated, 1), + `month` = MONTH(vDated), + `year` = YEAR(vDated), + `day` = DAY(vDated), + `week` = WEEK(vDated, 1), + `yearMonth` = YEAR(vDated) * 100 + MONTH(vDated); + + SET vDated = DATE_ADD(vDated, INTERVAL 1 DAY); + END WHILE; +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 DROP PROCEDURE IF EXISTS `refund` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -44808,8 +45643,7 @@ BEGIN WHERE id = vOriginTicket; SELECT id INTO vZoneFk - FROM zone WHERE agencyModeFk = vRefundAgencyMode - ORDER BY (warehouseFk = vWarehouse) DESC + FROM zone WHERE agencyModeFk = vRefundAgencyMode LIMIT 1; INSERT INTO vn2008.Tickets ( @@ -45353,77 +46187,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45819,7 +46653,14 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `sale_calculateComponent`(vSale INT, vOption INT) proc: BEGIN - +/** + * Actualiza los componentes + * + * @param vSale Delivery date + * @param vOption indica en que componente pone el descuadre, NULL en casos habituales + * @return tmp.ticketLot(warehouseFk, available, itemFk, buyFk) + * @return tmp.sale(saleFk, warehouseFk) + */ DECLARE vShipped DATE; DECLARE vWarehouseFk SMALLINT; DECLARE vAgencyModeFk INT; @@ -45915,33 +46756,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46731,19 +47572,18 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `stowawayUnBoarding` */; +/*!50003 DROP PROCEDURE IF EXISTS `stowaway_unboarding` */; /*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `stowawayUnBoarding`(vShipFk INT, vStowawayFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `stowaway_unboarding`(vShipFk INT, vStowawayFk INT) BEGIN - DECLARE vWorker VARCHAR(255); DELETE FROM stowaway @@ -46754,11 +47594,13 @@ BEGIN WHERE code = 'BOARDING' AND ticketFk = vShipFk; DELETE FROM sale - WHERE ticketFk = vShipFk AND itemFk = 98 AND concept = CONCAT('POLIZÓN! ',vStowawayFk); + WHERE ticketFk = vShipFk + AND itemFk = 98 + AND concept = CONCAT('POLIZÓN! ',vStowawayFk); SELECT u.`name` INTO vWorker - FROM account.user u JOIN vn.worker w ON w.userFk = u.id - WHERE w.id = vn2008.Averiguar_ComercialCliente_IdTicket_Id(vStowawayFk); + FROM account.user u JOIN worker w ON w.userFk = u.id + WHERE w.id = client_getSalesPersonByTicket(vStowawayFk); SELECT messageSend(vWorker,CONCAT('El ticket: ', vStowawayFk, ' ha dejado de ser un polizón')) INTO @a; END ;; @@ -47094,32 +47936,42 @@ BEGIN DECLARE vAddress INT; DECLARE vLanded DATE; DECLARE vAgency INT; + DECLARE vZoneFk INT; REPLACE INTO orderTicket(orderFk,ticketFk) SELECT orderFk, vTicketNew FROM orderTicket WHERE ticketFk = vTicketOld; - - SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk - INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency + + SELECT t.clientFk, t.warehouseFk, date(t.shipped), t.addressFk, t.agencyModeFk, t.landed, a.agencyFk, t.zoneFk + INTO vClient, vWarehouse, vShipped, vAddress, vAgencyMode, vLanded, vAgency, vZoneFk FROM vn.agencyMode a JOIN vn.ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicketNew; + + IF vLanded IS NULL THEN + CALL zone_getLanded(vShipped, vAddress, vAgency, vWarehouse); + UPDATE ticket t + JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk + SET t.landed = zgl.landed, + t.zone = zgl.zoneFk + WHERE t.id = vTicketNew; + + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetLanded LIMIT 1; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + END IF; - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CALL zoneGetShippedWarehouse(vLanded, vAddress, vAgencyMode); - DELETE FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouse; - - CALL buyUltimate(vWarehouse, vShipped); -- rellena la tabla tmp.buyUltimate con la ultima compra + -- rellena la tabla tmp.buyUltimate con la ultima compra + CALL buyUltimate(vWarehouse, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; CREATE TEMPORARY TABLE tmp.ticketLot - SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk - FROM sale s - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk - WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; + SELECT vWarehouse warehouseFk, NULL available, s.itemFk, bu.buyFk + FROM sale s + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = s.itemFk + WHERE s.ticketFk = vTicketOld GROUP BY s.itemFk; - CALL ticketComponentCalculate(vAddress,vAgencyMode); + CALL catalog_componentCalculate(vZoneFk, vAddress, vAgencyMode); -- Bionizamos lineas con Preu = 0 DROP TEMPORARY TABLE IF EXISTS tmp.sale; @@ -47141,14 +47993,6 @@ BEGIN AND s.price > 0; CALL ticketComponentUpdateSale(6); - - IF vLanded IS NULL THEN - CALL zoneGetLanded(vShipped, vAddress, vAgency,vWarehouse); - UPDATE ticket t - JOIN tmp.zoneGetLanded zgl ON t.warehouseFk = zgl.warehouseFk - SET t.landed = zgl.landed - WHERE t.id = vTicketNew; - END IF; -- Log CALL `logAdd`(vTicketNew, 'update', ' ticket' , 'Bioniza Ticket'); @@ -47307,18 +48151,15 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vLanded DATE; - DECLARE vZoneFk INT; - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - + DECLARE vZoneFk INT; SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale WHERE id = vSale; - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; @@ -47360,9 +48201,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -47374,18 +48215,15 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vTicket BIGINT; DECLARE vItem BIGINT; - DECLARE vLanded DATE; DECLARE vZoneFk INT; - DECLARE vHasZone BOOLEAN DEFAULT FALSE; - - + SELECT ticketFk, itemFk INTO vTicket, vItem FROM sale WHERE id = vSale; - SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.landed, t.zoneFk - INTO vWarehouseFk, vShipped, vAddressFk, vLanded, vZoneFk + SELECT t.warehouseFk, DATE(t.shipped), t.addressFk, t.zoneFk + INTO vWarehouseFk, vShipped, vAddressFk, vZoneFk FROM agencyMode a JOIN ticket t ON t.agencyModeFk = a.id WHERE t.id = vTicket; @@ -47538,7 +48376,7 @@ BEGIN SELECT ticketFk FROM tmp.ticketClosure; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN RESIGNAL; END; @@ -47604,9 +48442,6 @@ BEGIN CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', NULL); -- Facturar si está contabilizado IF vIsTaxDataChecked THEN - - -- JGF cau 12220 - -- IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN CALL invoiceOut_newFromClient( vClientFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), @@ -47614,15 +48449,10 @@ BEGIN vCompanyFk, NULL, vNewInvoiceId); - /*ELSE - CALL invoiceOut_newFromTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), NULL, vNewInvoiceId); - END IF;*/ - END IF; ELSE -- Albaran_print CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); - INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); END IF; -- ticketClosure end @@ -47887,23 +48717,23 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentCalculate__` */; /*!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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentCalculate__`( vAddressFk INT, vAgencyModeFk INT) proc: BEGIN -- OBSOLETO usar catalog_componentCalculate /** - * Calcula los componentes de un ticket + * Calcula los componentes de un ticket * * @param vAddressFk Id del consignatario * @param vAgencyModeFk Id del modo de agencia @@ -48155,7 +48985,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentMakeUpdate__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48165,7 +48995,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentMakeUpdate__`( vTicketFk INT, vClientFk INT, vAgencyModeFk INT, @@ -48204,7 +49034,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPreview__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48214,7 +49044,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPreview__`( vTicketFk INT, vLanded DATE, vAddressFk INT, @@ -48311,7 +49141,7 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketComponentPriceDifference__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -48321,7 +49151,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketComponentPriceDifference__`( vTicketFk INT, vLanded DATE, vAddressFk INT, @@ -48643,9 +49473,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48657,7 +49487,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithoutZone`( ,vAddressFk INT ,vAgencyModeFk INT ,vRouteFk INT - ,vLanded DATE + ,vlanded DATE ,vUserId INT ,OUT vNewTicket INT) BEGIN @@ -48680,9 +49510,9 @@ BEGIN WHERE clientFk = vClientId AND isDefaultAddress; END IF; - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; INSERT INTO vn2008.Tickets ( @@ -48699,14 +49529,14 @@ BEGIN ) SELECT vClientId, - IFNULL(vShipped,vLanded), + vShipped, a.id, IF(vAgencyModeFk, vAgencyModeFk, a.agencyModeFk), a.nickname, vWarehouseFk, IF(vRouteFk,vRouteFk,NULL), vCompanyFk, - vLanded, + vlanded, vZoneFk FROM address a JOIN agencyMode am ON am.id = a.agencyModeFk @@ -48740,9 +49570,9 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48754,7 +49584,7 @@ CREATE DEFINER=`root`@`%` PROCEDURE `ticketCreateWithUser`( ,vAddressFk INT ,vAgencyModeFk INT ,vRouteFk INT - ,vLanded DATE + ,vlanded DATE ,vUserId INT ,OUT vNewTicket INT) BEGIN @@ -48773,9 +49603,9 @@ BEGIN IF vAgencyModeFk IS NOT NULL THEN - CALL vn.zoneGetShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + CALL vn.zone_getShippedWarehouse(vlanded, vAddressFk, vAgencyModeFk); - SELECT id INTO vZoneFk FROM tmp.zoneGetShipped + SELECT zoneFk INTO vZoneFk FROM tmp.zoneGetShipped WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; IF vZoneFk IS NULL OR vZoneFk = 0 THEN @@ -48796,14 +49626,14 @@ BEGIN ) SELECT vClientId, - IFNULL(vShipped,vLanded), + vShipped, a.id, vAgencyModeFk, a.nickname, vWarehouseFk, IF(vRouteFk,vRouteFk,NULL), vCompanyFk, - vLanded, + vlanded, vZoneFk FROM address a JOIN agencyMode am ON am.id = a.agencyModeFk @@ -50543,9 +51373,10 @@ proc: BEGIN DECLARE vAddressFk INT; DECLARE vLanded DATE; DECLARE vIsTicketEditable BOOLEAN; + DECLARE vZoneFk INTEGER; - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE - INTO vIsTicketEditable + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket WHERE id = vTicketFk; @@ -50567,7 +51398,7 @@ proc: BEGIN WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -50625,10 +51456,11 @@ proc: BEGIN DECLARE vAgencyModeFk INT; DECLARE vAddressFk INT; DECLARE vLanded DATE; + DECLARE vZoneFk INTEGER; IF vIsTicketEditable IS NULL THEN - SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE - INTO vIsTicketEditable + SELECT (IFNULL(ts.alertLevel,0) >0 or IFNULL(t.refFk,"") != "") = FALSE, t.zoneFk + INTO vIsTicketEditable, vZoneFk FROM ticket t LEFT JOIN ticketState ts ON t.id = ts.ticket WHERE id = vTicketFk; END IF; @@ -50650,7 +51482,7 @@ proc: BEGIN WHERE s.ticketFk = vTicketFk GROUP BY s.itemFk; - CALL vn.ticketComponentCalculate(vAddressFk,vAgencyModeFk); + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -50687,15 +51519,15 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `timeBusiness_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - -- BERNAT: WORKING IN THIS FILE + /** * Horas que debe trabajar un empleado según contrato y día. * @param vDatedFrom workerTimeControl @@ -50707,7 +51539,9 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.timeBusinessCalculate; DROP TEMPORARY TABLE IF EXISTS tmp.businessFullTime; - + + CALL rangeDateInfo(vDatedFrom, vDatedTo); + CREATE TEMPORARY TABLE tmp.timeBusinessCalculate SELECT dated, businessFk, @@ -50724,7 +51558,7 @@ BEGIN type, permissionrate, hoursWeek - FROM(SELECT t.dated, + FROM(SELECT rd.dated, b.business_id businessFk, w.userFk, bl.department_id departmentFk, @@ -50734,8 +51568,8 @@ BEGIN cs.type, cs.permissionRate, cl.hours_week hoursWeek - FROM vn.time t - LEFT JOIN postgresql.business b ON t.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) + FROM tmp.rangeDate rd + LEFT JOIN postgresql.business b ON rd.dated BETWEEN b.date_start AND ifnull(b.date_end, vDatedTo ) LEFT JOIN postgresql.profile AS pr ON b.client_id = pr.profile_id LEFT JOIN postgresql.person AS p ON pr.person_id = p.person_id LEFT JOIN vn.worker AS w ON p.id_trabajador = w.id @@ -50745,10 +51579,10 @@ BEGIN LEFT JOIN postgresql.professional_category AS pc ON bl.professional_category_id = pc.professional_category_id LEFT JOIN postgresql.workcenter AS wc ON bl.workcenter_id = wc.workcenter_id LEFT JOIN postgresql.calendar_labour_type AS cl ON bl.calendar_labour_type_id = cl.calendar_labour_type_id - LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(t.dated)+1 - LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = t.dated + LEFT JOIN postgresql.journey AS j ON j.business_id = b.business_id and j.day_id=WEEKDAY(rd.dated)+1 + LEFT JOIN postgresql.calendar_employee ce ON ce.business_id=b.business_id and ce.date = rd.dated LEFT JOIN postgresql.calendar_state cs ON cs.calendar_state_id = ce.calendar_state_id - WHERE t.dated BETWEEN vDatedFrom AND vDatedTo + WHERE rd.dated BETWEEN vDatedFrom AND vDatedTo GROUP BY w.userFk,dated )sub; @@ -50778,6 +51612,7 @@ BEGIN t.type = 'Festivo' WHERE t.type IS NULL; +DROP TEMPORARY TABLE IF EXISTS tmp.rangeDate; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50949,34 +51784,38 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `timeControl_calculate`(vDatedFrom DATETIME, vDatedTo DATETIME) BEGIN - -/** - * Horas totales trabajadas a partir de las fichadas, tiene en cuenta los descansos y fichadas impares - * (si hay fichadas impares nop devuelve info) - * @param vDatedFrom workerTimeControl - * @param vDatedTo workerTimeControl - * @table tmp.user(userFk) - * @return tmp.timeControlCalculate - */ - - DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; - - CREATE TEMPORARY TABLE tmp.timeControlCalculate - SELECT userFk, - dated, - IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, - SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, - @timeWork / 3600 timeWorkDecimal - FROM (SELECT wtc.userFk, - DATE(wtc.timed) dated, - SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))) timeWork - FROM vn.workerTimeControl wtc - JOIN tmp.`user` w ON w.userFk = wtc.userFk - WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo - GROUP BY wtc.userFk,dated - ORDER BY userFk,dated - )sub - WHERE sub.timeWork > 0; + SET @vIsOdd := TRUE; + SET @vUser := NULL; + SET @vDated := NULL; + + DROP TEMPORARY TABLE IF EXISTS tmp.timeControlCalculate; + + CREATE TEMPORARY TABLE tmp.timeControlCalculate + SELECT userFk, + dated, + IF( timeWork >= 18000, @timeWork:=timeWork + 1200, @timeWork:=timeWork) timeWorkSeconds, + SEC_TO_TIME(@timeWork ) timeWorkSexagesimal, + @timeWork / 3600 timeWorkDecimal + FROM (SELECT SUM(timeWork) timeWork, + userFk, + dated + FROM (SELECT IF(@vUser = wtc.userFk, @vUser :=@vUser, @vUser := wtc.userFk ), + IF(@vIsOdd, @vIsOdd := FALSE, @vIsOdd := TRUE ), + IF(direction='in', @vIsOdd := TRUE, @vIsOdd := @vIsOdd ), + IF(@vIsOdd, @vLastTimed:=UNIX_TIMESTAMP(timed),@vLastTimed:=@vLastTimed), + IF(@vIsOdd, 0, UNIX_TIMESTAMP(timed)-@vLastTimed) timeWork, + IF(direction='in', @vDated := DATE(wtc.timed), @vDated :=@vDated) dated, + wtc.userFk, + wtc.timed timed, + direction + FROM workerTimeControl wtc + JOIN tmp.`user` w ON w.userFk = wtc.userFk + WHERE wtc.timed BETWEEN vDatedFrom AND vDatedTo + ORDER BY userFk, timed + ) sub + GROUP BY userFk, dated + ORDER BY userFk, dated + )sub2; END ;; DELIMITER ; @@ -52401,16 +53240,17 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `workerTimeControl_add`(IN vUserFk INT, IN vWarehouseFk INT, IN vTimed DATETIME, IN vIsManual BOOL) BEGIN - SELECT vn.workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); - CALL vn.workerTimeControlSOWP(vUserFk, vTimed); + + + SELECT workerTimeControl_add(vUserFk,vWarehouseFk,vTimed,vIsManual); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52511,6 +53351,9 @@ proc: BEGIN DECLARE vTimedWorked INT; DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; DECLARE vDepartmentFk INT; + DECLARE vTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vBody VARCHAR(255) DEFAULT NULL; SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax @@ -52524,13 +53367,25 @@ proc: BEGIN SELECT MAX(timed) INTO vLastOut FROM vn.workerTimeControl WHERE userFk = vUserFk - AND direction = 'out'; + AND direction = 'out'; + + SELECT email INTO vTo + FROM vn.worker w + WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); + + SELECT CONCAT(firstName,' ',lastName) INTO vUserName + FROM vn.worker w + WHERE w.id = vUserFk; + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA -- VERIFICAR DESCANSO DIARIO IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN SELECT "Descansos 12 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52541,7 +53396,10 @@ proc: BEGIN AND timed >= vLastIn ) THEN SELECT "Dias con fichadas impares" AS problem; - LEAVE proc; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; END IF; -- VERIFICAR VACACIONES @@ -52559,7 +53417,11 @@ proc: BEGIN IF(LENGTH(vCalendarStateType)) THEN SELECT vCalendarStateType AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; + END IF; @@ -52574,7 +53436,11 @@ proc: BEGIN AND IFNULL(b.date_end,vDated) >= vDated ) = 0 THEN SELECT "No hay un contrato en vigor" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; + END IF; -- VERIFICAR DESCANSO SEMANAL @@ -52593,6 +53459,9 @@ proc: BEGIN IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA SELECT "Descansos 36 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52609,6 +53478,9 @@ proc: BEGIN IF vTimedWorked > vDayWorkMax THEN SELECT "Jornadas" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; @@ -52624,7 +53496,10 @@ proc: BEGIN WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk ) = 0 THEN SELECT "No perteneces a este departamento." AS problem; - LEAVE proc; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; + CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; END IF; END IF; @@ -53532,98 +54407,7 @@ BEGIN * @select Listado de agencias disponibles */ - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; - CREATE TEMPORARY TABLE tmp.zoneGetAgency - (INDEX (agencyModeFk)) ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM ( - SELECT am.id agencyModeFk, - am.name agencyMode, - am.description, - am.deliveryMethodFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - zi.isIncluded, - z.warehouseFk, - z.id zoneFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - JOIN agencyMode am ON am.id = z.agencyModeFk - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND TIMESTAMPADD(DAY,-z.travelingDays, vLanded) >= CURDATE() - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC, zi.isIncluded DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - ORDER BY shipped) t - GROUP BY agencyModeFk; -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 DROP PROCEDURE IF EXISTS `zoneGetFirstShipped` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetFirstShipped`(vAgencyModeFk INT, vAddress INT, vWarehouseFk INT) -BEGIN -/** -* Devuelve la primera fecha de envio disponible para una agencia en una direccion y un warehouse -* -* @param vAgencyMode id de la agencia en vn.agencyMode -* @param vAddress id de la direccion -* @param vWarehouse id del warehouse -* @return vShipped la primera fecha disponible y vLanded la fecha de llegada/recojida -*/ - - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddress - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - SELECT * FROM ( - SELECT TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) shipped, - zc.delivered landed, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - AND TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) >= CURDATE() - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, zc.delivered) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY landed ASC, zgFather.depth DESC) t - HAVING isIncluded > 0 LIMIT 1; + CALL zone_getAgency(vAddress,vLanded); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53634,58 +54418,23 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetLanded`(vShipped DATE, vAddress INT, vAgencyMode INT, vWarehouse INT) BEGIN /** * Devuelve una tabla temporal con el dia de recepcion para vShipped. * * @param vShipped Fecha de preparacion de mercancia -* @param vAddressFk Id de consignatario, %NULL para recogida -* @param vAgencyModeFk Id agencia +* @param vAddress Id de consignatario, %NULL para recogida +* @param vAgencyMode Id agencia * @table tmp.zoneGetLanded Datos de recepción */ - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; - CREATE TEMPORARY TABLE tmp.zoneGetLanded - ENGINE = MEMORY - SELECT - id zoneFk, - vShipped shipped, - delivered landed, - vWarehouseFk warehouseFk, - agencyModeFk, - isIncluded - FROM ( - SELECT zi.isIncluded, zc.delivered, z.id, z.agencyModeFk - FROM vn.zoneGeo zgSon - JOIN vn.zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = TIMESTAMPADD(DAY,z.travelingDays, vShipped) - AND IF(vShipped = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - ORDER BY zgFather.depth DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - LIMIT 1; + CALL zone_getLanded(vShipped,vAddress,vAgencyMode,vWarehouse); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53696,15 +54445,16 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetShipped`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) BEGIN /** + * OBSOLETO usar zone_getShippedWarehouse * Devuelve la mínima fecha de envía para cada warehouse * * @param vLanded La fecha de recepcion @@ -53712,41 +54462,10 @@ BEGIN * @param vAgencyModeFk Id de la agencia * @return tmp.zoneGetShipped */ - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - SELECT * FROM ( - SELECT * FROM ( - SELECT z.id zoneFk, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - vLanded landed, - vWarehouseFk warehouseFk, - z.agencyModeFk, - zi.isIncluded - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND z.warehouseFk = vWarehouseFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, zgFather.depth DESC, isIncluded DESC) t - GROUP BY zoneFk - HAVING isIncluded > 0 - ORDER BY shipped) - t - GROUP BY agencyModeFk; + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); + + SELECT * FROM tmp.zoneGetShipped WHERE warehouseFk <> vWarehouseFk; + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53773,40 +54492,7 @@ BEGIN * @param vAgencyModeFk Id de la agencia * @return tmp.zoneGetShipped */ - - DECLARE vGeoFk INT; - - SELECT p.geoFk INTO vGeoFk - FROM address a - JOIN town t ON t.provinceFk = a.provinceFk - JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode - WHERE a.id = vAddressFk - ORDER BY (a.city SOUNDS LIKE t.`name`) DESC - LIMIT 1; - - - DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; - CREATE TEMPORARY TABLE tmp.zoneGetShipped - ENGINE = MEMORY - SELECT * FROM ( - SELECT * FROM ( - SELECT z.id, - TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, - zi.isIncluded,z.warehouseFk - FROM zoneGeo zgSon - JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt - JOIN zoneIncluded zi ON zi.geoFk = zgFather.id - JOIN zone z ON z.id = zi.zoneFk - JOIN zoneCalendar zc ON zc.zoneFk = z.id - WHERE zgSon.`id` = vGeoFk - AND zc.delivered = vLanded - AND z.agencyModeFk = vAgencyModeFk - AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) - ORDER BY z.id, shipped ASC, zgFather.depth DESC, zi.isIncluded DESC) t - GROUP BY warehouseFk, id - HAVING isIncluded > 0 - ORDER BY shipped) t - GROUP BY warehouseFk; + CALL zone_getShippedWarehouse(vLanded, vAddressFk, vAgencyModeFk); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -53877,7 +54563,272 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; -/*!50003 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!50003 DROP PROCEDURE IF EXISTS `zoneGetWarehouse__` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zoneGetWarehouse__`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** +* Devuelve el listado de agencias disponibles para la fecha, + * dirección y warehouse pasadas + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + DECLARE vGeoFk INT; + + SELECT p.geoFk INTO vGeoFk + FROM address a + JOIN town t ON t.provinceFk = a.provinceFk + JOIN postCode p ON p.townFk = t.id AND p.code = a.postalCode + WHERE a.id = vAddress + ORDER BY (a.city SOUNDS LIKE t.`name`) DESC + LIMIT 1; + + SELECT * FROM ( + SELECT * FROM ( + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-z.travelingDays, vLanded) shipped, + z.warehouseFk, + zi.isIncluded, + z.id zoneFk + FROM zoneGeo zgSon + JOIN zoneGeo zgFather ON zgSon.lft BETWEEN zgFather.lft AND zgFather.rgt + JOIN zoneIncluded zi ON zi.geoFk = zgFather.id + JOIN zone z ON z.id = zi.zoneFk + JOIN zoneCalendar zc ON zc.zoneFk = z.id + JOIN agencyMode am ON am.id = z.agencyModeFk + WHERE zgSon.`id` = vGeoFk + AND delivered = vLanded + AND z.warehouseFk = vWarehouse + AND IF(TIMESTAMPADD(DAY,-z.travelingDays, vLanded) = CURDATE(), hour(now()) < hour(z.`hour`),TRUE) + ORDER BY z.id, zgFather.depth DESC) t + GROUP BY zoneFk + HAVING isIncluded > 0) t + GROUP BY agencyModeFk; + +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 DROP PROCEDURE IF EXISTS `zone_getAgency` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAgency`(vAddress INT, vLanded DATE) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha + * y dirección pasadas. + * + * @param vAddress Id de dirección de envío, %NULL si es recogida + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetAgency; + CREATE TEMPORARY TABLE tmp.zoneGetAgency + (INDEX (agencyModeFk)) ENGINE = MEMORY + SELECT am.name agencyMode, + am.description, + z.agencyModeFk, + am.deliveryMethodFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + TRUE isIncluded, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + GROUP BY agencyModeFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +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 DROP PROCEDURE IF EXISTS `zone_getAvailable` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getAvailable`(vAddress INT, vLanded DATE) +BEGIN + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT * FROM tmp.zoneOption; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +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 DROP PROCEDURE IF EXISTS `zone_getEvents` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getEvents`( + vProvinceFk INT, + vPostCode VARCHAR(255), + vAgencyModeFk INT) +BEGIN +/** + * Returns available events for the passed province/postcode and agency. + * + * @param vAgencyModeFk The agency mode id + * @param vProvinceFk The province id + * @param vPostCode The postcode or %NULL to use the province + */ + DECLARE vGeoFk INT; + + IF vPostCode IS NOT NULL THEN + SELECT p.geoFk INTO vGeoFk + FROM postCode p + JOIN town t ON t.id = p.townFk + WHERE p.`code` = vPostCode + AND t.provinceFk = vProvinceFk; + ELSE + SELECT geoFk INTO vGeoFk + FROM province + WHERE id = vProvinceFk; + END IF; + + CALL zone_getFromGeo(vGeoFk); + + IF vAgencyModeFk IS NOT NULL THEN + DELETE t FROM tmp.zone t + JOIN zone z ON z.id = t.id + WHERE z.agencyModeFk != vAgencyModeFk; + END IF; + + SELECT e.zoneFk, e.`type`, e.dated, e.`started`, e.`ended`, e.weekDays + FROM tmp.zone t + JOIN zoneEvent e ON e.zoneFk = t.id; + + SELECT e.zoneFk, e.dated + FROM tmp.zone t + JOIN zoneExclusion e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE tmp.zone; +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 DROP PROCEDURE IF EXISTS `zone_getFromGeo` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getFromGeo`(vGeoFk INT) +BEGIN +/** + * Returns all zones which have the passed geo included. + * + * @param vGeoFk The geo id + * @return tmp.zone(id) The list of zones + */ + DECLARE vChildFk INT DEFAULT vGeoFk; + DECLARE vParentFk INT; + DECLARE vLevel INT DEFAULT 1; + + DROP TEMPORARY TABLE IF EXISTS tNodes; + CREATE TEMPORARY TABLE tNodes + (PRIMARY KEY (id)) + ENGINE = MEMORY + SELECT vGeoFk id, vLevel `level`; + + myLoop: LOOP + SELECT parentFk INTO vParentFk + FROM zoneGeo + WHERE id = vChildFk; + + SET vChildFk = vParentFk; + SET vLevel = vLevel + 1; + + INSERT IGNORE INTO tNodes + SELECT vChildFk, vLevel + FROM DUAL + WHERE vChildFk IS NOT NULL; + + IF ROW_COUNT() = 0 THEN + LEAVE myLoop; + END IF; + END LOOP; + + DROP TEMPORARY TABLE IF EXISTS tmp.zone; + CREATE TEMPORARY TABLE tmp.zone + (INDEX (id)) + ENGINE = MEMORY + SELECT id FROM ( + SELECT zoneFk id, isIncluded + FROM ( + SELECT i.zoneFk, i.isIncluded + FROM tNodes n + JOIN zoneIncluded i ON i.geoFk = n.id + ORDER BY zoneFk, n.`level` + ) t + GROUP BY id HAVING isIncluded + ) t; + + DROP TEMPORARY TABLE tNodes; +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 DROP PROCEDURE IF EXISTS `zone_getLanded` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -53887,12 +54838,59 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLanded`(vShipped DATE, vAddressFk INT, vAgencyModeFk INT, vWarehouseFk INT) +BEGIN +/** +* Devuelve una tabla temporal con el dia de recepcion para vShipped. +* +* @param vShipped Fecha de preparacion de mercancia +* @param vAddressFk Id de consignatario, %NULL para recogida +* @param vAgencyModeFk Id agencia +* @param vWarehouseFk vWarehouseFk +* @table tmp.zoneGetLanded Datos de recepción +*/ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForShipment(vShipped); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetLanded; + CREATE TEMPORARY TABLE tmp.zoneGetLanded + ENGINE = MEMORY + SELECT vWarehouseFk warehouseFk, + TIMESTAMPADD(DAY,zo.travelingDays, vShipped) landed, + zo.zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN zoneWarehouse zw ON zw.zoneFk = z.id + WHERE agencyModeFk = vAgencyModeFk + AND zw.warehouseFk = vWarehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; + +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 DROP PROCEDURE IF EXISTS `zone_getLeaves` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `zone_getLeaves`( vSelf INT, vParentFk INT, vSearch VARCHAR(255) ) -BEGIN +BEGIN DECLARE vIsNumber BOOL; DECLARE vIsSearch BOOL DEFAULT vSearch IS NOT NULL AND vSearch != ''; @@ -53976,6 +54974,260 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `zone_getOptionsForLanding` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForLanding`(vLanded DATE) +BEGIN +/** + * Gets computed options for the passed zones and delivery date. + * + * @table tmp.zones(id) The zones ids + * @param vLanded The delivery date + * @return tmp.zoneOption The computed options + */ + DECLARE vHour TIME DEFAULT TIME(NOW()); + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.travelingDays, z.travelingDays) travelingDays, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + WHERE ( + e.`type` = 'day' + AND e.dated = vLanded + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(vLanded)) + AND (e.`started` IS NULL OR vLanded >= e.`started`) + AND (e.`ended` IS NULL OR vLanded <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = vLanded; + + DELETE FROM tTemp + WHERE (@shipped := TIMESTAMPADD(DAY, -travelingDays, vLanded)) < CURDATE() + OR @shipped = CURDATE() AND vHour > `hour`; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE tTemp; +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 DROP PROCEDURE IF EXISTS `zone_getOptionsForShipment` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getOptionsForShipment`(vShipped DATE) +BEGIN +/** + * Gets computed options for the passed zones and shipping date. + * + * @table tmp.zones(id) The zones ids + * @param vShipped The shipping date + * @return tmp.zoneOption(zoneFk, hour, travelingDays, price, bonus, specificity) The computed options + */ + DROP TEMPORARY TABLE IF EXISTS tLandings; + CREATE TEMPORARY TABLE tLandings + (INDEX (eventFk)) + ENGINE = MEMORY + SELECT e.id eventFk, + @travelingDays := IFNULL(e.travelingDays, z.travelingDays) travelingDays, + TIMESTAMPADD(DAY, @travelingDays, vShipped) landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id; + + DROP TEMPORARY TABLE IF EXISTS tTemp; + CREATE TEMPORARY TABLE tTemp + ENGINE = MEMORY + SELECT t.id zoneFk, + IFNULL(TIME(e.`hour`), TIME(z.`hour`)) `hour`, + IFNULL(e.price, z.price) price, + IFNULL(e.bonus, z.bonus) bonus, + CASE + WHEN e.`type` = 'day' + THEN 1 + WHEN e.`type` = 'range' + THEN 2 + ELSE 3 + END specificity, + l.travelingDays, + l.landed + FROM tmp.zone t + JOIN zone z ON z.id = t.id + JOIN zoneEvent e ON e.zoneFk = t.id + JOIN tLandings l ON l.eventFk = e.id + WHERE ( + e.`type` = 'day' + AND e.`dated` = l.landed + ) OR ( + e.`type` != 'day' + AND e.weekDays & (1 << WEEKDAY(l.landed)) + AND (e.`started` IS NULL OR l.landed >= e.`started`) + AND (e.`ended` IS NULL OR l.landed <= e.`ended`) + ); + + DELETE t FROM tTemp t + JOIN zoneExclusion e + ON e.zoneFk = t.zoneFk AND e.`dated` = t.landed; + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneOption; + CREATE TEMPORARY TABLE tmp.zoneOption + ENGINE = MEMORY + SELECT * + FROM ( + SELECT * FROM tTemp + ORDER BY zoneFk, specificity + ) t + GROUP BY zoneFk; + + DROP TEMPORARY TABLE + tTemp, + tLandings; +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 DROP PROCEDURE IF EXISTS `zone_getShippedWarehouse` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getShippedWarehouse`(vLanded DATE, vAddressFk INT, vAgencyModeFk INT) +BEGIN +/** + * Devuelve la mínima fecha de envío para cada warehouse + * + * @param vLanded La fecha de recepcion + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.zoneGetShipped + */ + + CALL zone_getFromGeo(address_getGeo(vAddressFk)); + CALL zone_getOptionsForLanding(vLanded); + + DROP TEMPORARY TABLE IF EXISTS tmp.zoneGetShipped; + CREATE TEMPORARY TABLE tmp.zoneGetShipped + ENGINE = MEMORY + SELECT * FROM ( + SELECT zo.zoneFk, + TIMESTAMPADD(DAY,-zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.agencyModeFk + FROM tmp.zoneOption zo + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + JOIN zone z ON z.id = zo.zoneFk + WHERE z.agencyModeFk = vAgencyModeFk + ORDER BY shipped) t + GROUP BY warehouseFk; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +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 DROP PROCEDURE IF EXISTS `zone_getWarehouse` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `zone_getWarehouse`(vAddress INT, vLanded DATE, vWarehouse INT) +BEGIN +/** + * Devuelve el listado de agencias disponibles para la fecha, + * dirección y almacén pasados. + * + * @param vAddress + * @param vWarehouse warehouse + * @param vLanded Fecha de recogida + * @select Listado de agencias disponibles + */ + + CALL zone_getFromGeo(address_getGeo(vAddress)); + CALL zone_getOptionsForLanding(vLanded); + + SELECT am.id agencyModeFk, + am.name agencyMode, + am.description, + am.deliveryMethodFk, + TIMESTAMPADD(DAY, -zo.travelingDays, vLanded) shipped, + zw.warehouseFk, + z.id zoneFk + FROM tmp.zoneOption zo + JOIN zone z ON z.id = zo.zoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + JOIN zoneWarehouse zw ON zw.zoneFk = zo.zoneFk + WHERE zw.warehouseFk + GROUP BY z.agencyModeFk + ORDER BY agencyMode; + + DROP TEMPORARY TABLE + tmp.zone, + tmp.zoneOption; +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 */ ; -- -- Current Database: `vncontrol` @@ -54038,7 +55290,6 @@ CREATE TABLE `inter` ( KEY `ticket` (`Id_Ticket`), KEY `inter_state` (`state_id`), KEY `inter_id` (`Id_Ticket`,`inter_id`) USING BTREE, - CONSTRAINT `currante` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE, CONSTRAINT `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn`.`ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn`.`state` (`id`) ON UPDATE CASCADE, CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn`.`worker` (`id`) ON UPDATE CASCADE @@ -55263,7 +56514,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable` from `bi`.`tarifa_componentes` `t` */; +/*!50001 VIEW `component` AS select `t`.`Id_Componente` AS `id`,`t`.`Componente` AS `name`,`t`.`tarifa_componentes_series_id` AS `typeFk`,`t`.`tarifa_class` AS `classRate`,`t`.`tax` AS `tax`,`t`.`is_renewable` AS `isRenewable`,`t`.`code` AS `code` from `bi`.`tarifa_componentes` `t` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -55996,9 +57247,9 @@ USE `vn`; /*!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 = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ /*!50001 VIEW `saleFreight` AS select `s`.`ticketFk` AS `ticketFk`,`t`.`clientFk` AS `clientFk`,`t`.`routeFk` AS `routeFk`,`s`.`id` AS `saleFk`,`t`.`zoneFk` AS `zoneFk`,`t`.`companyFk` AS `companyFk`,`t`.`shipped` AS `shipped`,`zc`.`price` AS `price`,((((`s`.`quantity` * `r`.`cm3`) * `zc`.`price`) * `i`.`compression`) / `cb`.`volume`) AS `freight`,(((`s`.`quantity` * `r`.`cm3`) * `i`.`compression`) / 1000000) AS `volume` from (((((`vn`.`sale` `s` join `vn`.`item` `i` on((`i`.`id` = `s`.`itemFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`packaging` `cb` on((`cb`.`id` = '94'))) join `bi`.`rotacion` `r` on(((`r`.`Id_Article` = `s`.`itemFk`) and (`r`.`warehouse_id` = `t`.`warehouseFk`)))) join `vn`.`zoneCalendar` `zc` on(((`zc`.`zoneFk` = `t`.`zoneFk`) and (`zc`.`delivered` = `t`.`landed`)))) */; @@ -56381,4 +57632,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-16 10:31:31 +-- Dump completed on 2019-12-20 11:02:02 diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index 0f7810ed2..ea6a787b0 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -56,6 +56,7 @@ module.exports = Self => { ]; for (const key in params) { + console.log('key', key); if (validUpdateParams.indexOf(key) === -1) throw new UserError(`You don't have enough privileges to do that`); } From 3d4fc9c18ef589fccaaa1b86095fa6a1b2ce43c3 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Mon, 23 Dec 2019 08:05:58 +0100 Subject: [PATCH 46/59] #1963 Entry & zone style changes --- e2e/helpers/selectors.js | 2 +- front/core/components/chip/style.scss | 19 ++++++++++- modules/agency/front/location/style.scss | 13 +++++--- modules/item/front/last-entries/index.html | 32 +++++++++---------- .../ticket/specs/deleteStowaway.spec.js | 2 +- 5 files changed, 45 insertions(+), 23 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index d752b265f..bb23c9d96 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -360,7 +360,7 @@ export default { goBackToModuleIndexButton: 'vn-ticket-descriptor a[ui-sref="ticket.index"]', moreMenu: 'vn-ticket-descriptor vn-icon-menu[icon=more_vert]', moreMenuAddStowaway: '.vn-drop-down.shown li[name="Add stowaway"]', - moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Remove stowaway"]', + moreMenuDeleteStowawayButton: '.vn-drop-down.shown li[name="Delete stowaway"]', moreMenuAddToTurn: '.vn-drop-down.shown li[name="Add turn"]', moreMenuDeleteTicket: '.vn-drop-down.shown li[name="Delete ticket"]', moreMenuMakeInvoice: '.vn-drop-down.shown li[name="Make invoice"]', diff --git a/front/core/components/chip/style.scss b/front/core/components/chip/style.scss index 5840ecdf1..3778c62b9 100644 --- a/front/core/components/chip/style.scss +++ b/front/core/components/chip/style.scss @@ -14,8 +14,25 @@ vn-chip { &.colored { background-color: $color-main; - color: $color-font-dark; + color: $color-font-bg; } + &.notice { + background-color: $color-notice-medium + } + &.success { + background-color: $color-success-medium; + } + &.warning { + background-color: $color-main-medium; + } + &.alert { + background-color: $color-alert-medium; + } + &.message { + color: $color-font-dark; + background-color: $color-bg-dark + } + & > div { display: flex; align-items: center; diff --git a/modules/agency/front/location/style.scss b/modules/agency/front/location/style.scss index 4972a5d29..2316a2622 100644 --- a/modules/agency/front/location/style.scss +++ b/modules/agency/front/location/style.scss @@ -1,14 +1,19 @@ @import "variables"; vn-treeview-child { - .content > .vn-check:not(.indeterminate) { - color: $color-button; + .content > .vn-check:not(.indeterminate):not(.checked) { + color: $color-alert; & > .btn { - border-color: $color-button; + border-color: $color-alert; } } .content > .vn-check.checked { - color: $color-button; + color: $color-notice; + + & > .btn { + background-color: $color-notice; + border-color: $color-notice + } } } \ No newline at end of file diff --git a/modules/item/front/last-entries/index.html b/modules/item/front/last-entries/index.html index a7046e17b..28ba9989b 100644 --- a/modules/item/front/last-entries/index.html +++ b/modules/item/front/last-entries/index.html @@ -43,27 +43,27 @@ disabled="true"> - {{entry.warehouse| dashIfEmpty}} - {{entry.landed | date:'dd/MM/yyyy HH:mm'}} - {{entry.entryFk | dashIfEmpty}} - {{entry.price2 | dashIfEmpty}} - {{entry.price3 | dashIfEmpty}} + {{::entry.warehouse| dashIfEmpty}} + {{::entry.landed | date:'dd/MM/yyyy HH:mm'}} + {{::entry.entryFk | dashIfEmpty}} + {{::entry.price2 | dashIfEmpty}} + {{::entry.price3 | dashIfEmpty}} {{entry.stickers | dashIfEmpty}} - - {{entry.packing | dashIfEmpty}} - + + {{::entry.packing | dashIfEmpty}} + - - {{entry.grouping | dashIfEmpty}} - + + {{::entry.grouping | dashIfEmpty}} + - {{entry.stems | dashIfEmpty}} - {{entry.quantity}} - {{entry.buyingValue | dashIfEmpty}} - {{entry.packageFk | dashIfEmpty}} - {{entry.supplier | dashIfEmpty}} + {{::entry.stems | dashIfEmpty}} + {{::entry.quantity}} + {{::entry.buyingValue | dashIfEmpty}} + {{::entry.packageFk | dashIfEmpty}} + {{::entry.supplier | dashIfEmpty}} diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js index d5a10ac3b..3c8097e37 100644 --- a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -1,6 +1,6 @@ const app = require('vn-loopback/server/server'); -fdescribe('ticket deleteStowaway()', () => { +describe('ticket deleteStowaway()', () => { const shipId = 16; const stowawayId = 17; From 0827b998a1f5dc2fe07c09c3fbabbfde36aae073 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Mon, 23 Dec 2019 15:15:58 +0100 Subject: [PATCH 47/59] update structure sql --- .../00-catalog_componentCalculate.sql | 254 + .../00-manaSpellersRequery.sql | 70 + db/dump/structure.sql | 6776 ++++------------- db/export-structure.sh | 1 - .../back/methods/client/updateFiscalData.js | 1 - modules/worker/back/models/worker-mana.json | 2 +- 6 files changed, 1984 insertions(+), 5120 deletions(-) create mode 100644 db/changes/10130-christmas/00-catalog_componentCalculate.sql create mode 100644 db/changes/10130-christmas/00-manaSpellersRequery.sql diff --git a/db/changes/10130-christmas/00-catalog_componentCalculate.sql b/db/changes/10130-christmas/00-catalog_componentCalculate.sql new file mode 100644 index 000000000..6eb30bbfd --- /dev/null +++ b/db/changes/10130-christmas/00-catalog_componentCalculate.sql @@ -0,0 +1,254 @@ +DROP procedure IF EXISTS `vn`.`catalog_componentCalculate`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`catalog_componentCalculate`( + vZoneFk INT, + vAddressFk INT, + vShipped DATE) +proc: BEGIN +/** + * Calcula los componentes de los articulos de tmp.ticketLot + * + * @param vZoneFk para calcular el transporte + * @param vAgencyModeFk Id del modo de agencia + * @param tmp.ticketLot (warehouseFk,available,itemFk,buyFk) + * + * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, + * packing, grouping, groupingMode, buyFk, typeFk) + * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) + */ + DECLARE vClientFk INT; + DECLARE vGeneralInflationCoefficient INT DEFAULT 1; + DECLARE vMinimumDensityWeight INT DEFAULT 167; + DECLARE vBoxFreightItem INT DEFAULT 71; + DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; + DECLARE vSpecialPriceComponent INT DEFAULT 10; + DECLARE vDeliveryComponent INT DEFAULT 15; + DECLARE vRecoveryComponent INT DEFAULT 17; + DECLARE vSellByPacketComponent INT DEFAULT 22; + DECLARE vBuyValueComponent INT DEFAULT 28; + DECLARE vMarginComponent INT DEFAULT 29; + DECLARE vDiscountLastItemComponent INT DEFAULT 32; + DECLARE vExtraBaggedComponent INT DEFAULT 38; + DECLARE vManaAutoComponent INT DEFAULT 39; + + SELECT volume INTO vBoxVolume + FROM vn.packaging + WHERE id = '94'; + + SELECT clientFk INTO vClientFK + FROM address + WHERE id = vAddressFk; + + SET @rate2 := 0; + SET @rate3 := 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; + CREATE TEMPORARY TABLE tmp.ticketComponentCalculate + (PRIMARY KEY (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT + tl.itemFk, tl.warehouseFk, tl.available, + IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, + IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, + IFNULL(pf.rate3, 0) AS minPrice, + IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.`grouping`, b.`grouping`) `grouping`, + ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, + tl.buyFk, + i.typeFk, + IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping + FROM tmp.ticketLot tl + JOIN buy b ON b.id = tl.buyFk + JOIN item i ON i.id = tl.itemFk + JOIN itemType it ON it.id = i.typeFk + LEFT JOIN itemCategory ic ON ic.id = it.categoryFk + LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk + LEFT JOIN ( + SELECT * FROM ( + SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk + FROM priceFixed pf + JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) + WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC + ) tpf + GROUP BY tpf.itemFk, tpf.warehouseFk + ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk + WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponent; + CREATE TEMPORARY TABLE tmp.ticketComponent ( + `warehouseFk` INT UNSIGNED NOT NULL, + `itemFk` INT NOT NULL, + `componentFk` INT UNSIGNED NOT NULL, + `cost` DECIMAL(10,4) NOT NULL, + INDEX `itemWarehouse` USING BTREE (`itemFk` ASC, `warehouseFk` ASC), + UNIQUE INDEX `itemWarehouseComponent` (`itemFk` ASC, `warehouseFk` ASC, `componentFk` ASC)); + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vBuyValueComponent, + b.buyingValue + b.freightValue + b.packageValue + b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) + SELECT + tcc.warehouseFk, + tcc.itemFk, + vMarginComponent, + tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; + CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY + SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk + FROM tmp.ticketComponent tc + GROUP BY tc.itemFk, warehouseFk; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.recobro, 0.25), 3) + FROM tmp.ticketComponentBase tcb + JOIN bi.claims_ratio cr ON cr.Id_Cliente = vClientFk + WHERE cr.recobro > 0.009; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto + FROM tmp.ticketComponentBase tcb + JOIN `client` c on c.id = vClientFk + JOIN workerMana wm ON c.salesPersonFk = wm.workerFk + WHERE wm.isPricesModifierActivated + HAVING manaAuto <> 0; + + INSERT INTO tmp.ticketComponent + SELECT tcb.warehouseFk, + tcb.itemFk, + cr.id, + GREATEST(IFNULL(ROUND(tcb.base * cr.tax, 4), 0), tcc.minPrice - tcc.rate3) + FROM tmp.ticketComponentBase tcb + JOIN componentRate cr + JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE cr.id = vDiscountLastItemComponent AND cr.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 + FROM tmp.ticketComponentCalculate tcc + JOIN buy b ON b.id = tcc.buyFk + LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk + WHERE sp.value IS NULL; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFK, + tcc.itemFk, + vDeliveryComponent, + vGeneralInflationCoefficient + * ROUND(( + i.compression + * r.cm3 + * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) + * IFNULL((z.price - z.bonus) + * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 + ) cost + FROM tmp.ticketComponentCalculate tcc + JOIN item i ON i.id = tcc.itemFk + JOIN zone z ON z.id = vZoneFk + JOIN agencyMode am ON am.id = z.agencyModeFk + LEFT JOIN bi.rotacion r ON r.warehouse_id = tcc.warehouseFk + AND r.Id_Article = tcc.itemFk + HAVING cost <> 0; + + IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost + FROM tmp.ticketComponentCalculate tcc + JOIN vn.addressForPackaging ap + WHERE ap.addressFk = vAddressFk; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; + CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY + SELECT * FROM tmp.ticketComponent; + + INSERT INTO tmp.ticketComponent + SELECT tcc.warehouseFk, + tcc.itemFk, + vSpecialPriceComponent, + sp.value - SUM(tcc.cost) sumCost + FROM tmp.ticketComponentCopy tcc + JOIN componentRate cr ON cr.id = tcc.componentFk + JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk + WHERE cr.classRate IS NULL + GROUP BY tcc.itemFk, tcc.warehouseFk + HAVING ABS(sumCost) > 0.001; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; + CREATE TEMPORARY TABLE tmp.ticketComponentSum + (INDEX (itemFk, warehouseFk)) + ENGINE = MEMORY + SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, cr.classRate + FROM tmp.ticketComponent tc + JOIN componentRate cr ON cr.id = tc.componentFk + GROUP BY tc.itemFk, tc.warehouseFk, cr.classRate; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; + CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY + SELECT tcc.warehouseFk, + tcc.itemFk, + 1 rate, + IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, + CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 1) = 1 + AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 2 rate, + tcc.packing `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 + AND tcc.packing > 0 AND tcc.available >= tcc.packing) + GROUP BY tcs.warehouseFk, tcs.itemFk; + + INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) + SELECT + tcc.warehouseFk, + tcc.itemFk, + 3 rate, + tcc.available `grouping`, + SUM(tcs.sumCost) price, + SUM(tcs.sumCost) / weightGrouping priceKg + FROM tmp.ticketComponentCalculate tcc + JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk + AND tcs.warehouseFk = tcc.warehouseFk + WHERE IFNULL(tcs.classRate, 3) = 3 + GROUP BY tcs.warehouseFk, tcs.itemFk; + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentPrice; + CREATE TEMPORARY TABLE tmp.ticketComponentPrice ENGINE = MEMORY + SELECT * FROM ( + SELECT * FROM tmp.ticketComponentRate ORDER BY price + ) t + GROUP BY itemFk, warehouseFk, `grouping`; + + DROP TEMPORARY TABLE + tmp.ticketComponentCalculate, + tmp.ticketComponentSum, + tmp.ticketComponentBase, + tmp.ticketComponentRate, + tmp.ticketComponentCopy; +END$$ +DELIMITER ; \ No newline at end of file diff --git a/db/changes/10130-christmas/00-manaSpellersRequery.sql b/db/changes/10130-christmas/00-manaSpellersRequery.sql new file mode 100644 index 000000000..cc185fdba --- /dev/null +++ b/db/changes/10130-christmas/00-manaSpellersRequery.sql @@ -0,0 +1,70 @@ + +DROP procedure IF EXISTS `vn`.`manaSpellersRequery`; + +DELIMITER $$ +CREATE DEFINER=`root`@`%` PROCEDURE `vn`.`manaSpellersRequery`(vWorkerFk INTEGER) +BEGIN + + DECLARE vWorkerIsExcluded BOOLEAN; + DECLARE vFromDated DATE; + DECLARE vToDated DATE DEFAULT TIMESTAMPADD(DAY,1,CURDATE()); + DECLARE vMana INT; + DECLARE vAutoMana INT; + DECLARE vManaBank INT; + DECLARE vManaGreugeType INT; + + SELECT id INTO vMana + FROM `component` WHERE code = 'mana'; + + SELECT id INTO vAutoMana + FROM `component` WHERE code = 'autoMana'; + + SELECT id INTO vManaBank + FROM `bank` WHERE code = 'mana'; + + SELECT id INTO vManaGreugeType + FROM `greugeType` WHERE code = 'mana'; + + SELECT COUNT(*) INTO vWorkerIsExcluded + FROM workerManaExcluded + WHERE workerFk = vWorkerFk; + + IF NOT vWorkerIsExcluded THEN + + SELECT max(dated) INTO vFromDated + FROM clientManaCache; + + REPLACE workerMana (workerFk, amount) + SELECT vWorkerFk, sum(mana) FROM + ( + SELECT s.quantity * sc.value as mana + FROM ticket t + JOIN address a ON a.id = t.addressFk + JOIN client c ON c.id = a.clientFk + JOIN sale s ON s.ticketFk = t.id + JOIN saleComponent sc ON sc.saleFk = s.id + WHERE c.salesPersonFk = vWorkerFk AND sc.componentFk IN (vMana, vAutoMana) + AND t.shipped > vFromDated AND t.shipped < vToDated + UNION ALL + SELECT - r.amountPaid + FROM receipt r + JOIN client c ON c.id = r.clientFk + WHERE c.salesPersonFk = vWorkerFk AND bankFk = vManaBank + AND payed > vFromDated + UNION ALL + SELECT g.amount + FROM greuge g + JOIN client c ON c.id = g.clientFk + WHERE c.salesPersonFk = vWorkerFk AND g.greugeTypeFk = vManaGreugeType + AND g.shipped > vFromDated and g.shipped < CURDATE() + UNION ALL + SELECT cc.mana + FROM clientManaCache cc + JOIN client c ON c.id = cc.clientFk + WHERE c.salesPersonFk = vWorkerFk AND cc.dated = vFromDated + ) sub; + END IF; +END$$ + +DELIMITER ; + diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 901153a58..c56b2a0a1 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -2919,55 +2919,55 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `analisis_ventas_update`() -BEGIN - DECLARE vLastMonth DATE; - - SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); - - DELETE FROM analisis_ventas - WHERE Año > YEAR(vLastMonth) - OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); - - INSERT INTO analisis_ventas ( - Familia, - Reino, - Comercial, - Comprador, - Provincia, - almacen, - Año, - Mes, - Semana, - Vista, - Importe - ) - SELECT - tp.Tipo AS Familia, - r.reino AS Reino, - tr.CodigoTrabajador AS Comercial, - tr2.CodigoTrabajador AS Comprador, - p.name AS Provincia, - w.name AS almacen, - tm.year AS Año, - tm.month AS Mes, - tm.week AS Semana, - v.vista AS Vista, - bt.importe AS Importe - FROM bs.ventas bt - LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id - LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id - LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador - LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador - JOIN vn2008.time tm ON tm.date = bt.fecha - JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento - LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia - LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista - LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna - LEFT JOIN vn2008.province p ON p.province_id = cs.province_id - LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id - WHERE bt.fecha >= vLastMonth AND r.mercancia; +BEGIN + DECLARE vLastMonth DATE; + + SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE())); + + DELETE FROM analisis_ventas + WHERE Año > YEAR(vLastMonth) + OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth)); + + INSERT INTO analisis_ventas ( + Familia, + Reino, + Comercial, + Comprador, + Provincia, + almacen, + Año, + Mes, + Semana, + Vista, + Importe + ) + SELECT + tp.Tipo AS Familia, + r.reino AS Reino, + tr.CodigoTrabajador AS Comercial, + tr2.CodigoTrabajador AS Comprador, + p.name AS Provincia, + w.name AS almacen, + tm.year AS Año, + tm.month AS Mes, + tm.week AS Semana, + v.vista AS Vista, + bt.importe AS Importe + FROM bs.ventas bt + LEFT JOIN vn2008.Tipos tp ON tp.tipo_id = bt.tipo_id + LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id + LEFT JOIN vn2008.Clientes c on c.Id_Cliente = bt.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = c.Id_Trabajador + LEFT JOIN vn2008.Trabajadores tr2 ON tr2.Id_Trabajador = tp.Id_Trabajador + JOIN vn2008.time tm ON tm.date = bt.fecha + JOIN vn2008.Movimientos m ON m.Id_Movimiento = bt.Id_Movimiento + LEFT JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia + LEFT JOIN vn2008.Vistas v ON v.vista_id = a.Vista + LEFT JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = t.Id_Consigna + LEFT JOIN vn2008.province p ON p.province_id = cs.province_id + LEFT JOIN vn2008.warehouse w ON w.id = t.warehouse_id + WHERE bt.fecha >= vLastMonth AND r.mercancia; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2985,33 +2985,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `call_add`() -BEGIN - DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; - - -- Seleccionamos la ultima fecha introducida - SELECT MAX(Fecha) INTO datSTART FROM `call`; - - -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos - DELETE FROM `call` WHERE Fecha = datSTART; - - INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) - SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, - dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone - FROM ( - SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, - hour(calldate) as Hora,src as phone - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') - WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration - UNION ALL - SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst - FROM vn2008.Trabajadores T - JOIN vn2008.cdr C ON C.src = T.extension - WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration - ) ll - JOIN vn2008.Permisos USING(Id_Trabajador) - LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone - WHERE Id_Grupo = 6; +BEGIN + DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/ ; + + -- Seleccionamos la ultima fecha introducida + SELECT MAX(Fecha) INTO datSTART FROM `call`; + + -- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos + DELETE FROM `call` WHERE Fecha = datSTART; + + INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone) + SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador, dur_in, + dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone + FROM ( + SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, + hour(calldate) as Hora,src as phone + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%') + WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration + UNION ALL + SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0) dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst + FROM vn2008.Trabajadores T + JOIN vn2008.cdr C ON C.src = T.extension + WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration + ) ll + JOIN vn2008.Permisos USING(Id_Trabajador) + LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone + WHERE Id_Grupo = 6; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3029,205 +3029,205 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` 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 - */ - - -- descuentos comerciales COD 11 - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) - SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * - Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01' - HAVING nz(Importe) <> 0; - - DELETE mc.* - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) - SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - WHERE m.Id_Article = 11 - AND m.Concepte NOT LIKE '$%' - AND t.Fecha > '2017-01-01'; - - UPDATE vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - SET Concepte = CONCAT('$ ',Concepte) - WHERE Id_Article = 11 - AND Concepte NOT LIKE '$%' - AND Fecha > '2014-01-01'; - - -- Reclamaciones demasiado sensibles - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe, Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim ',cm.id,' : ', m.Concepte) - ,round( -1 * ((sensib -1)/4) * Cantidad * - Preu * (100 - Descuento) / 100, 2) AS Reclamaciones - , 4 - , m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Reclamaciones que pasan a Maná - - INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, - Importe , Greuges_type_id,Id_Ticket) - SELECT cm.Fecha - , cm.Id_Cliente - , concat('Claim_mana ',cm.id,' : ', m.Concepte) - ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) - AS Reclamaciones - ,3 - ,m.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca USING(Id_Movimiento) - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3 - AND cm.mana; - - -- Marcamos para no repetir - UPDATE vn2008.cl_act ca - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - SET greuge = 1 - WHERE ca.cl_sol_id NOT IN (1,5) - AND ca.greuge = 0 - AND cm.cl_est_id = 3; - - -- Recobros - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT DISTINCT t.Id_Ticket - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket - JOIN vncontrol.inter i ON i.inter_id = ts.inter_id - JOIN vn2008.state s ON s.id = i.state_id - WHERE mc.Id_Componente = 17 - AND mc.greuge = 0 - AND t.Fecha >= '2016-10-01' - AND t.Fecha < CURDATE() - AND s.alert_level >= 3; - - DELETE g.* - FROM vn2008.Greuges g - JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket - WHERE Greuges_type_id = 2; - - INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, - Greuges_type_id, Id_Ticket) - SELECT Id_Cliente - ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) - AS dif - ,date(t.Fecha) - , 2 - ,tt.Id_Ticket - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket - JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc - ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 - GROUP BY t.Id_Ticket - HAVING ABS(dif) > 1; - - UPDATE vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket - SET greuge = 1 - WHERE Id_Componente = 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_Cliente, 0,0,0,0 - FROM vn2008.Clientes; - - REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) - SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, - round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 - FROM bi.facturacion_media_anual fm - LEFT JOIN( - SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * - Cantidad * Preu * (100 - Descuento) / 100)) - AS Reclamaciones - FROM vn2008.Movimientos m - JOIN vn2008.cl_act ca - ON ca.Id_Movimiento = m.Id_Movimiento - JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id - WHERE ca.cl_sol_id NOT IN (1,5) - AND cm.cl_est_id = 3 - AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) - GROUP BY cm.Id_Cliente - ) claims ON claims.Id_Cliente = fm.Id_Cliente; - - - -- Calculamos el porcentaje del recobro para añadirlo al precio de venta - UPDATE bi.claims_ratio cr - JOIN ( - SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge - FROM vn2008.Greuges - WHERE Fecha <= CURDATE() - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = cr.Id_Cliente - SET recobro = GREATEST(0,round(nz(Greuge) / - (nz(Consumo) * vMonthToRefund / 12 ) ,3)); - - -- 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,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 +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 + */ + + -- descuentos comerciales COD 11 + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket) + SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * + Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01' + HAVING nz(Importe) <> 0; + + DELETE mc.* + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor) + SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4) + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + WHERE m.Id_Article = 11 + AND m.Concepte NOT LIKE '$%' + AND t.Fecha > '2017-01-01'; + + UPDATE vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + SET Concepte = CONCAT('$ ',Concepte) + WHERE Id_Article = 11 + AND Concepte NOT LIKE '$%' + AND Fecha > '2014-01-01'; + + -- Reclamaciones demasiado sensibles + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe, Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim ',cm.id,' : ', m.Concepte) + ,round( -1 * ((sensib -1)/4) * Cantidad * + Preu * (100 - Descuento) / 100, 2) AS Reclamaciones + , 4 + , m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Reclamaciones que pasan a Maná + + INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, + Importe , Greuges_type_id,Id_Ticket) + SELECT cm.Fecha + , cm.Id_Cliente + , concat('Claim_mana ',cm.id,' : ', m.Concepte) + ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) + AS Reclamaciones + ,3 + ,m.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca USING(Id_Movimiento) + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3 + AND cm.mana; + + -- Marcamos para no repetir + UPDATE vn2008.cl_act ca + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + SET greuge = 1 + WHERE ca.cl_sol_id NOT IN (1,5) + AND ca.greuge = 0 + AND cm.cl_est_id = 3; + + -- Recobros + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT DISTINCT t.Id_Ticket + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket + JOIN vncontrol.inter i ON i.inter_id = ts.inter_id + JOIN vn2008.state s ON s.id = i.state_id + WHERE mc.Id_Componente = 17 + AND mc.greuge = 0 + AND t.Fecha >= '2016-10-01' + AND t.Fecha < CURDATE() + AND s.alert_level >= 3; + + DELETE g.* + FROM vn2008.Greuges g + JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket + WHERE Greuges_type_id = 2; + + INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, + Greuges_type_id, Id_Ticket) + SELECT Id_Cliente + ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) + AS dif + ,date(t.Fecha) + , 2 + ,tt.Id_Ticket + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket + JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc + ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17 + GROUP BY t.Id_Ticket + HAVING ABS(dif) > 1; + + UPDATE vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket + SET greuge = 1 + WHERE Id_Componente = 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_Cliente, 0,0,0,0 + FROM vn2008.Clientes; + + REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro) + SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, + round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0 + FROM bi.facturacion_media_anual fm + LEFT JOIN( + SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * + Cantidad * Preu * (100 - Descuento) / 100)) + AS Reclamaciones + FROM vn2008.Movimientos m + JOIN vn2008.cl_act ca + ON ca.Id_Movimiento = m.Id_Movimiento + JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id + WHERE ca.cl_sol_id NOT IN (1,5) + AND cm.cl_est_id = 3 + AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE()) + GROUP BY cm.Id_Cliente + ) claims ON claims.Id_Cliente = fm.Id_Cliente; + + + -- Calculamos el porcentaje del recobro para añadirlo al precio de venta + UPDATE bi.claims_ratio cr + JOIN ( + SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge + FROM vn2008.Greuges + WHERE Fecha <= CURDATE() + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = cr.Id_Cliente + SET recobro = GREATEST(0,round(nz(Greuge) / + (nz(Consumo) * vMonthToRefund / 12 ) ,3)); + + -- 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,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); + 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 */ ; @@ -3245,23 +3245,23 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE vDateLong DATETIME; - DECLARE vOneYearAgo DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); - SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); - - -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; - - DELETE FROM bi.Greuge_Evolution - WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) - OR Fecha < vOneYearAgo; - - DELETE FROM bi.defaulters WHERE `date` < vDateLong; - DELETE FROM bi.defaulting WHERE `date` < vDateLong; +BEGIN + DECLARE vDateShort DATETIME; + DECLARE vDateLong DATETIME; + DECLARE vOneYearAgo DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE()); + SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,CURDATE()); + + -- DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong; + + DELETE FROM bi.Greuge_Evolution + WHERE (Fecha < vDateShort AND weekday(Fecha) != 1) + OR Fecha < vOneYearAgo; + + DELETE FROM bi.defaulters WHERE `date` < vDateLong; + DELETE FROM bi.defaulting WHERE `date` < vDateLong; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3739,18 +3739,18 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `facturacion_media_anual_update`() -BEGIN - TRUNCATE TABLE bi.facturacion_media_anual; - - REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) - SELECT clientFk, avg(Facturacion) - FROM ( - SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion - FROM vn.invoiceOut - WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) - GROUP BY clientFk, year, month - ) vol - GROUP BY clientFk; +BEGIN + TRUNCATE TABLE bi.facturacion_media_anual; + + REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo) + SELECT clientFk, avg(Facturacion) + FROM ( + SELECT clientFk, YEAR(issued) year, MONTH(issued) month, sum(amount) as Facturacion + FROM vn.invoiceOut + WHERE issued BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND TIMESTAMPADD(DAY, - DAY(CURDATE()),CURDATE()) + GROUP BY clientFk, year, month + ) vol + GROUP BY clientFk; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -3870,116 +3870,116 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `Greuge_Evolution_Add`() -BEGIN -/* - Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, - así como las ventas acumuladas en los ultimos 365 dias, para poder controlar - su evolucion. -*/ - DECLARE datFEC DATE; - DECLARE datFEC_TOMORROW DATE; - DECLARE datFEC_LASTYEAR DATE; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN - - GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; - SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); - - END; - - SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; +BEGIN +/* + Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, + así como las ventas acumuladas en los ultimos 365 dias, para poder controlar + su evolucion. +*/ + DECLARE datFEC DATE; + DECLARE datFEC_TOMORROW DATE; + DECLARE datFEC_LASTYEAR DATE; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN + + GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT; + SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + INSERT INTO vn2008.mail (`to`,`subject`,`text`) VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'))); + + END; + + SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; DELETE FROM bi.Greuge_Evolution WHERE Fecha >= TIMESTAMPADD(MONTH,-1,CURDATE()); - - SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), - TIMESTAMPADD(DAY,2,MAX(Fecha)) - INTO datFEC, - datFEC_TOMORROW - FROM bi.Greuge_Evolution; - - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; - - CREATE TEMPORARY TABLE maxInvoice - (PRIMARY KEY (Id_Cliente)) - ENGINE = MEMORY - SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha - FROM vn2008.Facturas - GROUP BY Id_Cliente - HAVING maxFecha < timestampadd(month,-2,datFEC); - - WHILE datFEC < CURDATE() DO - - REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) - - SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 - FROM ( - SELECT Id_Cliente, sum(Importe) as Greuge - FROM vn2008.Greuges - where Fecha <= datFEC - group by Id_Cliente - ) sub - RIGHT JOIN - - ( - - SELECT Id_Cliente, sum(Ventas) as Ventas - FROM - ( - - SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas - FROM bs.ventas - WHERE fecha = datFEC or fecha = datFEC_LASTYEAR - - UNION ALL - - SELECT Id_Cliente, Ventas - FROM bi.Greuge_Evolution - WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) - - ) sub - group by Id_Cliente - - ) v using(Id_Cliente) - ; - - -- Ahora calcularemos el greuge muerto - - UPDATE bi.Greuge_Evolution ge - JOIN maxInvoice m using(Id_Cliente) - SET FOSIL = GREUGE - WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); - - -- Recobro - - UPDATE bi.Greuge_Evolution ge - JOIN ( - SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE t.Fecha >= datFEC - AND t.Fecha < datFEC_TOMORROW - AND mc.Id_Componente = 17 -- Recobro - GROUP BY cs.Id_Cliente - ) sub using(Id_Cliente) - SET Recobro = Importe - WHERE ge.Fecha = datFEC; - - SET datFEC = datFEC_TOMORROW; - SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); - SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); - - - END WHILE; - - DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + SELECT TIMESTAMPADD(DAY,1,MAX(Fecha)), + TIMESTAMPADD(DAY,2,MAX(Fecha)) + INTO datFEC, + datFEC_TOMORROW + FROM bi.Greuge_Evolution; + + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; + + CREATE TEMPORARY TABLE maxInvoice + (PRIMARY KEY (Id_Cliente)) + ENGINE = MEMORY + SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha + FROM vn2008.Facturas + GROUP BY Id_Cliente + HAVING maxFecha < timestampadd(month,-2,datFEC); + + WHILE datFEC < CURDATE() DO + + REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas, Fosil) + + SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas, 0 + FROM ( + SELECT Id_Cliente, sum(Importe) as Greuge + FROM vn2008.Greuges + where Fecha <= datFEC + group by Id_Cliente + ) sub + RIGHT JOIN + + ( + + SELECT Id_Cliente, sum(Ventas) as Ventas + FROM + ( + + SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas + FROM bs.ventas + WHERE fecha = datFEC or fecha = datFEC_LASTYEAR + + UNION ALL + + SELECT Id_Cliente, Ventas + FROM bi.Greuge_Evolution + WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC) + + ) sub + group by Id_Cliente + + ) v using(Id_Cliente) + ; + + -- Ahora calcularemos el greuge muerto + + UPDATE bi.Greuge_Evolution ge + JOIN maxInvoice m using(Id_Cliente) + SET FOSIL = GREUGE + WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha); + + -- Recobro + + UPDATE bi.Greuge_Evolution ge + JOIN ( + SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE t.Fecha >= datFEC + AND t.Fecha < datFEC_TOMORROW + AND mc.Id_Componente = 17 -- Recobro + GROUP BY cs.Id_Cliente + ) sub using(Id_Cliente) + SET Recobro = Importe + WHERE ge.Fecha = datFEC; + + SET datFEC = datFEC_TOMORROW; + SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW); + SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC); + + + END WHILE; + + DROP TEMPORARY TABLE IF EXISTS maxInvoice; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4063,10 +4063,10 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `nigthlyAnalisisVentas`() -BEGIN - CALL analisis_ventas_update; - CALL analisis_ventas_simple; - CALL analisis_ventas_evolution_add; +BEGIN + CALL analisis_ventas_update; + CALL analisis_ventas_simple; + CALL analisis_ventas_evolution_add; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -4845,3460 +4845,6 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; --- --- Current Database: `bs` --- - -CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; - -USE `bs`; - --- --- Temporary table structure for view `bajasLaborales` --- - -DROP TABLE IF EXISTS `bajasLaborales`; -/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `bajasLaborales` AS SELECT - 1 AS `firstname`, - 1 AS `name`, - 1 AS `business_id`, - 1 AS `lastDate`, - 1 AS `endContract`, - 1 AS `type`, - 1 AS `dias`, - 1 AS `userFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `bancos_evolution` --- - -DROP TABLE IF EXISTS `bancos_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `bancos_evolution` ( - `Fecha` date NOT NULL, - `Id_Banco` int(11) NOT NULL, - `saldo` double NOT NULL DEFAULT '0', - `quilla` double NOT NULL DEFAULT '0', - `deuda` double NOT NULL DEFAULT '0', - `liquidez` double NOT NULL DEFAULT '0', - `disponibilidad ajena` double NOT NULL DEFAULT '0', - `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas', - PRIMARY KEY (`Fecha`,`Id_Banco`), - KEY `fk_banco_evolution_idx` (`Id_Banco`), - CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn`.`bank` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `carteras` --- - -DROP TABLE IF EXISTS `carteras`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `carteras` ( - `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL, - `Año` int(11) NOT NULL, - `Mes` int(11) NOT NULL, - `Peso` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientDied` --- - -DROP TABLE IF EXISTS `clientDied`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientDied` ( - `id` int(11) NOT NULL DEFAULT '0', - `clientName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, - `lastInvoiced` date DEFAULT NULL, - `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `clientNewBorn` --- - -DROP TABLE IF EXISTS `clientNewBorn`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `clientNewBorn` ( - `clientFk` int(11) NOT NULL, - `shipped` date NOT NULL, - PRIMARY KEY (`clientFk`), - CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores` --- - -DROP TABLE IF EXISTS `compradores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `semana` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`semana`), - CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `compradores_evolution` --- - -DROP TABLE IF EXISTS `compradores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `compradores_evolution` ( - `Id_Trabajador` int(11) NOT NULL, - `fecha` date NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`fecha`), - CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `experienceIberflora2016` --- - -DROP TABLE IF EXISTS `experienceIberflora2016`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `experienceIberflora2016` ( - `Id_Cliente` int(11) NOT NULL, - `isVisitor` tinyint(4) NOT NULL DEFAULT '0', - PRIMARY KEY (`Id_Cliente`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `fondo_maniobra` --- - -DROP TABLE IF EXISTS `fondo_maniobra`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `fondo_maniobra` ( - `fecha` date NOT NULL, - `fondo` double DEFAULT NULL, - `clientes_facturas` double DEFAULT NULL, - `clientes_cobros` double DEFAULT NULL, - `proveedores_facturas` double DEFAULT NULL, - `proveedores_pagos` double DEFAULT NULL, - `fondo_medio` double DEFAULT NULL, - PRIMARY KEY (`fecha`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `indicators` --- - -DROP TABLE IF EXISTS `indicators`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `indicators` ( - `updated` date NOT NULL, - `lastYearSales` int(11) DEFAULT NULL, - `totalGreuge` int(11) DEFAULT NULL, - `latePaymentRate` decimal(5,4) DEFAULT NULL, - `countEmployee` decimal(10,2) DEFAULT NULL, - `averageMana` int(11) DEFAULT NULL, - `bankingPool` int(11) DEFAULT NULL, - `lastMonthActiveClients` int(11) DEFAULT NULL, - `lastMonthLostClients` int(11) DEFAULT NULL, - `lastMonthNewClients` int(11) DEFAULT NULL, - `lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL, - `productionHours` decimal(10,1) DEFAULT NULL, - `dailyWorkersCost` decimal(10,0) DEFAULT NULL, - `volumeM3` decimal(10,0) DEFAULT NULL, - `salesValue` decimal(10,0) DEFAULT NULL, - `valueM3` decimal(10,0) DEFAULT NULL, - `hoursM3` decimal(5,2) DEFAULT NULL, - `workerCostM3` decimal(10,1) DEFAULT NULL, - `salesWorkersCostRate` decimal(10,2) DEFAULT NULL, - `thisWeekSales` decimal(10,2) DEFAULT NULL, - `lastYearWeekSales` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`updated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `lastIndicators` --- - -DROP TABLE IF EXISTS `lastIndicators`; -/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `lastIndicators` AS SELECT - 1 AS `updated`, - 1 AS `lastYearSales`, - 1 AS `incLastYearSales`, - 1 AS `totalGreuge`, - 1 AS `incTotalGreuge`, - 1 AS `latePaymentRate`, - 1 AS `incLatePaymentRate`, - 1 AS `countEmployee`, - 1 AS `incCountEmployee`, - 1 AS `averageMana`, - 1 AS `incAverageMana`, - 1 AS `bankingPool`, - 1 AS `incbankingPool`, - 1 AS `lastMonthActiveClients`, - 1 AS `incLastMonthActiveClients`, - 1 AS `lastMonthLostClients`, - 1 AS `incLastMonthLostClients`, - 1 AS `lastMonthNewClients`, - 1 AS `incLastMonthNewClients`, - 1 AS `lastMonthWebBuyingRate`, - 1 AS `incLastMonthWebBuyingRate`, - 1 AS `productionHours`, - 1 AS `dailyWorkersCost`, - 1 AS `volumeM3`, - 1 AS `salesValue`, - 1 AS `valueM3`, - 1 AS `hoursM3`, - 1 AS `workerCostM3`, - 1 AS `salesWorkersCostRate`, - 1 AS `thisWeekSales`, - 1 AS `lastYearWeekSales`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `m3` --- - -DROP TABLE IF EXISTS `m3`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `m3` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `fecha` date NOT NULL, - `provinceFk` smallint(5) unsigned DEFAULT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0', - `m3` decimal(10,2) DEFAULT NULL, - `year` int(11) DEFAULT NULL, - `month` int(11) DEFAULT NULL, - `week` int(11) DEFAULT NULL, - `day` int(11) DEFAULT NULL, - `dayName` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, - `euros` decimal(10,2) DEFAULT '0.00', - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `m3Silla` --- - -DROP TABLE IF EXISTS `m3Silla`; -/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `m3Silla` AS SELECT - 1 AS `fecha`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`, - 1 AS `dayName`, - 1 AS `Volumen`, - 1 AS `Euros`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `m3analisis` --- - -DROP TABLE IF EXISTS `m3analisis`; -/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `m3analisis` AS SELECT - 1 AS `fecha`, - 1 AS `year`, - 1 AS `month`, - 1 AS `week`, - 1 AS `day`, - 1 AS `dayName`, - 1 AS `Volumen`, - 1 AS `Euros`, - 1 AS `Departamento`, - 1 AS `Horas`, - 1 AS `Salarios`, - 1 AS `tiempoM3`, - 1 AS `valorM3`, - 1 AS `costeLaboralM3`, - 1 AS `costeEuros`, - 1 AS `precioHora`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `manaCustomer` --- - -DROP TABLE IF EXISTS `manaCustomer`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `manaCustomer` ( - `Id_Cliente` int(11) NOT NULL, - `Mana` decimal(10,0) NOT NULL DEFAULT '0', - `dated` date NOT NULL, - PRIMARY KEY (`Id_Cliente`,`dated`), - KEY `manaCustomerIdx1` (`dated`), - CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `manaSpellersExcluded` --- - -DROP TABLE IF EXISTS `manaSpellersExcluded`; -/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `manaSpellersExcluded` AS SELECT - 1 AS `workerFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `mana_spellers` --- - -DROP TABLE IF EXISTS `mana_spellers`; -/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mana_spellers` AS SELECT - 1 AS `Id_Trabajador`, - 1 AS `size`, - 1 AS `used`, - 1 AS `prices_modifier_rate`, - 1 AS `prices_modifier_activated`, - 1 AS `minRate`, - 1 AS `maxRate`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mana_spellers_excluded` --- - -DROP TABLE IF EXISTS `mana_spellers_excluded`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mana_spellers_excluded` ( - `Id_Trabajador` int(11) NOT NULL, - PRIMARY KEY (`Id_Trabajador`), - CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `mermas` --- - -DROP TABLE IF EXISTS `mermas`; -/*!50001 DROP VIEW IF EXISTS `mermas`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `mermas` AS SELECT - 1 AS `Comprador`, - 1 AS `Familia`, - 1 AS `Referencia`, - 1 AS `Item`, - 1 AS `Cantidad`, - 1 AS `Coste_Unitario`, - 1 AS `Importe`, - 1 AS `Cliente`, - 1 AS `ticketFk`, - 1 AS `Fecha`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `mermasCache` --- - -DROP TABLE IF EXISTS `mermasCache`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `mermasCache` ( - `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `año` int(4) NOT NULL, - `Valor_Compra` decimal(10,0) DEFAULT NULL, - `Faltas` decimal(10,0) DEFAULT NULL, - `Basura` decimal(10,0) DEFAULT NULL, - PRIMARY KEY (`Comprador`,`año`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `nightTask` --- - -DROP TABLE IF EXISTS `nightTask`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTask` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `started` datetime DEFAULT NULL, - `finished` datetime DEFAULT NULL, - `lastFinished` datetime DEFAULT NULL, - `order` int(11) DEFAULT NULL, - `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL, - `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `errorCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert` BEFORE INSERT ON `nightTask` FOR EACH ROW -BEGIN - - IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN - - CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - - END IF; - -END */;; -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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate` BEFORE UPDATE ON `nightTask` FOR EACH ROW -BEGIN - - IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN - - CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); - - END IF; - -END */;; -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 */ ; - --- --- Table structure for table `nightTaskConfig` --- - -DROP TABLE IF EXISTS `nightTaskConfig`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `nightTaskConfig` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `logMail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payMethodClient` --- - -DROP TABLE IF EXISTS `payMethodClient`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payMethodClient` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '0', - `clientFk` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`id`), - KEY `FkPayMethod_idx` (`payMethodFk`), - KEY `FkClientPayMethod_idx` (`clientFk`), - KEY `FkDateClientPayMethod` (`dated`,`clientFk`), - CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_bin; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `payMethodClientEvolution` --- - -DROP TABLE IF EXISTS `payMethodClientEvolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `payMethodClientEvolution` ( - `id` int(11) NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `payMethodName` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `amountClient` int(11) NOT NULL, - `amount` decimal(10,2) NOT NULL, - `equalizationTax` decimal(10,2) NOT NULL, - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity` --- - -DROP TABLE IF EXISTS `productivity`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity` ( - `id` int(10) unsigned NOT NULL AUTO_INCREMENT, - `dated` date NOT NULL, - `hh` int(10) unsigned NOT NULL, - `mm` int(10) unsigned NOT NULL, - `m3` double NOT NULL DEFAULT '0', - `workers` int(11) NOT NULL DEFAULT '0', - `wCost` double NOT NULL DEFAULT '0', - `numCoordinadores` int(11) NOT NULL DEFAULT '0', - `costCoordinacion` double NOT NULL DEFAULT '0', - `numSacadores` int(11) NOT NULL DEFAULT '0', - `costSacado` double NOT NULL DEFAULT '0', - `numEncajadores` int(11) NOT NULL DEFAULT '0', - `costEncajado` double NOT NULL DEFAULT '0', - `numPaletizadores` int(11) NOT NULL DEFAULT '0', - `costPaletizado` double NOT NULL DEFAULT '0', - `numCamareros` int(11) NOT NULL DEFAULT '0', - `costCamara` double NOT NULL DEFAULT '0', - `numComplementos` int(11) NOT NULL DEFAULT '0', - `costComplementos` double NOT NULL DEFAULT '0', - `numArtificial` int(11) NOT NULL DEFAULT '0', - `costArtificial` double NOT NULL DEFAULT '0', - `m3FV` double NOT NULL DEFAULT '0', - `m3PCA` double NOT NULL DEFAULT '0', - `m3Artificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`id`) -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivityDepartment` --- - -DROP TABLE IF EXISTS `productivityDepartment`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivityDepartment` ( - `dated` date NOT NULL, - `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', - `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `productivity_evolution` --- - -DROP TABLE IF EXISTS `productivity_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `productivity_evolution` ( - `dated` date NOT NULL, - `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00', - PRIMARY KEY (`dated`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salaries2018` --- - -DROP TABLE IF EXISTS `salaries2018`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salaries2018` ( - `person_id` int(11) NOT NULL DEFAULT '0', - `sex` enum('M','F') CHARACTER SET utf8 NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', - `edad` int(6) DEFAULT NULL, - `antiguedad` int(6) DEFAULT NULL, - `Modalidad` varchar(22) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', - `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, - `worker` varchar(82) CHARACTER SET utf8 DEFAULT NULL, - `totalDays` decimal(32,0) DEFAULT NULL, - `totalAnual` decimal(16,0) DEFAULT NULL, - `virtualMonthlySalary` decimal(16,0) DEFAULT NULL, - `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, - `category_name` varchar(50) CHARACTER SET utf8 NOT NULL, - `level_name` varchar(5) CHARACTER SET utf8 DEFAULT NULL, - `thisYearDateStart` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL, - PRIMARY KEY (`person_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salePersonEvolution` --- - -DROP TABLE IF EXISTS `salePersonEvolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salePersonEvolution` ( - `dated` date NOT NULL DEFAULT '0000-00-00', - `amount` decimal(10,2) NOT NULL DEFAULT '0.00', - `equalizationTax` decimal(10,2) NOT NULL DEFAULT '0.00', - `salesPersonFk` int(11) NOT NULL DEFAULT '0', - PRIMARY KEY (`dated`,`salesPersonFk`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `salesByWeek` --- - -DROP TABLE IF EXISTS `salesByWeek`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `salesByWeek` ( - `week` int(11) NOT NULL, - `year` int(11) NOT NULL, - `sales` double DEFAULT NULL, - UNIQUE KEY `week` (`week`,`year`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores` --- - -DROP TABLE IF EXISTS `vendedores`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores` ( - `Id_Trabajador` int(11) NOT NULL, - `año` int(4) NOT NULL, - `mes` int(2) NOT NULL, - `importe` decimal(10,2) DEFAULT NULL, - `comision` decimal(10,2) DEFAULT NULL, - `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', - `comisionNuevos` decimal(10,2) DEFAULT NULL, - `sustitucionArrendada` decimal(10,2) DEFAULT NULL, - `sustitucionCedida` decimal(10,2) DEFAULT NULL, - `itemTypeLended` decimal(10,2) DEFAULT NULL, - `itemTypeBorrowed` decimal(10,2) DEFAULT NULL, - PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), - CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `vendedores_evolution` --- - -DROP TABLE IF EXISTS `vendedores_evolution`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `vendedores_evolution` ( - `workerFk` int(11) NOT NULL, - `year` int(11) NOT NULL, - `sales` decimal(10,2) DEFAULT NULL, - `month` int(11) NOT NULL, - PRIMARY KEY (`workerFk`,`year`,`month`), - CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas` --- - -DROP TABLE IF EXISTS `ventas`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas` ( - `Id_Movimiento` int(11) NOT NULL, - `importe` decimal(10,3) NOT NULL DEFAULT '0.000', - `recargo` decimal(10,3) NOT NULL DEFAULT '0.000', - `fecha` date NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `Id_Cliente` int(11) NOT NULL DEFAULT '1', - `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', - PRIMARY KEY (`Id_Movimiento`), - KEY `tip_to_tip_idx` (`tipo_id`), - KEY `clientes_bs_ventas_idx` (`Id_Cliente`), - KEY `empresa_bs_ventas_idx` (`empresa_id`), - KEY `fecha_bs` (`fecha`), - CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, - CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `ventas_contables` --- - -DROP TABLE IF EXISTS `ventas_contables`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `ventas_contables` ( - `year` int(4) NOT NULL, - `month` int(2) NOT NULL, - `venta` decimal(10,2) DEFAULT NULL, - `grupo` int(1) NOT NULL, - `reino_id` int(10) unsigned NOT NULL, - `tipo_id` smallint(5) unsigned NOT NULL, - `empresa_id` int(4) NOT NULL, - `gasto` varchar(10) CHARACTER SET latin1 NOT NULL, - PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Table structure for table `warehouseProduction_kk` --- - -DROP TABLE IF EXISTS `warehouseProduction_kk`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `warehouseProduction_kk` ( - `fecha` date NOT NULL, - `warehouse_id` smallint(6) unsigned NOT NULL, - `m3` decimal(10,0) NOT NULL DEFAULT '0', - `labourCost` decimal(10,0) NOT NULL DEFAULT '0', - `workerHours` decimal(10,0) NOT NULL DEFAULT '0', - PRIMARY KEY (`fecha`,`warehouse_id`), - KEY `warehouseProduction_fk1_idx` (`warehouse_id`), - CONSTRAINT `warehouseProduction_fk1` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Temporary table structure for view `workerMana` --- - -DROP TABLE IF EXISTS `workerMana`; -/*!50001 DROP VIEW IF EXISTS `workerMana`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `workerMana` AS SELECT - 1 AS `workerFk`, - 1 AS `amount`*/; -SET character_set_client = @saved_cs_client; - --- --- Table structure for table `workerSpeed` --- - -DROP TABLE IF EXISTS `workerSpeed`; -/*!40101 SET @saved_cs_client = @@character_set_client */; -/*!40101 SET character_set_client = utf8 */; -CREATE TABLE `workerSpeed` ( - `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, - `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, - `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', - `LitrosMinuto` decimal(10,1) DEFAULT NULL, - `LitrosMinutoLastHour` decimal(10,1) DEFAULT NULL, - `lastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', - PRIMARY KEY (`workerCode`,`warehouseFk`,`accion`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; -/*!40101 SET character_set_client = @saved_cs_client */; - --- --- Dumping events for database 'bs' --- -/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; -/*!50106 DROP EVENT IF EXISTS `nightTask_launchAll` */; -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 = 'NO_ENGINE_SUBSTITUTION' */ ;; -/*!50003 SET @saved_time_zone = @@time_zone */ ;; -/*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; -/*!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 'bs' --- -/*!50003 DROP FUNCTION IF EXISTS `tramo` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci -BEGIN - - DECLARE vTramo VARCHAR(20); - DECLARE vHour INT; - - SET vHour = HOUR(vDateTime) ; - - SET vTramo = - CASE - WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' - WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' - END ; - -RETURN vTramo; -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 DROP PROCEDURE IF EXISTS `analisisComponentes` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() -BEGIN - -DECLARE vDateStart DATE DEFAULT '2016-01-01'; -DECLARE vDateEnd DATE DEFAULT '2016-11-30'; -DECLARE vDate DATE; - -SET vDate = vDateStart; - -DELETE FROM bs.ventasComponentes; - -WHILE vDate <= vDateEnd DO - - INSERT INTO bs.ventasComponentes - SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe - FROM vn2008.Movimientos_componentes mc - JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento - JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento - WHERE v.fecha = vDate - AND empresa_id IN (442,567) - GROUP BY mc.Id_Componente; - - SET vDate = TIMESTAMPADD(DAY,1,vDate); - - IF DAY(vDate) MOD 28 = 0 THEN - - SELECT vDate; - - END IF; - -END WHILE; - - SELECT vDate; - - -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 DROP PROCEDURE IF EXISTS `bancos_evolution_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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() -BEGIN - /* - - Inserta en la tabla bancos_evolution los saldos acumulados - - */ - - - DECLARE vCurrentDate DATE; - DECLARE vStartingDate DATE DEFAULT '2016-01-01'; - DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, CURDATE()); - - DELETE FROM bs.bancos_evolution WHERE Fecha > vStartingDate; - - SET vCurrentDate = vStartingDate; - - WHILE vCurrentDate < vMaxDate DO - - REPLACE bs.bancos_evolution( Fecha - ,Id_Banco - ,saldo) - - SELECT vCurrentDate - , Id_Banco - , sum(saldo) - - FROM - ( - - SELECT Id_Banco - ,saldo_aux as saldo - FROM bs.bancos_evolution - - WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior - - UNION ALL - - SELECT c.Id_Banco, IFNULL(sum(Entrada),0) - ifnull(sum(Salida),0) as saldo - FROM vn2008.Cajas c - JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas - WHERE cash IN (0,3) - AND Cajafecha = vCurrentDate - AND (Serie = 'MB' OR cash = 3) - GROUP BY Id_Banco - - UNION ALL - - SELECT id_banco, - importe -- pagos futuros - FROM vn2008.pago - WHERE fecha = vCurrentDate - AND fecha >= CURDATE() - AND NOT conciliado - - UNION ALL - - SELECT Id_Banco, Entregado -- cobros futuros - FROM vn2008.Recibos - WHERE Fechacobro = vCurrentDate - AND Fechacobro > CURDATE() - - UNION ALL - - SELECT sp.Id_Banco, Importe -- saldos de la tabla prevision - FROM vn2008.Saldos_Prevision sp - JOIN vn2008.Bancos b using(Id_Banco) - WHERE cash IN (0,3) - AND Fecha = vCurrentDate - - - - )sub - GROUP BY Id_Banco; - - -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas - - UPDATE bs.bancos_evolution be - SET saldo_aux = saldo; - - -- Ahora actualizamos la quilla - UPDATE bs.bancos_evolution be - LEFT JOIN - ( - SELECT Id_Banco, - sum(importe) as quilla - FROM vn2008.Bancos_poliza - WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) - GROUP BY Id_Banco - ) sub using(Id_Banco) - SET be.quilla = sub.quilla - WHERE be.Fecha = vCurrentDate; - - - SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); - - END WHILE; - - - -- Deuda - UPDATE bs.bancos_evolution be - JOIN vn2008.Bancos using(Id_Banco) - SET be.deuda = IF(cash = 3, be.saldo_aux, 0) - , be.saldo = IF(cash = 3, 0, be.saldo_aux) - WHERE Fecha >= vStartingDate; - - - -- Liquidez - update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; - - -- Disponibilidad - update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; - -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 DROP PROCEDURE IF EXISTS `campaignComparative` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) -BEGIN - SELECT - workerName, - id, - name, - CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, - CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount - FROM ( - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - SUM(v.importe) AS previousAmmount, - 0 currentAmmount - FROM bs.ventas v - INNER JOIN vn.`client` c ON v.Id_Cliente = c.id - INNER JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) - AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) - GROUP BY w.id, v.Id_Cliente) - UNION ALL - (SELECT - CONCAT(w.firstname, ' ', w.lastName) AS workerName, - c.id, - c.name, - 0 AS previousAmmount, - SUM(s.quantity * s.price) AS currentAmmount - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.worker w ON c.salesPersonFk = w.id - WHERE t.shipped BETWEEN vDateFrom - AND vDateTo - GROUP BY w.id, c.id) - ) comparative - GROUP BY workerName, id - HAVING (previousAmmount <> 0 OR currentAmmount <> 0) - ORDER BY workerName, id; -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 DROP PROCEDURE IF EXISTS `carteras_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`() -BEGIN - -DELETE FROM bs.carteras -WHERE Año >= YEAR(CURDATE()) - 1; - -INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) -SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso -FROM vn2008.time t -JOIN bs.ventas v on t.date = v.fecha -JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente -JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador -WHERE t.year >= YEAR(CURDATE()) - 1 -GROUP BY CodigoTrabajador, Año, Mes; - - -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 */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`() -BEGIN - - IF DAY(CURDATE()) = 6 THEN - - SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE()); - SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE()); - SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE()); - - TRUNCATE TABLE bs.clientDied; - - INSERT INTO bs.clientDied - SELECT c.id, - c.name as clientName, - maxIssued as lastInvoiced, - w.code AS workerCode, - b.code AS Boss, - CASE - WHEN IFNULL(maxIssued,'2000-01-01') < @tercerAviso THEN 'Tercer Aviso' - WHEN maxIssued < @segundoAviso THEN 'Segundo Aviso' - WHEN maxIssued < @primerAviso THEN 'Primer Aviso' - END as Aviso - FROM vn.client c - JOIN vn.worker w ON w.id = c.salesPersonFk - JOIN vn2008.jerarquia j ON j.worker_id = w.id - JOIN vn.worker b ON b.id = j.boss_id - JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.salesPersonFk - LEFT JOIN (SELECT clientFk, max(issued) as maxIssued FROM vn.invoiceOut GROUP BY clientFk) io ON io.clientFk = c.id - WHERE (maxIssued IS NULL OR maxIssued < @primerAviso) - AND c.created < @tercerAviso; - - 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 DROP PROCEDURE IF EXISTS `clientNewBorn_Update` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientNewBorn_Update`() -BEGIN - - DECLARE fromDated DATE DEFAULT '2019-04-01'; - - -- Eliminamos clientes que ya no son nuevos - DELETE FROM bs.clientNewBorn - WHERE shipped < TIMESTAMPADD(YEAR,-1,CURDATE()); - - -- Clientes nuevos - REPLACE bs.clientNewBorn(clientFk,shipped) - SELECT t.clientFk, MIN(t.shipped) as shipped - FROM vn.ticket t - WHERE shipped > '2001-01-01' - GROUP BY t.clientFk - HAVING shipped >= GREATEST(TIMESTAMPADD(YEAR,-1,CURDATE()), fromDated); - -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 DROP PROCEDURE IF EXISTS `comercialesCompleto` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE) -BEGIN - -CALL vn.subordinateGetList(vWorker); - -SELECT - c.Id_Cliente id_cliente, - c.calidad, - c.Cliente cliente, - cr.recobro * 100 tarifa, - c.Telefono telefono, - c.movil, - c.POBLACION poblacion, - p.`name` provincia, - vn2008.red(f.futur) futur, - c.Credito credito, - pm.`name` forma_pago, - vn2008.red(c365 / 12) consumo_medio365, - vn2008.red(c365) consumo365, - vn2008.red(CmLy.peso) peso_mes_año_pasado, - vn2008.red(CmLy.peso * 1.19) objetivo, - tr.CodigoTrabajador, - vn2008.red(mes_actual.consumo) consumoMes, - vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, - DATE(LastTicket) ultimo_ticket, - dead.muerto, - g.Greuge, - cr.recobro -FROM - vn2008.Clientes c - LEFT JOIN - (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge - FROM vn2008.Greuges - GROUP BY Id_Cliente - ) g ON g.Id_Cliente = c.Id_Cliente - LEFT JOIN - vn2008.province p ON p.province_id = c.province_id - JOIN - vn2008.pay_met pm ON pm.id = c.pay_met_id - LEFT JOIN - vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - LEFT JOIN - bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 - FROM bs.ventas v - JOIN vn2008.Clientes c USING (Id_Cliente) - - WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate - GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - Id_Cliente, SUM(importe) consumo - FROM - bs.ventas v - INNER JOIN vn2008.Clientes c USING (Id_Cliente) - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) - GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - t.Id_Cliente, - SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente - JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) - GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente - LEFT JOIN - (SELECT - MAX(t.Fecha) LastTicket, c.Id_Cliente - FROM - vn2008.Tickets t - JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - SUM(importe) peso, c.Id_Cliente - FROM - bs.ventas v - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - MONTH(fecha) = MONTH(vDate) - AND YEAR(fecha) = YEAR(vDate) - 1 - AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente - LEFT JOIN - (SELECT - c.Id_Cliente, - IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto - FROM - vn2008.Facturas f - JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente - - LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador - WHERE - (c.Id_Trabajador = vWorker OR tr.boss = vWorker) - GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente - JOIN tmp.subordinate s ON s.workerFk = c.Id_Trabajador; - -DROP TEMPORARY TABLE tmp.subordinate; -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 DROP PROCEDURE IF EXISTS `compradores_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT) -BEGIN - -REPLACE bs.compradores - -SELECT tp.Id_Trabajador - , intYEAR as año - , tm.week as semana - , sum(importe) as importe - , 0 as comision - -FROM bs.ventas v -JOIN vn2008.time tm on tm.date = v.fecha -JOIN vn2008.Tipos tp using(tipo_id) -WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END -AND reino_id != 6 -GROUP BY tp.Id_Trabajador, tm.week; - - - - -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 */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add_launcher`() -BEGIN - - DECLARE vYear INT; - DECLARE vWeek INT; - DECLARE done BOOL DEFAULT FALSE; - - DECLARE rs CURSOR FOR - SELECT year, week - FROM vn.time - WHERE (year = vYear AND week >= vWeek) - OR year > vYear; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT MAX(año) INTO vYear - FROM compradores; - - SELECT MAX(semana) INTO vWeek - FROM compradores - WHERE año = vYear; - - OPEN rs; - - FETCH rs INTO vYear, vWeek; - - WHILE NOT done DO - - CALL compradores_add(vYear, vWeek, vWeek); - - FETCH rs INTO vYear, vWeek; - - END WHILE; - - CLOSE rs; - - CALL compradores_evolution_add; - -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 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; - - WHILE datFEC < CURDATE() DO - - SELECT datFEC; - - REPLACE bs.compradores_evolution( Id_Trabajador - , fecha - , importe) - - SELECT Id_Trabajador - , datFEC as fecha - , sum(importe) as importe - - FROM - ( - - SELECT Id_Trabajador - , importe - FROM bs.compradores_evolution - WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior - - UNION ALL - - SELECT Id_Trabajador - , importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual - FROM bs.ventas v - JOIN vn2008.Tipos tp using(tipo_id) - WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC)) - AND reino_id != 6 - - )sub - GROUP BY Id_Trabajador; - - - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -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 */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */; -ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`() -BEGIN -/* - -Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias - -*/ - -DECLARE datFEC DATE DEFAULT '2015-01-01'; - - -SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.fondo_maniobra; - - WHILE datFEC < CURDATE() DO - - -- esto solo sirve para no aburrirse mientras esperamos... - - IF day(datFEC) mod 28 = 0 then - SELECT datFEC; - end if; - - - REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) - SELECT datFEC as Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos - FROM - ( - SELECT Sum(Facturas.Importe) AS Facturas - FROM vn2008.Facturas - INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <>1381 - AND Fecha between '2011-01-01' and datFEC) fac - JOIN - ( - SELECT - Sum(Entregado) AS Cobros - FROM vn2008.Recibos - INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente - WHERE Clientes.`real` - AND empresa_id <> 1381 - AND Fechacobro Between '2011-01-01' and datFEC) cob - JOIN - ( - SELECT - Sum(cantidad) AS Recibidas - FROM vn2008.recibida - INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id - WHERE empresa_id <> 1381 - AND recibida.fecha Between '2015-01-01' and datFEC) rec - JOIN - ( - SELECT Sum(importe) AS Pagos - FROM vn2008.pago - WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag; - - - - UPDATE bs.fondo_maniobra - JOIN - (SELECT avg(fondo) as media - FROM bs.fondo_maniobra - WHERE fecha <= datFEC) sub - SET fondo_medio = media - WHERE fecha = datFEC; - - - SET datFEC = TIMESTAMPADD(DAY,1,datFEC); - - END WHILE; - - -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 */ ; -ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; -/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdate`(vDated DATE) -BEGIN - - DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated); - DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated); - DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated); - DECLARE vWeek INT; - - REPLACE indicators(updated) - VALUES(vDated); - - -- Ventas totales del ultimo año - UPDATE indicators - SET lastYearSales = - ( - SELECT SUM(importe + recargo) - FROM bs.ventas v - JOIN vn2008.empresa e ON e.id = v.empresa_id - JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo - WHERE fecha BETWEEN oneYearBefore AND vDated - AND eg.grupo = 'Verdnatura' - ) - WHERE updated = vDated; - - -- Greuge total acumulado - UPDATE indicators - SET totalGreuge = - ( - SELECT SUM(amount) - FROM vn.greuge - WHERE shipped <= vDated - ) - WHERE updated = vDated; - - - -- Tasa de morosidad con respecto a las ventas del último mes - UPDATE indicators - SET latePaymentRate = - (SELECT SUM(amount) FROM bi.defaulters WHERE date = vDated and amount > 0) - / - ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) - WHERE updated = vDated; - - -- Número de trabajadores activos - UPDATE indicators - SET countEmployee = - ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) - FROM - postgresql.business AS b - JOIN postgresql.profile p ON p.profile_id = b.provider_id - JOIN postgresql.person pe ON pe.person_id = p.person_id - LEFT JOIN - postgresql.business_labour AS bl ON bl.business_id = b.business_id - LEFT JOIN - postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - WHERE - (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated)) - AND pe.name = 'VERDNATURA LEVANTE SL' - ) - WHERE updated = vDated; - - -- Maná medio acumulado por comercial - UPDATE indicators - SET averageMana = - (SELECT avg(used) - FROM bs.mana_spellers - ) - WHERE updated = vDated; - - -- Número de clientes que han comprado en los últimos 30 dias - UPDATE indicators - SET lastMonthActiveClients = - (SELECT COUNT(DISTINCT t.clientFk) - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) - WHERE updated = vDated; - - -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores - UPDATE indicators - SET lastMonthLostClients = - (SELECT COUNT(lm.clientFk) - FROM - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) cm - RIGHT JOIN - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped >= twoMonthsBefore - AND t.shipped < oneMonthBefore - ) lm ON lm.clientFk = cm.clientFk - WHERE cm.clientFk IS NULL - ) - WHERE updated = vDated; - - -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores - UPDATE indicators - SET lastMonthNewClients = - (SELECT COUNT(cm.clientFk) - FROM - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped BETWEEN oneMonthBefore AND vDated - ) cm - LEFT JOIN - ( - SELECT DISTINCT t.clientFk - FROM vn.ticket t - WHERE t.shipped >= twoMonthsBefore - AND t.shipped < oneMonthBefore - ) lm ON lm.clientFk = cm.clientFk - WHERE lm.clientFk IS NULL - ) - WHERE updated = vDated; - - -- Porcentaje de autopedidos sobre los pedidos totales - UPDATE indicators - SET lastMonthWebBuyingRate = - ( SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '') - FROM hedera.`order` - WHERE date_send BETWEEN oneMonthBefore AND vDated - ) - WHERE updated = vDated; - - -- Indicadores de producción - UPDATE indicators i - JOIN productionIndicators pi ON pi.dated = i.updated - SET i.productionHours = pi.productionHours, - i.dailyWorkersCost = pi.dailyWorkersCost, - i.volumeM3 = pi.volumeM3, - i.salesValue = pi.salesValue, - i.valueM3 = pi.valueM3, - i.hoursM3 = pi.hoursM3, - i.workerCostM3 = pi.workerCostM3, - i.salesWorkersCostRate = pi.salesWorkersCostRate - WHERE updated BETWEEN oneMonthBefore AND vDated; - - -- CAP Para el calculo de las ventas agrupado por semanas - - SELECT week - FROM vn.time - WHERE dated=vDated INTO vWeek; - - TRUNCATE `bs`.`salesByWeek`; - - INSERT INTO `bs`.`salesByWeek` (week,year,sales) - SELECT `t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales` - FROM `bs`.`ventas` `v` - LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha - GROUP BY `t`.`week` , `t`.`year` - ORDER BY `t`.`week` , `t`.`year`; - - -- CAP Indicador Ventas semana actual - UPDATE indicators i - JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated) - SET i.thisWeekSales = s.sales - WHERE updated = vDated; - - -- CAP indicador ventas semana actual en el año pasado - UPDATE indicators i - JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)-1 - SET i.lastYearWeekSales = s.sales - WHERE updated = vDated; - -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 DROP PROCEDURE IF EXISTS `indicatorsUpdateLauncher` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdateLauncher`() -BEGIN - - DECLARE vDated DATE; - - SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') - INTO vDated - FROM bs.indicators; - - WHILE vDated < CURDATE() DO - - CALL indicatorsUpdate(vDated); - - SELECT TIMESTAMPADD(DAY,1,MAX(updated)) - INTO vDated - FROM bs.indicators; - - END WHILE; - -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 DROP PROCEDURE IF EXISTS `m3Add` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `m3Add`() -BEGIN - - DECLARE datSTART DATE; - DECLARE datEND DATE; - - SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART - FROM bs.m3; - - SET datEND = TIMESTAMPADD(DAY,-1,CURDATE()); - - DELETE FROM bs.m3 - WHERE fecha >= datSTART; - - INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) - SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(i.compression * s.quantity * r.cm3) / 1000000 AS m3, - tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) - FROM vn.ticket t - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it ON it.id = i.typeFk - JOIN bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas" - JOIN vn.time tm ON tm.dated = v.fecha - JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk - JOIN vn.address a ON a.id = t.addressFk - WHERE v.fecha BETWEEN datSTART AND datEND - AND s.quantity > 0 -- evita abonos - AND t.companyFk = 442 -- Verdnatura - GROUP BY t.warehouseFk, v.fecha, a.provinceFk; -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 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`() -BEGIN -DECLARE vToDated DATE; - DECLARE vFromDated DATE; - DECLARE vForDeleteDated DATE; - DECLARE vManaId INT DEFAULT 37; - DECLARE vManaAutoId INT DEFAULT 39; - DECLARE vManaBankId INT DEFAULT 66; - DECLARE vManaGreugeTypeId INT DEFAULT 3; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - DELETE - FROM bs.manaCustomer - WHERE dated = vFromDated; - - SELECT IFNULL(max(dated), '2016-01-01') - INTO vFromDated - FROM bs.manaCustomer; - - WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO - - SELECT - timestampadd(DAY,30,vFromDated), - timestampadd(DAY,-90,vFromDated) - INTO - vToDated, - vForDeleteDated; - - DELETE FROM bs.manaCustomer - WHERE dated <= vForDeleteDated; - - - INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated) - - SELECT - Id_Cliente, - cast(sum(mana) as decimal(10,2)) as mana, - vToDated as dated - FROM - - ( - SELECT cs.Id_Cliente, Cantidad * Valor as mana - FROM vn2008.Tickets t - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket - JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento - WHERE Id_Componente IN (vManaAutoId, vManaId) - AND t.Fecha > vFromDated - AND date(t.Fecha) <= vToDated - - - UNION ALL - - SELECT r.Id_Cliente, - Entregado - FROM vn2008.Recibos r - WHERE Id_Banco = vManaBankId - AND Fechacobro > vFromDated - AND Fechacobro <= vToDated - - UNION ALL - - SELECT g.Id_Cliente, g.Importe - FROM vn2008.Greuges g - WHERE Greuges_type_id = vManaGreugeTypeId - AND Fecha > vFromDated - AND Fecha <= vToDated - - UNION ALL - - SELECT Id_Cliente, mana - FROM bs.manaCustomer - WHERE dated = vFromDated - ) sub - - GROUP BY Id_Cliente - HAVING Id_Cliente; - - SET vFromDated = vToDated; - - END WHILE; - -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 DROP PROCEDURE IF EXISTS `manaSpellers_actualize` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `manaSpellers_actualize`() -BEGIN - - /* PAK 2019/08/09 updated - * - * Recalcula el valor del campo con el modificador de precio para el componente de maná automático. - * La tabla mana_spellers es una caché - * - */ - - UPDATE mana_spellers me - JOIN - (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual - FROM bs.vendedores - WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) - GROUP BY Id_Trabajador - ) lastYearSales USING(Id_Trabajador) - SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; - -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 DROP PROCEDURE IF EXISTS `mermasCacheUpdate` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `mermasCacheUpdate`() -BEGIN - - DECLARE vTimeRange INT DEFAULT 30; - DECLARE vCurYearStarted DATE DEFAULT TIMESTAMPADD(DAY, - vTimeRange, CURDATE()); - DECLARE vCurYearFinished DATE DEFAULT CURDATE(); - DECLARE vLastYearStarted DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearStarted); - DECLARE vLastYearFinished DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearFinished); - - REPLACE bs.mermasCache - SELECT Comprador, - IF(Fecha < vCurYearStarted, year(CURDATE()) - 1,year(CURDATE())) año, - CAST(sum(Importe) as DECIMAL(10,0)) as Valor_Compra, - CAST(sum(IF(Cliente LIKE 'FALTAS',Importe,0)) as DECIMAL(10,0)) as Faltas, - CAST(sum(IF(Cliente LIKE 'BASURA',Importe,0)) as DECIMAL(10,0)) as Basura - FROM bs.mermas - WHERE Fecha BETWEEN vCurYearStarted AND vCurYearFinished - OR Fecha BETWEEN vLastYearStarted AND vLastYearFinished - GROUP BY año, Comprador; - - -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 DROP PROCEDURE IF EXISTS `nightTask_launchAll` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchAll`() -BEGIN -/** - * Runs all nightly tasks. - */ - DECLARE vDone BOOL; - DECLARE vError VARCHAR(255); - DECLARE vErrorCode VARCHAR(255); - DECLARE vNErrors INT DEFAULT 0; - DECLARE vSchema VARCHAR(255); - DECLARE vProcedure VARCHAR(255); - DECLARE vLogMail VARCHAR(255); - DECLARE vId INT; - - DECLARE rs CURSOR FOR - SELECT id, `schema`, `procedure` - FROM nightTask - WHERE finished <= CURDATE() - OR finished IS NULL - ORDER BY `order`; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SET max_sp_recursion_depth = 3; - OPEN rs; - - myLoop: LOOP - SET vDone = FALSE; - FETCH rs INTO vId, vSchema, vProcedure; - - IF vDone THEN - LEAVE myLoop; - END IF; - - UPDATE nightTask - SET `started` = NOW(), - `finished` = NULL, - `error` = NULL, - `errorCode` = NULL - WHERE id = vId; - - SET vError = NULL; - CALL nightTask_launchTask( - vSchema, - vProcedure, - vError, - vErrorCode - ); - - IF vError IS NOT NULL THEN - SET vNErrors = vNErrors + 1; - - UPDATE nightTask - SET `error` = vError, - `errorCode` = vErrorCode - WHERE id = vId; - ELSE - UPDATE nightTask - SET finished = NOW(), - lastFinished = NOW() - WHERE id = vId; - END IF; - END LOOP; - - CLOSE rs; - - SELECT logMail INTO vLogMail - FROM nightTaskConfig LIMIT 1; - - IF vNErrors > 0 AND vLogMail IS NOT NULL THEN - INSERT INTO vn.mail SET - `sender` = vLogMail, - `subject` = 'Nightly task failed', - `body` = CONCAT( - vNErrors, ' procedures of nightly tasks have failed. ', - 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' - ); - 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 DROP PROCEDURE IF EXISTS `nightTask_launchTask` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchTask`( - vSchema VARCHAR(255), - vProcedure VARCHAR(255), - OUT vError VARCHAR(255), - OUT vErrorCode VARCHAR(255) -) -BEGIN -/** - * Runs an specific procedure from nightly tasks, if an error - * occurs, instead of throw it, #vError and #vErrorCode variables - * are setted. - * - * @param vSchema The procedure schema - * @param vProcedure The procedure name - * @param vError The error message, if any - * @param vErrorCode The error code, if any - */ - DECLARE EXIT HANDLER FOR SQLEXCEPTION - GET DIAGNOSTICS CONDITION 1 - vError = MESSAGE_TEXT, - vErrorCode = RETURNED_SQLSTATE; - - CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); -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 DROP PROCEDURE IF EXISTS `payMethodClientAdd` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `payMethodClientAdd`() -BEGIN - INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) - SELECT CURDATE(), c.payMethodFk, c.id - FROM vn.client c - JOIN vn.payMethod p ON c.payMethodFk = p.id; - - TRUNCATE `bs`.`payMethodClientEvolution` ; - - INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) - SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) - FROM bs.payMethodClient p - JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente - FROM bs.ventas v - WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) - GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk - JOIN vn.payMethod pm ON p.payMethodFk = pm.id - GROUP BY dated,payMethodFk; -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 DROP PROCEDURE IF EXISTS `productivityAdd` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE) -BEGIN - - DECLARE vDateStart DATETIME DEFAULT vDate; - DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); - DECLARE myDepLft INT; - DECLARE myDepRgt INT; - - DROP TEMPORARY TABLE IF EXISTS tmp.productivity; - - CREATE TEMPORARY TABLE tmp.productivity - ENGINE = MEMORY - SELECT hh, - mm, - 000.00 as m3, - 000.00 as m3FV, - 000.00 as m3PCA, - 000.00 as m3Artificial, - 0 as workers, - 000.00 as wCost, - 0 as numCoordinadores, - 000.00 as costCoordinacion, - 0 as numSacadores, - 000.00 as costSacado, - 0 as numEncajadores, - 000.00 as costEncajado, - 0 as numPaletizadores, - 000.00 as costPaletizado, - 0 as numCamareros, - 000.00 as costCamara, - 0 as numComplementos, - 000.00 as costComplementos, - 0 as numArtificial, - 000.00 as costArtificial - FROM vn.dayMinute; - --- Trabajadores - CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker - CALL vn.workerDepartmentByDate(vDate); - - -- General - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - WHERE Almacen IN (1,44) - AND wdd.production - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.workers = sub.workers, p.wCost = sub.Bruto; - - -- Coordinadores - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'COORDINACION'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numCoordinadores = sub.workers, p.costCoordinacion = sub.Bruto; - - -- Sacado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'SACADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numSacadores = sub.workers, p.costSacado = sub.Bruto; - - -- Encajado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'ENCAJADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numEncajadores = sub.workers, p.costEncajado = sub.Bruto; - - -- Paletizado - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'PALETIZADO'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numPaletizadores = sub.workers, p.costPaletizado = sub.Bruto; - - -- Cámara - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'CAMARA'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numCamareros = sub.workers, p.costCamara = sub.Bruto; - - -- Complementos - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'COMPLEMENTOS'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numComplementos = sub.workers, p.costComplementos = sub.Bruto; - - -- Artificial - SELECT lft, rgt INTO myDepLft, myDepRgt - FROM vn.department - WHERE name = 'ARTIFICIAL'; - - UPDATE tmp.productivity p - JOIN - (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto - FROM tmp.dayMinuteWorker dmw - JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk - JOIN vn.department d ON d.id = wdd.departmentFk - WHERE Almacen IN (1,44) - AND d.lft BETWEEN myDepLft AND myDepRgt - GROUP BY Hora, Minuto - ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto - SET p.numArtificial = sub.workers, p.costArtificial = sub.Bruto; - - -- m3 - CALL vn.ticketBuiltTime(vDate); -- Genera la tabla tmp.ticketBuiltTime(ticketFk,builtTime) - CALL vn.ticketVolumeByDate_ventas(vDate); -- Genera la tabla tmp.ticketVolumeByDate(ticketFk,m3), filtrado por las ventas validas - CALL vn.ticketVolumeByDate_ventas_Artificial(vDate); -- Genera la tabla tmp.ticketVolumeByDate_ventas_Artificial - - UPDATE tmp.productivity p - JOIN - (SELECT HOUR(builtTime) hh, - MINUTE(builtTime) mm, - sum(tvd.m3) as m3, - sum(IF(t.warehouseFk = 1,tvd.m3,0)) as m3FV, - sum(IF(t.warehouseFk = 44,tvd.m3 - IFNULL(tvda.m3,0),0)) as m3PCA, - sum(IFNULL(tvda.m3,0)) as m3Artificial - FROM tmp.ticketBuiltTime tbt - JOIN tmp.ticketVolumeByDate tvd ON tvd.ticketFk = tbt.ticketFk - LEFT JOIN tmp.ticketVolumeByDate_Artificial tvda ON tvda.ticketFk = tbt.ticketFk - JOIN vn.ticket t ON t.id = tbt.ticketFk - WHERE t.warehouseFk IN (1,44) - GROUP BY hh,mm - ) v ON v.hh = p.hh AND v.mm = p.mm - SET p.m3 = v.m3, p.m3FV = v.m3FV, p.m3PCA = v.m3PCA, p.m3Artificial = v.m3Artificial; - - - - DELETE FROM bs.productivity - WHERE dated = vDate; - - INSERT INTO bs.productivity(dated, - hh, - mm, - m3, - m3FV, - m3PCA, - m3Artificial, - workers, - wCost, - numCoordinadores, - costCoordinacion, - numSacadores, - costSacado, - numEncajadores, - costEncajado, - numPaletizadores, - costPaletizado, - numCamareros, - costCamara, - numComplementos, - costComplementos, - numArtificial, - costArtificial) - SELECT vDate, - hh, - mm, - m3, - m3FV, - m3PCA, - m3Artificial, - workers, - wCost, - numCoordinadores, - costCoordinacion, - numSacadores, - costSacado, - numEncajadores, - costEncajado, - numPaletizadores, - costPaletizado, - numCamareros, - costCamara, - numComplementos, - costComplementos, - numArtificial, - costArtificial - FROM tmp.productivity p; - - -- Productivity Evolution - REPLACE bs.productivity_evolution(dated, m3productionCost) - SELECT CURDATE(), sum(wCost) / sum(m3) - FROM bs.productivity - WHERE dated BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE(); - - DROP TEMPORARY TABLE tmp.dayMinuteWorker; - DROP TEMPORARY TABLE tmp.productivity; - DROP TEMPORARY TABLE tmp.ticketBuiltTime; - DROP TEMPORARY TABLE tmp.ticketVolumeByDate; - DROP TEMPORARY TABLE tmp.workerDepartmentByDate; - - -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 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) -BEGIN - - DECLARE vEndingDate DATETIME; - - SET vEndingDate = vDateStart; - - WHILE vEndingDate <= vDateEndPeriod DO - REPLACE INTO bs.productivityDepartment - SELECT vEndingDate, - CAST(((productivityCoordinacionLastYear - productivityCoordinacion) / 2) * m3 AS DECIMAL (10,2)) AS amountCoordinacion, - CAST(((productivitySacadoLastYear - productivitySacado) / 2) * m3 AS DECIMAL (10,2)) AS amountSacado, - CAST(((productivityEncajadoLastYear - productivityEncajado) / 2) * m3 AS DECIMAL (10,2)) AS amountEncajado, - CAST(((productivityPaletizadoLastYear - productivityPaletizado) / 2) * m3 AS DECIMAL (10,2)) AS amountPaletizado, - CAST(((productivityCamaraLastYear - productivityCamara) / 2) * m3FV AS DECIMAL (10,2)) AS amountCamara, - CAST(((productivityComplementosLastYear - productivityComplementos) / 2) * m3PCA AS DECIMAL (10,2)) AS amountComplementos, - CAST(((productivityArtificialLastYear - productivityArtificial) / 2) * m3Artificial AS DECIMAL (10,2)) AS amountArtificia - FROM - (SELECT - SUM(p.m3) AS m3, SUM(p.m3FV) as m3FV, SUM(p.m3PCA) as m3PCA, SUM(p.m3Artificial) as m3Artificial, - SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacion, - SUM(p.costSacado) / SUM(p.m3) AS productivitySacado, - SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajado, - SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizado, - SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamara, - SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementos, - SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificial - FROM - bs.productivity p - WHERE - p.dated BETWEEN vDateStartPeriod AND vEndingDate) sub - JOIN - (SELECT - SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacionLastYear, - SUM(p.costSacado) / SUM(p.m3) AS productivitySacadoLastYear, - SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajadoLastYear, - SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizadoLastYear, - SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamaraLastYear, - SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementosLastYear, - SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificialLastYear - FROM - bs.productivity p - WHERE - p.dated BETWEEN DATE_ADD(vDateStartPeriod, INTERVAL - 1 YEAR) AND DATE_ADD(vEndingDate, INTERVAL - 1 YEAR)) sub1; - - SET vEndingDate = TIMESTAMPADD(DAY,1, vEndingDate); - END WHILE; - 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 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`() -BEGIN - CALL bs.productivityDepartmentAdd('2019-05-06', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK)); -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 DROP PROCEDURE IF EXISTS `productivityLauncher` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`() -BEGIN - - DECLARE vDateFrom DATE; - - SELECT LEAST(TIMESTAMPADD(MONTH, -1, CURDATE()),MAX(dated)) - INTO vDateFrom - FROM bs.productivity; - - WHILE CURDATE() > vDateFrom DO - CALL bs.productivityAdd(vDateFrom); - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - END WHILE; - - SET vDateFrom = TIMESTAMPADD(MONTH, -13, CURDATE()); - - WHILE TIMESTAMPADD(MONTH, -12, CURDATE()) > vDateFrom DO - CALL bs.productivityAdd(vDateFrom); - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - END WHILE; - -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 DROP PROCEDURE IF EXISTS `productivityLauncher_manual` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual`(vDateFrom DATE, vToDate DATE) -BEGIN - - TRUNCATE tmp.log; - - WHILE vToDate >= vDateFrom DO - - INSERT INTO tmp.log(text) VALUES (vDateFrom); - CALL bs.productivityAdd(vDateFrom); - - CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); - INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); - - SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); - - END WHILE; - - -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 DROP PROCEDURE IF EXISTS `pruebas` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `pruebas`(IN vDateStart DATE, IN vDateEnd DATE) -BEGIN - -WHILE vDateStart <> vDateEnd -DO - UPDATE indicators - SET countEmployee = - ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) - FROM - postgresql.business AS b - JOIN postgresql.profile p ON p.profile_id = b.provider_id - JOIN postgresql.person pe ON pe.person_id = p.person_id - LEFT JOIN - postgresql.business_labour AS bl ON bl.business_id = b.business_id - LEFT JOIN - postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id - WHERE - (vDateStart BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDateStart)) - AND pe.name = 'VERDNATURA LEVANTE SL' - ) - WHERE updated = vDateStart; - SET vDateStart = DATE_ADD(vDateStart, INTERVAL 1 DAY); - -END WHILE; -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 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) -BEGIN - DELETE FROM bs.salePersonEvolution - WHERE dated <= DATE_SUB(CURDATE(), INTERVAL 1 YEAR); - - - INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) - SELECT fecha dated, - CAST(SUM(importe) AS DECIMAL(10,2) ) amount, - CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , - IFNULL(salesPersonFk,0) salesPersonFk - FROM bs.ventas v - JOIN vn.client c ON v.Id_Cliente = c.id - JOIN vn.company co ON co.id = v.empresa_id - WHERE co.code = "VNL" AND fecha >= vDateStart - GROUP BY v.fecha,c.salesPersonFk - ORDER BY salesPersonFk,dated ASC; -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 DROP PROCEDURE IF EXISTS `userSundayRole` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole`() -BEGIN - -- 4996 Fran Natek Echevarria - DECLARE vDay INT; - SET vDay := (SELECT DAYOFWEEK(CURDATE())); - IF vDay = 1 THEN - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesAssistant"; - ELSE - UPDATE account.user u - JOIN account.role r - SET u.role = r.id - WHERE u.id = 4996 AND r.name = "salesPerson"; - 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 DROP PROCEDURE IF EXISTS `vendedores_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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(intYEAR INT, vQuarter INT) -BEGIN - - DECLARE comisionRate DOUBLE DEFAULT 0.029; - - REPLACE vendedores - SELECT c.Id_Trabajador - , intYEAR - , MONTH(v.fecha) intMONTH - , sum(importe) as importe - , sum(importe) * 0.029 as comision - , 0 as comisionCedida - , 0 as comisionArrendada - , 0 as comisionNuevos - - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month`; - - -- Ventas nuevas - UPDATE vendedores v - JOIN - ( - SELECT c.Id_Trabajador - , sum(importe) * 0.029 as comisionNueva - , t.`month` - , t.`year` - FROM ventas v - JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk - JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.Id_Trabajador, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionNuevos = sub.comisionNueva, v.comision = v.comision - sub.comisionNueva; - - -- Ventas cedidas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_old as Id_Trabajador - , sum(importe) * 0.029 * comision_old as cedido - , sum(importe) * 0.029 * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_old, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionCedida = sub.cedido, v.comision = v.comision - sub.cedido - sub.arrendada; - - -- Ventas arrendadas - UPDATE vendedores v - JOIN ( - SELECT cc.Id_Trabajador_new as Id_Trabajador - , sum(importe) * 0.029 * comision_new as arrendada - , t.`month` - , t.`year` - FROM ventas v - JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente - JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND - JOIN vn2008.`time` t on t.`date` = v.fecha - WHERE c.Id_Trabajador is not null - AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY cc.Id_Trabajador_new, t.`month` - ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año - SET v.comisionArrendada = sub.arrendada; - -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 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() -BEGIN - - call bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); - - call bs.vendedores_evolution_add; - -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 DROP PROCEDURE IF EXISTS `vendedores_evolution_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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add`() -BEGIN -/* - -Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes - -*/ - -DECLARE vYear, vMonth INTEGER; -DECLARE vCurYear, vCurMonth INTEGER; -DECLARE vFirstYear INTEGER DEFAULT 2017; -DECLARE vFirstMonth INTEGER DEFAULT 1; - -DECLARE vDateFrom DATE; -DECLARE vDateTo DATE; - -SET vCurYear = year(CURDATE()); -SET vCurMonth = month(CURDATE()); - -SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) - INTO vYear, vMonth - FROM bs.vendedores_evolution; - - WHILE (vYear < vCurYear) OR (vYear = vCurYear AND vMonth < vCurMonth) DO - - SELECT max(dated), TIMESTAMPADD(DAY,-364,max(dated)) INTO vDateTo, vDateFrom - FROM vn.time - WHERE year = vYear - AND month = vMonth; - - SELECT vDateTo, vDateFrom, vYear, vMonth; - - REPLACE bs.vendedores_evolution( workerFk - , year - , month - , sales) - SELECT c.salesPersonFk - , vYear as year - , vMonth as month - , sum(v.importe) as sales - FROM bs.ventas v - JOIN vn.client c on c.id = v.Id_Cliente - WHERE v.fecha BETWEEN vDateFrom AND vDateTo - AND c.salesPersonFk is not null - GROUP BY c.salesPersonFk; - - SET vMonth = vMonth + 1; - - IF vMonth = 13 THEN - - SET vMonth = 1; - SET vYear = vYear + 1; - - END IF; - - END WHILE; - - -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 DROP PROCEDURE IF EXISTS `ventas_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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - IF datSTART < '2015-10-01' OR datEND < '2015-10-01' THEN - CALL util.throw('fechaDemasiadoAntigua'); - END IF; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = datSTART; - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; - -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 DROP PROCEDURE IF EXISTS `ventas_add_launcher` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() -BEGIN - - call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); - -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 DROP PROCEDURE IF EXISTS `ventas_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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add__`(IN datSTART DATETIME, IN datEND DATETIME) -BEGIN - - DECLARE vStartingDate DATETIME; - DECLARE vEndingDate DATETIME; - DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - - SET datEND = util.dayEnd(datEND); - SET vStartingDate = GREATEST('2015-10-01',datSTART); - SET vEndingDate = vn2008.dayend(vStartingDate); - - DELETE - FROM ventas - WHERE fecha between vStartingDate and datEND; - - WHILE vEndingDate <= datEND DO - - REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) - SELECT Id_Movimiento, - SUM(IF(base, Cantidad * Valor, 0)) as importe, - SUM(IF(base, 0, Cantidad * Valor)) as recargo, - vStartingDate, - a.tipo_id, - cs.Id_Cliente, - t.empresa_id - FROM vn2008.Movimientos_componentes mc - JOIN bi.tarifa_componentes tc using(Id_Componente) - JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) - JOIN vn2008.Movimientos m using(Id_Movimiento) - JOIN vn2008.Articles a using(Id_Article) - JOIN vn2008.Tipos tp using(tipo_id) - JOIN vn2008.reinos r on r.id = tp.reino_id - JOIN vn2008.Tickets t using(Id_Ticket) - JOIN vn2008.Consignatarios cs using(Id_Consigna) - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - WHERE t.Fecha between vStartingDate and vEndingDate - AND datEND >= '2015-10-01' - AND c.typeFk IN ('Normal','handMaking','internalUse') - AND m.Cantidad <> 0 - AND a.tipo_id != TIPO_PATRIMONIAL - AND c.Id_Trabajador IS NOT NULL - AND m.Descuento <> 100 - AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) - GROUP BY mc.Id_Movimiento - HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; - - SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); - SET vEndingDate = util.dayEnd(vStartingDate); - - END WHILE; - -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 DROP PROCEDURE IF EXISTS `ventas_contables_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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) -BEGIN -/** - * Reemplaza las ventas contables. Es el origen de datos para el balance de Entradas - * - * @param vYear Año a reemplazar - * @param vMonth Mes a reemplazar - * - * - **/ -DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; - -DELETE FROM bs.ventas_contables - WHERE year = vYear - AND month = vMonth; - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - -INSERT INTO bs.ventas_contables(year - , month - , venta - , grupo - , reino_id - , tipo_id - , empresa_id - , gasto) - - SELECT vYear - , vMonth - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , tp.reino_id - , a.tipo_id - , t.empresa_id - , 7000000000 - + if(e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) * 1000000 - + tp.reino_id * 10000 as Gasto - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != TIPO_PATRIMONIAL - GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; - - -DROP TEMPORARY TABLE tmp.ticket_list; -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 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() -BEGIN - - call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); - -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 DROP PROCEDURE IF EXISTS `ventas_contables_por_cliente` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) -BEGIN - - -DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - -CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (Id_Ticket)) - SELECT Id_Ticket - FROM vn2008.Tickets t - JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura - WHERE year(f.Fecha) = vYear - AND month(f.Fecha) = vMonth; - - - - SELECT vYear Año - , vMonth Mes - , t.Id_Cliente - , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta - , if( - e.empresa_grupo = e2.empresa_grupo - ,1 - ,if(e2.empresa_grupo,2,0) - ) as grupo - , t.empresa_id empresa - FROM vn2008.Movimientos m - JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket - JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna - JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente - JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket - JOIN vn2008.Articles a on m.Id_Article = a.Id_Article - JOIN vn2008.empresa e on e.id = t.empresa_id - LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente - JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id - WHERE Cantidad <> 0 - AND Preu <> 0 - AND m.Descuento <> 100 - AND a.tipo_id != 188 - GROUP BY t.Id_Cliente, grupo,t.empresa_id; - -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 DROP PROCEDURE IF EXISTS `vivosMuertos` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() -BEGIN - -SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); -SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE()); - -DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; - -CREATE TEMPORARY TABLE tmp.VivosMuertos -SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto -FROM vn2008.Clientes c -JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm -LEFT JOIN - (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; - -UPDATE tmp.VivosMuertos vm -JOIN ( - SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Nuevo = 1; - -SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; - -UPDATE tmp.VivosMuertos vm -JOIN ( - SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente - FROM vn2008.Facturas f - JOIN vn2008.time tm ON tm.date = f.Fecha - WHERE Fecha BETWEEN @datSTART AND @datEND - GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente -SET Muerto = 1 -WHERE yearMonth < @lastYearMonth; - - SELECT * FROM tmp.VivosMuertos; - -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 DROP PROCEDURE IF EXISTS `workerSpeed` */; -/*!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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed`() -BEGIN - - /* #UPDATED PAK 2019/09/02 - * #PENDING REVIEW - * - * - * - * - */ - - DECLARE vLastUpdated DATETIME; - DECLARE vSecondsDelay INT DEFAULT 300; - - SELECT IFNULL(MAX(lastUpdated),CURDATE()) INTO vLastUpdated - FROM bs.workerSpeed; - - IF TIMESTAMPDIFF(SECOND, vLastUpdated, NOW()) > vSecondsDelay THEN - - DELETE FROM bs.workerSpeed ; - -- WHERE lastUpdated < CURDATE(); - - -- Sacadores - REPLACE bs.workerSpeed - SELECT workerCode, - accion, - warehouseFk, - CAST(60 * sumaLitros / time_to_sec(timediff(finished, started)) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sumaLitrosLastHour / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM - ( - SELECT warehouseFk, - accion, - workerCode, - sum(litros) as sumaLitros, - min(created) as started, - max(created) as finished, - sum(IF(created >= TIMESTAMPADD(HOUR, -1, NOW()),litros, 0)) as sumaLitrosLastHour - FROM - ( - SELECT t.warehouseFk, - st.saleFk, - st.isChecked, - st.originalQuantity, - a.accion, - st.created, - e.code, - w.firstname, - w.lastName, - w.code as workerCode, - r.cm3 * s.quantity / 1000 as litros, - s.concept - FROM vn.saleTracking st - LEFT JOIN - (SELECT saleFk - FROM vn.saleTracking st - JOIN vn.state e ON e.id = st.stateFk - WHERE st.created > CURDATE() - AND e.code LIKE 'PREVIOUS_PREPARATION') prevPrepSales ON prevPrepSales.saleFk = st.saleFk - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > TIMESTAMPADD(HOUR,-1,NOW()) - AND prevPrepSales.saleFk IS NULL - ) sub - GROUP BY warehouseFk, accion, workerCode - ) sub2; - - -- Encajadores - REPLACE bs.workerSpeed - SELECT code as workerCode, - 'ENCAJAR' as accion, - warehouseFk, - CAST(60 * sum(Litros) / time_to_sec(timediff(MAX(finished), MIN(started))) AS DECIMAL(10,1)) as LitrosMinuto, - CAST(sum(litrosUltimaHora) / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, - now() as lastUpdated - FROM ( - SELECT sv.ticketFk, - sum(sv.litros) as litros, - sum(IF(started > TIMESTAMPADD(HOUR,-1,NOW()),sv.litros,0)) as litrosUltimaHora, - code, - started, - finished, - cajas, - warehouseFk - FROM vn.saleVolume sv - JOIN - ( - SELECT ticketFk, - min(e.created) as started, - max(e.created) as finished, - max(counter) as cajas, - w.code, - t.warehouseFk - FROM vn.expedition e - JOIN vn.worker w ON w.id = e.workerFk - JOIN vn.ticket t ON t.id = e.ticketFk - WHERE e.created > CURDATE() - GROUP BY ticketFk - ) sub ON sub.ticketFk = sv.ticketFk - GROUP BY sv.ticketFk) sub2 - GROUP BY code; - - END IF; - - SELECT * FROM bs.workerSpeed; - -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 DROP PROCEDURE IF EXISTS `workerSpeed_detail` */; -/*!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_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed_detail`(vWorkerCode VARCHAR(3), vAction VARCHAR(25)) -BEGIN - - SELECT * FROM - ( - SELECT time_format(st.created,'%H:%i') as hora, - t.warehouseFk as Almacen, - t.id as ticketFk, - floor(sum(s.quantity * r.cm3) / 1000) as Litros - - FROM vn.saleTracking st - JOIN vn.sale s ON s.id = st.saleFk - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk - JOIN vn.worker w ON w.id = st.workerFk - JOIN vn.state e ON e.id = st.stateFk - JOIN vncontrol.accion a ON a.accion_id = st.actionFk - WHERE st.created > CURDATE() - AND a.accion LIKE vAction - AND w.code LIKE vWorkerCode - GROUP BY t.id) sub - ORDER BY hora; - -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 */ ; - -- -- Current Database: `cache` -- @@ -8863,9 +5409,9 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cacheCalc_clean`() -BEGIN - DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); - DELETE FROM cache_calc WHERE expires < vCleanTime; +BEGIN + DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW()); + DELETE FROM cache_calc WHERE expires < vCleanTime; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8883,27 +5429,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_end`(IN `v_calc` INT) -BEGIN - DECLARE v_cache_name VARCHAR(255); - DECLARE v_params VARCHAR(255); - - -- Libera el bloqueo y actualiza la fecha de ultimo refresco. - - UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id - SET - cc.last_refresh = NOW(), - cc.expires = ADDTIME(NOW(), c.lifetime), - cc.connection_id = NULL - WHERE cc.id = v_calc; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +BEGIN + DECLARE v_cache_name VARCHAR(255); + DECLARE v_params VARCHAR(255); + + -- Libera el bloqueo y actualiza la fecha de ultimo refresco. + + UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id + SET + cc.last_refresh = NOW(), + cc.expires = ADDTIME(NOW(), c.lifetime), + cc.connection_id = NULL + WHERE cc.id = v_calc; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -8921,88 +5467,88 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_start`(OUT `v_calc` INT, INOUT `v_refresh` INT, IN `v_cache_name` VARCHAR(50), IN `v_params` VARCHAR(100)) -proc: BEGIN - DECLARE v_valid BOOL; - DECLARE v_lock_id VARCHAR(100); - DECLARE v_cache_id INT; - DECLARE v_expires DATETIME; - DECLARE v_clean_time DATETIME; - - DECLARE EXIT HANDLER FOR SQLEXCEPTION - BEGIN - IF v_lock_id IS NOT NULL THEN - DO RELEASE_LOCK(v_lock_id); - END IF; - - RESIGNAL; - END; - - SET v_params = IFNULL(v_params, ''); - - -- Si el servidor se ha reiniciado invalida todos los calculos. - - SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; - - IF !v_valid - THEN - DELETE FROM cache_calc; - INSERT INTO cache_valid (valid) VALUES (TRUE); - END IF; - - -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. - - SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); - - IF !GET_LOCK(v_lock_id, 30) - THEN - SET v_calc = NULL; - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Comprueba si el calculo solicitado existe y esta actualizado. - - SELECT c.id, ca.id, ca.expires - INTO v_cache_id, v_calc, v_expires - FROM cache c - LEFT JOIN cache_calc ca - ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' - WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; - - -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. - - IF !v_refresh AND NOW() < v_expires - THEN - DO RELEASE_LOCK(v_lock_id); - SET v_refresh = FALSE; - LEAVE proc; - END IF; - - -- Si el calculo no existe le crea una entrada en la tabla de calculos. - - IF v_calc IS NULL - THEN - INSERT INTO cache_calc SET - cache_id = v_cache_id, - cacheName = v_cache_name, - params = v_params, - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID(); - - SET v_calc = LAST_INSERT_ID(); - ELSE - UPDATE cache_calc - SET - last_refresh = NULL, - expires = NULL, - connection_id = CONNECTION_ID() - WHERE id = v_calc; - END IF; - - -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. - - SET v_refresh = TRUE; +proc: BEGIN + DECLARE v_valid BOOL; + DECLARE v_lock_id VARCHAR(100); + DECLARE v_cache_id INT; + DECLARE v_expires DATETIME; + DECLARE v_clean_time DATETIME; + + DECLARE EXIT HANDLER FOR SQLEXCEPTION + BEGIN + IF v_lock_id IS NOT NULL THEN + DO RELEASE_LOCK(v_lock_id); + END IF; + + RESIGNAL; + END; + + SET v_params = IFNULL(v_params, ''); + + -- Si el servidor se ha reiniciado invalida todos los calculos. + + SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid; + + IF !v_valid + THEN + DELETE FROM cache_calc; + INSERT INTO cache_valid (valid) VALUES (TRUE); + END IF; + + -- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia. + + SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params); + + IF !GET_LOCK(v_lock_id, 30) + THEN + SET v_calc = NULL; + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Comprueba si el calculo solicitado existe y esta actualizado. + + SELECT c.id, ca.id, ca.expires + INTO v_cache_id, v_calc, v_expires + FROM cache c + LEFT JOIN cache_calc ca + ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' + WHERE c.name = v_cache_name COLLATE 'utf8_general_ci'; + + -- Si existe una calculo valido libera el bloqueo y devuelve su identificador. + + IF !v_refresh AND NOW() < v_expires + THEN + DO RELEASE_LOCK(v_lock_id); + SET v_refresh = FALSE; + LEAVE proc; + END IF; + + -- Si el calculo no existe le crea una entrada en la tabla de calculos. + + IF v_calc IS NULL + THEN + INSERT INTO cache_calc SET + cache_id = v_cache_id, + cacheName = v_cache_name, + params = v_params, + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID(); + + SET v_calc = LAST_INSERT_ID(); + ELSE + UPDATE cache_calc + SET + last_refresh = NULL, + expires = NULL, + connection_id = CONNECTION_ID() + WHERE id = v_calc; + END IF; + + -- Si se debe recalcular mantiene el bloqueo y devuelve su identificador. + + SET v_refresh = TRUE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9020,24 +5566,24 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_calc_unlock`(IN `v_calc` INT) -proc: BEGIN - DECLARE v_cache_name VARCHAR(50); - DECLARE v_params VARCHAR(100); - - IF v_calc IS NULL THEN - LEAVE proc; - END IF; - - SELECT c.name, ca.params INTO v_cache_name, v_params - FROM cache c - JOIN cache_calc ca ON c.id = ca.cache_id - WHERE ca.id = v_calc; - - DELETE FROM cache_calc WHERE id = v_calc; - - IF v_cache_name IS NOT NULL THEN - DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); - END IF; +proc: BEGIN + DECLARE v_cache_name VARCHAR(50); + DECLARE v_params VARCHAR(100); + + IF v_calc IS NULL THEN + LEAVE proc; + END IF; + + SELECT c.name, ca.params INTO v_cache_name, v_params + FROM cache c + JOIN cache_calc ca ON c.id = ca.cache_id + WHERE ca.id = v_calc; + + DELETE FROM cache_calc WHERE id = v_calc; + + IF v_cache_name IS NOT NULL THEN + DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, ''))); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9056,9 +5602,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `cache_clean`() NO SQL -BEGIN - CALL available_clean; - CALL visible_clean; +BEGIN + CALL available_clean; + CALL visible_clean; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -9076,13 +5622,13 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean`() -BEGIN - - DECLARE vDateShort DATETIME; - - SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); - - DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; +BEGIN + + DECLARE vDateShort DATETIME; + + SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE()); + + DELETE FROM cache.departure_limit WHERE Fecha < vDateShort; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10546,158 +7092,158 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ekt_load`(IN `vSelf` INT) -BEGIN - DECLARE vRef INT; - DECLARE vBuy INT; - DECLARE vItem INT; - DECLARE vQty INT; - DECLARE vPackage INT; - DECLARE vIsLot BOOLEAN; - DECLARE vForceToPacking INT DEFAULT 2; - - -- Carga los datos necesarios del EKT - - SELECT ref, qty, package INTO vRef, vQty, vPackage - FROM ekt e - LEFT JOIN item i ON e.ref = i.id - WHERE e.id = vSelf; - - -- Inserta el cubo si no existe - - IF vPackage = 800 - THEN - SET vPackage = 800 + vQty; - - INSERT IGNORE INTO vn2008.Cubos SET - Id_Cubo = vPackage, - x = 7200 / vQty, - y = 1; - ELSE - INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) - SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) - FROM bucket WHERE bucket_id = vPackage; - - IF ROW_COUNT() > 0 - THEN - INSERT INTO vn2008.mail SET - `subject` = 'Cubo añadido', - `text` = CONCAT('Se ha añadido el cubo: ', vPackage), - `to` = 'ekt@verdnatura.es'; - END IF; - END IF; - - -- Intenta obtener el artículo en base a los atributos holandeses - - INSERT IGNORE INTO item_track SET - item_id = vRef; - - SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem - FROM vn2008.buy_edi e - JOIN item_track t ON t.item_id = e.ref - LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref - LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id - JOIN vn2008.config cfg - WHERE e.id = vSelf - AND l.id != vSelf - AND c.Id_Article != cfg.generic_item - AND IF(t.s1, l.s1 = e.s1, TRUE) - AND IF(t.s2, l.s2 = e.s2, TRUE) - AND IF(t.s3, l.s3 = e.s3, TRUE) - AND IF(t.s4, l.s4 = e.s4, TRUE) - AND IF(t.s5, l.s5 = e.s5, TRUE) - AND IF(t.s6, l.s6 = e.s6, TRUE) - AND IF(t.kop, l.kop = e.kop, TRUE) - AND IF(t.pac, l.pac = e.pac, TRUE) - AND IF(t.cat, l.cat = e.cat, TRUE) - AND IF(t.ori, l.ori = e.ori, TRUE) - AND IF(t.pro, l.pro = e.pro, TRUE) - AND IF(t.sub, l.sub = e.sub, TRUE) - AND IF(t.package, l.package = e.package, TRUE) - AND c.Id_Article < 170000 - ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; - - -- Determina si el articulo se vende por lotes - - IF vItem - THEN - SELECT COUNT(*) > 0 INTO vIsLot - FROM vn2008.Articles a - LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id - WHERE a.Id_Article = vItem - AND t.`transaction`; - - -- Si el articulo se vende por lotes se inserta un nuevo artículo - - IF vIsLot - THEN - INSERT INTO vn2008.Articles ( - Article - ,Medida - ,Categoria - ,Id_Origen - ,iva_group_id - ,Foto - ,Color - ,Codintrastat - ,tipo_id - ,Tallos - ) - SELECT - i.`name` - ,IFNULL(e.s1, e.pac) - ,e.cat - ,IFNULL(o.id, 17) - ,IFNULL(a.iva_group_id, 1) - ,a.Foto - ,a.Color - ,a.Codintrastat - ,IFNULL(a.tipo_id, 10) - ,IF(a.tipo_id = 15, 0, 1) - FROM vn2008.buy_edi e - LEFT JOIN item i ON i.id = e.ref - LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori - LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem - WHERE e.id = vSelf; - - SET vItem = LAST_INSERT_ID(); - END IF; - END IF; - - -- Inserta la compra asociada al EKT - - INSERT INTO vn2008.Compres - ( - Id_Entrada - ,buy_edi_id - ,Costefijo - ,Id_Article - ,`grouping` - ,caja - ,Packing - ,Cantidad - ,Productor - ,Etiquetas - ,Id_Cubo - ) - SELECT - cfg.edi_entry - ,vSelf - ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri - ,IFNULL(vItem, cfg.generic_item) - ,IFNULL(c.`grouping`, e.pac) - ,vForceToPacking - ,@pac := e.pac / @t - ,@pac * e.qty - ,s.company_name - ,e.qty - ,IFNULL(c.Id_Cubo, e.package) - FROM vn2008.buy_edi e - LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy - LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article - LEFT JOIN supplier s ON e.pro = s.supplier_id - JOIN vn2008.config cfg - WHERE e.id = vSelf - LIMIT 1; +BEGIN + DECLARE vRef INT; + DECLARE vBuy INT; + DECLARE vItem INT; + DECLARE vQty INT; + DECLARE vPackage INT; + DECLARE vIsLot BOOLEAN; + DECLARE vForceToPacking INT DEFAULT 2; + + -- Carga los datos necesarios del EKT + + SELECT ref, qty, package INTO vRef, vQty, vPackage + FROM ekt e + LEFT JOIN item i ON e.ref = i.id + WHERE e.id = vSelf; + + -- Inserta el cubo si no existe + + IF vPackage = 800 + THEN + SET vPackage = 800 + vQty; + + INSERT IGNORE INTO vn2008.Cubos SET + Id_Cubo = vPackage, + x = 7200 / vQty, + y = 1; + ELSE + INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z) + SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10) + FROM bucket WHERE bucket_id = vPackage; + + IF ROW_COUNT() > 0 + THEN + INSERT INTO vn2008.mail SET + `subject` = 'Cubo añadido', + `text` = CONCAT('Se ha añadido el cubo: ', vPackage), + `to` = 'ekt@verdnatura.es'; + END IF; + END IF; + + -- Intenta obtener el artículo en base a los atributos holandeses + + INSERT IGNORE INTO item_track SET + item_id = vRef; + + SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem + FROM vn2008.buy_edi e + JOIN item_track t ON t.item_id = e.ref + LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref + LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id + JOIN vn2008.config cfg + WHERE e.id = vSelf + AND l.id != vSelf + AND c.Id_Article != cfg.generic_item + AND IF(t.s1, l.s1 = e.s1, TRUE) + AND IF(t.s2, l.s2 = e.s2, TRUE) + AND IF(t.s3, l.s3 = e.s3, TRUE) + AND IF(t.s4, l.s4 = e.s4, TRUE) + AND IF(t.s5, l.s5 = e.s5, TRUE) + AND IF(t.s6, l.s6 = e.s6, TRUE) + AND IF(t.kop, l.kop = e.kop, TRUE) + AND IF(t.pac, l.pac = e.pac, TRUE) + AND IF(t.cat, l.cat = e.cat, TRUE) + AND IF(t.ori, l.ori = e.ori, TRUE) + AND IF(t.pro, l.pro = e.pro, TRUE) + AND IF(t.sub, l.sub = e.sub, TRUE) + AND IF(t.package, l.package = e.package, TRUE) + AND c.Id_Article < 170000 + ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1; + + -- Determina si el articulo se vende por lotes + + IF vItem + THEN + SELECT COUNT(*) > 0 INTO vIsLot + FROM vn2008.Articles a + LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id + WHERE a.Id_Article = vItem + AND t.`transaction`; + + -- Si el articulo se vende por lotes se inserta un nuevo artículo + + IF vIsLot + THEN + INSERT INTO vn2008.Articles ( + Article + ,Medida + ,Categoria + ,Id_Origen + ,iva_group_id + ,Foto + ,Color + ,Codintrastat + ,tipo_id + ,Tallos + ) + SELECT + i.`name` + ,IFNULL(e.s1, e.pac) + ,e.cat + ,IFNULL(o.id, 17) + ,IFNULL(a.iva_group_id, 1) + ,a.Foto + ,a.Color + ,a.Codintrastat + ,IFNULL(a.tipo_id, 10) + ,IF(a.tipo_id = 15, 0, 1) + FROM vn2008.buy_edi e + LEFT JOIN item i ON i.id = e.ref + LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori + LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem + WHERE e.id = vSelf; + + SET vItem = LAST_INSERT_ID(); + END IF; + END IF; + + -- Inserta la compra asociada al EKT + + INSERT INTO vn2008.Compres + ( + Id_Entrada + ,buy_edi_id + ,Costefijo + ,Id_Article + ,`grouping` + ,caja + ,Packing + ,Cantidad + ,Productor + ,Etiquetas + ,Id_Cubo + ) + SELECT + cfg.edi_entry + ,vSelf + ,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri + ,IFNULL(vItem, cfg.generic_item) + ,IFNULL(c.`grouping`, e.pac) + ,vForceToPacking + ,@pac := e.pac / @t + ,@pac * e.qty + ,s.company_name + ,e.qty + ,IFNULL(c.Id_Cubo, e.package) + FROM vn2008.buy_edi e + LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy + LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article + LEFT JOIN supplier s ON e.pro = s.supplier_id + JOIN vn2008.config cfg + WHERE e.id = vSelf + LIMIT 1; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10747,154 +7293,154 @@ CREATE DEFINER=`root`@`%` PROCEDURE `exchange_new`( IN `vAuction` SMALLINT, IN `vPackage` INT, IN `vPutOrderFk` INT) -BEGIN +BEGIN /** * Adds a new exchange, generates it's barcode and * inserts/updates the transaction. When the referenced * transaction exists as provisional, updates it with - * the new values. - */ - DECLARE vEkt INT; - DECLARE vRewriteKop INT DEFAULT NULL; - DECLARE vBarcode CHAR(15) DEFAULT NULL; - DECLARE vIsDuplicated BOOL; + * the new values. + */ + DECLARE vEkt INT; + DECLARE vRewriteKop INT DEFAULT NULL; + DECLARE vBarcode CHAR(15) DEFAULT NULL; + DECLARE vIsDuplicated BOOL; DECLARE vUpdateExistent BOOL DEFAULT FALSE; - DECLARE duplicateKey CONDITION FOR 1062; + DECLARE duplicateKey CONDITION FOR 1062; + + DECLARE CONTINUE HANDLER FOR duplicateKey + SET vIsDuplicated = TRUE; + + -- Generates the barcode + + IF vAgj != 0 AND vAgj IS NOT NULL + THEN + SET vBarcode = CONCAT( + LPAD(vAuction, 2, 0), + LPAD(IFNULL(vClock, 99), 2, 0), + LPAD(DAYOFYEAR(vDate), 3, 0), + IF(vClock IS NULL OR vClock = 99, + LPAD(vAgj, 7, 0), + CONCAT(LPAD(vAgj, 5, 0), '01') + ), + '0' + ); + END IF; + + -- Rewrites the kop parameter + + IF vKop IS NULL THEN + SELECT defaultKop INTO vKop FROM exchangeConfig; + END IF; + + SELECT e.kop INTO vRewriteKop + FROM mailSender e + JOIN mail m ON m.senderFk = e.id + WHERE m.id = vMailFk; + + SET vKop = IFNULL(vRewriteKop, vKop); + + -- Inserts the new transaction - DECLARE CONTINUE HANDLER FOR duplicateKey - SET vIsDuplicated = TRUE; - - -- Generates the barcode - - IF vAgj != 0 AND vAgj IS NOT NULL - THEN - SET vBarcode = CONCAT( - LPAD(vAuction, 2, 0), - LPAD(IFNULL(vClock, 99), 2, 0), - LPAD(DAYOFYEAR(vDate), 3, 0), - IF(vClock IS NULL OR vClock = 99, - LPAD(vAgj, 7, 0), - CONCAT(LPAD(vAgj, 5, 0), '01') - ), - '0' - ); - END IF; - - -- Rewrites the kop parameter - - IF vKop IS NULL THEN - SELECT defaultKop INTO vKop FROM exchangeConfig; - END IF; - - SELECT e.kop INTO vRewriteKop - FROM mailSender e - JOIN mail m ON m.senderFk = e.id - WHERE m.id = vMailFk; - - SET vKop = IFNULL(vRewriteKop, vKop); - - -- Inserts the new transaction - - SET vIsDuplicated = FALSE; - INSERT INTO ekt SET - barcode = IFNULL(vBarcode, barcode) - ,deliveryNumber = vDeliveryNumber - ,entryYear = YEAR(vDate) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk; - - -- If it exists duplicado updates it - - IF NOT vIsDuplicated - THEN - SET vEkt = LAST_INSERT_ID(); - CALL ekt_load (vEkt); - - ELSEIF vDeliveryNumber != 0 - AND vDeliveryNumber IS NOT NULL - THEN - SELECT id INTO vEkt - FROM ekt - WHERE deliveryNumber = vDeliveryNumber; - - SELECT COUNT(*) = 0 INTO vUpdateExistent - FROM ekt t - JOIN `exchange` b ON b.ektFk = t.id - JOIN exchangeConfig c - WHERE t.deliveryNumber = vDeliveryNumber - AND t.entryYear = YEAR(vDate) - AND b.typeFk != c.presaleFk; - END IF; - - IF vUpdateExistent - THEN - UPDATE ekt SET - barcode = IFNULL(vBarcode, barcode) - ,fec = vDate - ,hor = vHour - ,ref = vRef - ,item = vItem - ,agj = vAgj - ,cat = vCat - ,pac = vPac - ,sub = vSub - ,kop = vKop - ,ptd = vPtd - ,pro = vPro - ,ori = vOrigin - ,ptj = vPtj - ,qty = vQuantiy - ,pri = vPrice - ,klo = vClock - ,s1 = vS1 - ,s2 = vS2 - ,s3 = vS3 - ,s4 = vS4 - ,s5 = vS5 - ,s6 = vS6 - ,k1 = vK1 - ,k2 = vK2 - ,k3 = vP1 - ,k4 = vP2 - ,auction = vAuction - ,package = vPackage - ,putOrderFk = vPutOrderFk - WHERE id = vEkt; - END IF; - - -- Registers the exchange - - INSERT INTO `exchange` SET - mailFk = vMailFk - ,typeFk = vType - ,ektFk = vEkt; + SET vIsDuplicated = FALSE; + INSERT INTO ekt SET + barcode = IFNULL(vBarcode, barcode) + ,deliveryNumber = vDeliveryNumber + ,entryYear = YEAR(vDate) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk; + + -- If it exists duplicado updates it + + IF NOT vIsDuplicated + THEN + SET vEkt = LAST_INSERT_ID(); + CALL ekt_load (vEkt); + + ELSEIF vDeliveryNumber != 0 + AND vDeliveryNumber IS NOT NULL + THEN + SELECT id INTO vEkt + FROM ekt + WHERE deliveryNumber = vDeliveryNumber; + + SELECT COUNT(*) = 0 INTO vUpdateExistent + FROM ekt t + JOIN `exchange` b ON b.ektFk = t.id + JOIN exchangeConfig c + WHERE t.deliveryNumber = vDeliveryNumber + AND t.entryYear = YEAR(vDate) + AND b.typeFk != c.presaleFk; + END IF; + + IF vUpdateExistent + THEN + UPDATE ekt SET + barcode = IFNULL(vBarcode, barcode) + ,fec = vDate + ,hor = vHour + ,ref = vRef + ,item = vItem + ,agj = vAgj + ,cat = vCat + ,pac = vPac + ,sub = vSub + ,kop = vKop + ,ptd = vPtd + ,pro = vPro + ,ori = vOrigin + ,ptj = vPtj + ,qty = vQuantiy + ,pri = vPrice + ,klo = vClock + ,s1 = vS1 + ,s2 = vS2 + ,s3 = vS3 + ,s4 = vS4 + ,s5 = vS5 + ,s6 = vS6 + ,k1 = vK1 + ,k2 = vK2 + ,k3 = vP1 + ,k4 = vP2 + ,auction = vAuction + ,package = vPackage + ,putOrderFk = vPutOrderFk + WHERE id = vEkt; + END IF; + + -- Registers the exchange + + INSERT INTO `exchange` SET + mailFk = vMailFk + ,typeFk = vType + ,ektFk = vEkt; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -12970,30 +9516,30 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `item_listAllocation`(IN `vWh` TINYINT, IN `vDate` DATE, IN `vType` INT, IN `vPrefix` VARCHAR(255), IN `vUseIds` BOOLEAN) -BEGIN -/** - * Lists visible items and it's box sizes of the specified - * type at specified date. - * - * @param vWh The warehouse id - * @param vDate The visible date - * @param vType The type id - * @param vPrefix The article prefix to filter or %NULL for all - * @param vUseIds Whether to order the result by item id - * @select List of visible items with it's box sizes - */ - CALL item_getVisible(vWh, vDate, vType, vPrefix); - - IF vUseIds - THEN - SELECT * FROM tmp.itemVisible - ORDER BY Id_Article; - ELSE - SELECT * FROM tmp.itemVisible - ORDER BY Article, packing; - END IF; - - DROP TEMPORARY TABLE tmp.itemVisible; +BEGIN +/** + * Lists visible items and it's box sizes of the specified + * type at specified date. + * + * @param vWh The warehouse id + * @param vDate The visible date + * @param vType The type id + * @param vPrefix The article prefix to filter or %NULL for all + * @param vUseIds Whether to order the result by item id + * @select List of visible items with it's box sizes + */ + CALL item_getVisible(vWh, vDate, vType, vPrefix); + + IF vUseIds + THEN + SELECT * FROM tmp.itemVisible + ORDER BY Id_Article; + ELSE + SELECT * FROM tmp.itemVisible + ORDER BY Article, packing; + END IF; + + DROP TEMPORARY TABLE tmp.itemVisible; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18334,8 +14880,8 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `log_add_beta`(IN `vTableName` VARCHAR(255), IN `vNewId` VARCHAR(255), IN `vOldId` VARCHAR(255)) -proc: BEGIN - -- XXX: Disabled while testing +proc: BEGIN + -- XXX: Disabled while testing DECLARE vLanded DATE; DECLARE vWarehouseFk INT; DECLARE vBuyerFk INT; @@ -18343,20 +14889,20 @@ proc: BEGIN DECLARE vItemFk INT; DECLARE vItemName VARCHAR(50); - -- LEAVE proc; + -- LEAVE proc; - IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vOldId, - operation = 'delete'; - END IF; - - IF vNewId IS NOT NULL THEN - INSERT IGNORE INTO `log` SET - tableName = vTableName, - tableId = vNewId, - operation = 'insert'; + IF vOldId IS NOT NULL AND !(vOldId <=> vNewId) THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vOldId, + operation = 'delete'; + END IF; + + IF vNewId IS NOT NULL THEN + INSERT IGNORE INTO `log` SET + tableName = vTableName, + tableId = vNewId, + operation = 'insert'; END IF; IF vTableName = 'buy' THEN @@ -18386,7 +14932,7 @@ proc: BEGIN END IF; END IF; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -18654,29 +15200,29 @@ CREATE DEFINER=`root`@`%` PROCEDURE `log_refreshSale`( BEGIN DROP TEMPORARY TABLE IF EXISTS tValues; CREATE TEMPORARY TABLE tValues - ENGINE = MEMORY - SELECT - m.id saleFk, - m.ticketFk, - m.itemFk, - t.warehouseFk, - t.shipped, + ENGINE = MEMORY + SELECT + m.id saleFk, + m.ticketFk, + m.itemFk, + t.warehouseFk, + t.shipped, ABS(m.quantity) quantity, m.created, TIMESTAMPADD(DAY, tp.life, t.shipped) expired, m.quantity < 0 isIn, - m.isPicked OR s.alertLevel > 1 isPicked - FROM vn.sale m - JOIN vn.ticket t ON t.id = m.ticketFk + m.isPicked OR s.alertLevel > 1 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.itemType tp ON tp.id = i.typeFk WHERE ( - vTableId IS NULL - OR (vTableName = 'ticket' AND t.id = vTableId) - OR (vTableName = 'sale' AND m.id = vTableId) - ) - AND t.shipped >= vn.getInventoryDate() + vTableId IS NULL + OR (vTableName = 'ticket' AND t.id = vTableId) + OR (vTableName = 'sale' AND m.id = vTableId) + ) + AND t.shipped >= vn.getInventoryDate() AND m.quantity != 0; REPLACE INTO inbound ( @@ -18709,7 +15255,7 @@ BEGIN FROM tValues WHERE !isIn; - DROP TEMPORARY TABLE tValues; + DROP TEMPORARY TABLE tValues; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21664,14 +18210,31 @@ CREATE TABLE `clientLog` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Temporary table structure for view `clientManaCache` +-- Table structure for table `clientManaCache` -- DROP TABLE IF EXISTS `clientManaCache`; -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientManaCache` ( + `clientFk` int(11) NOT NULL, + `mana` decimal(10,0) NOT NULL DEFAULT '0', + `dated` date NOT NULL, + PRIMARY KEY (`clientFk`,`dated`), + KEY `manaCustomerIdx1` (`dated`), + CONSTRAINT `cliente_fk` FOREIGN KEY (`clientFk`) REFERENCES `client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `clientManaCache__` +-- + +DROP TABLE IF EXISTS `clientManaCache__`; +/*!50001 DROP VIEW IF EXISTS `clientManaCache__`*/; SET @saved_cs_client = @@character_set_client; SET character_set_client = utf8; -/*!50001 CREATE VIEW `clientManaCache` AS SELECT +/*!50001 CREATE VIEW `clientManaCache__` AS SELECT 1 AS `clientFk`, 1 AS `mana`, 1 AS `dated`*/; @@ -30053,6 +26616,20 @@ CREATE TABLE `workerMana` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `workerManaExcluded` +-- + +DROP TABLE IF EXISTS `workerManaExcluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `workerManaExcluded` ( + `workerFk` int(11) NOT NULL, + PRIMARY KEY (`workerFk`), + CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Temporary table structure for view `workerMana__` -- @@ -30747,90 +27324,90 @@ DELIMITER ;; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; /*!50003 SET @saved_time_zone = @@time_zone */ ;; /*!50003 SET time_zone = 'SYSTEM' */ ;; -/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN - - DECLARE vCurrentCount INT; - DECLARE vCheckSum INT; - DECLARE vIsAlreadyNotified BOOLEAN; - DECLARE vTableQueue TEXT; - DECLARE vLineQueue TEXT; - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vCur CURSOR FOR - SELECT CONCAT(' - ', IFNULL(pq.id, ''), ' - ', IFNULL(p.path, ''),' - ', IFNULL(i.Informe, ''),' - ', IFNULL(e.Estado, ''),' - ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' - ', IFNULL(pq.`error`, ''),' - ') - FROM vn.printingQueue pq - LEFT JOIN vn.worker w ON w.id = pq.worker - LEFT JOIN vn.printer p ON p.id = pq.printer - LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report - JOIN vn2008.Estados e ON e.Id_Estado = pq.state - LIMIT 30; - - DECLARE CONTINUE HANDLER FOR NOT FOUND - SET vDone = TRUE; - - SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum - FROM vn.printingQueue WHERE state = 1; - - SELECT isAlreadyNotified INTO vIsAlreadyNotified - FROM printingQueueCheck; - - IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND - (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND - vIsAlreadyNotified = FALSE AND vCurrentCount > 0 - THEN - - SELECT ' - - - - - - - - ' INTO vTableQueue; - - OPEN vCur; - - l: LOOP - - SET vDone = FALSE; - - FETCH vCur INTO vLineQueue; - - IF vDone THEN - LEAVE l; - END IF; - - SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; - - END LOOP; - - CLOSE vCur; - - INSERT INTO vn2008.mail (`to`, subject, text) - VALUES ('cau@verdnatura.es', - 'servidor de impresion parado', - CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); - - UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; - END IF; - - IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND - vIsAlreadyNotified = TRUE - THEN - UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; - END IF; - - UPDATE printingQueueCheck - SET lastCount = vCurrentCount, - lastCheckSum = vCheckSum; - +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `printQueue_check` ON SCHEDULE EVERY 10 MINUTE STARTS '2019-11-08 00:00:00' ON COMPLETION PRESERVE ENABLE COMMENT 'Notifica en caso de que el servidor de impresión este parado' DO BEGIN + + DECLARE vCurrentCount INT; + DECLARE vCheckSum INT; + DECLARE vIsAlreadyNotified BOOLEAN; + DECLARE vTableQueue TEXT; + DECLARE vLineQueue TEXT; + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vCur CURSOR FOR + SELECT CONCAT(' + ', IFNULL(pq.id, ''), ' + ', IFNULL(p.path, ''),' + ', IFNULL(i.Informe, ''),' + ', IFNULL(e.Estado, ''),' + ', IFNULL(w.firstname, ''), " ", IFNULL(w.lastName, ''),' + ', IFNULL(pq.`error`, ''),' + ') + FROM vn.printingQueue pq + LEFT JOIN vn.worker w ON w.id = pq.worker + LEFT JOIN vn.printer p ON p.id = pq.printer + LEFT JOIN vn2008.Informes i ON i.Id_Informe = pq.report + JOIN vn2008.Estados e ON e.Id_Estado = pq.state + LIMIT 30; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SELECT COUNT(*), IFNULL(SUM(id),0) INTO vCurrentCount, vCheckSum + FROM vn.printingQueue WHERE state = 1; + + SELECT isAlreadyNotified INTO vIsAlreadyNotified + FROM printingQueueCheck; + + IF (SELECT lastCount FROM printingQueueCheck) = vCurrentCount AND + (SELECT lastCheckSum FROM printingQueueCheck) = vCheckSum AND + vIsAlreadyNotified = FALSE AND vCurrentCount > 0 + THEN + + SELECT ' + + + + + + + + ' INTO vTableQueue; + + OPEN vCur; + + l: LOOP + + SET vDone = FALSE; + + FETCH vCur INTO vLineQueue; + + IF vDone THEN + LEAVE l; + END IF; + + SELECT CONCAT(vTableQueue, vLineQueue) INTO vTableQueue; + + END LOOP; + + CLOSE vCur; + + INSERT INTO vn2008.mail (`to`, subject, text) + VALUES ('cau@verdnatura.es', + 'servidor de impresion parado', + CONCAT('Hay ', vCurrentCount, ' lineas bloqueadas', vTableQueue, '
Id ColaRuta ImpresoraInformeEstadoTrabajadorError
')); + + UPDATE printingQueueCheck SET isAlreadyNotified = TRUE; + END IF; + + IF (SELECT lastCount FROM printingQueueCheck) > vCurrentCount AND + vIsAlreadyNotified = TRUE + THEN + UPDATE printingQueueCheck SET isAlreadyNotified = FALSE; + END IF; + + UPDATE printingQueueCheck + SET lastCount = vCurrentCount, + lastCheckSum = vCheckSum; + END */ ;; /*!50003 SET time_zone = @saved_time_zone */ ;; /*!50003 SET sql_mode = @saved_sql_mode */ ;; @@ -34153,6 +30730,35 @@ DELIMITER ; /*!50003 SET character_set_client = @saved_cs_client */ ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP FUNCTION IF EXISTS `validationCode` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `validationCode`(vString VARCHAR(255)) RETURNS int(11) + DETERMINISTIC +BEGIN + + DECLARE vTail VARCHAR(3); + DECLARE vCode INT; + + SET vTail = LEFT(LPAD(vString,3,'0'),3); + + SET vCode = (ASCII(MID(vTail,1,1)) * ASCII(MID(vTail,2,1)) * ASCII(MID(vTail,3,1))) mod 1000; + + RETURN vCode; + +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 DROP FUNCTION IF EXISTS `workerIsBoss` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -35855,27 +32461,27 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clean__`() -BEGIN - DECLARE vDateShort DATETIME; - DECLARE oneYearAgo DATE; - DECLARE twoYearsAgo DATE; - DECLARE fourYearsAgo DATE; - - SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); - SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); - SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); - SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); - - DELETE FROM vn.message WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; - DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; - DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; - DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); - CALL shelving_clean; - +BEGIN + DECLARE vDateShort DATETIME; + DECLARE oneYearAgo DATE; + DECLARE twoYearsAgo DATE; + DECLARE fourYearsAgo DATE; + + SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); + SET oneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); + SET twoYearsAgo = TIMESTAMPADD(YEAR,-2,CURDATE()); + SET fourYearsAgo = TIMESTAMPADD(YEAR,-4,CURDATE()); + + DELETE FROM vn.message WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.messageInbox WHERE sendDate < vDateShort; + DELETE FROM vn.workerTimeControl WHERE timed < fourYearsAgo; + DELETE FROM vn.itemShelving WHERE created < CURDATE() AND visible = 0; + DELETE FROM vn.ticketDown WHERE created < TIMESTAMPADD(DAY,-1,CURDATE()); + CALL shelving_clean; + CALL vn.ticketPackagingRecovery; - + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -36663,54 +33269,54 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `clientRemoveWorker`() -BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vClientFk INT; - - DECLARE rs CURSOR FOR - SELECT c.clientFk - FROM tmp.clientGetDebt c - LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk - WHERE IFNULL(r.risk,0) = 0; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - SELECT cd.id as clientFk - FROM bs.clientDied cd - LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id - JOIN vn.client c ON c.id = cd.id - JOIN vn.province p ON p.id = c.provinceFk - JOIN vn.country co ON co.id = p.countryFk - WHERE cd.Aviso = 'TERCER AVISO' - AND cp.clientFk IS NULL - AND co.country NOT IN ('Portugal','Francia','España exento') - AND c.salesPersonFk IS NOT NULL; - - CALL vn.clientGetDebt(curdate()); - - DROP TEMPORARY TABLE IF EXISTS tmp.contador; - CREATE TEMPORARY TABLE tmp.contador (id INT) - ENGINE = MEMORY; - - OPEN rs; - FETCH rs INTO vClientFk; - - WHILE NOT done DO - INSERT INTO tmp.contador SET id = vClientFk; - CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vClientFk INT; + + DECLARE rs CURSOR FOR + SELECT c.clientFk + FROM tmp.clientGetDebt c + LEFT JOIN tmp.risk r ON r.clientFk = c.clientFk + WHERE IFNULL(r.risk,0) = 0; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; + CREATE TEMPORARY TABLE tmp.clientGetDebt + SELECT cd.id as clientFk + FROM bs.clientDied cd + LEFT JOIN vn.clientProtected cp ON cp.clientFk = cd.id + JOIN vn.client c ON c.id = cd.id + JOIN vn.province p ON p.id = c.provinceFk + JOIN vn.country co ON co.id = p.countryFk + WHERE cd.Aviso = 'TERCER AVISO' + AND cp.clientFk IS NULL + AND co.country NOT IN ('Portugal','Francia','España exento') + AND c.salesPersonFk IS NOT NULL; + + CALL vn.clientGetDebt(curdate()); + + DROP TEMPORARY TABLE IF EXISTS tmp.contador; + CREATE TEMPORARY TABLE tmp.contador (id INT) + ENGINE = MEMORY; + + OPEN rs; + FETCH rs INTO vClientFk; + + WHILE NOT done DO + INSERT INTO tmp.contador SET id = vClientFk; + CALL vn.clientGreugeSpray(vClientFk, TRUE, '',TRUE); UPDATE vn.client SET salesPersonFk = NULL WHERE id = vClientFk; INSERT INTO vn.clientLog (originFk, userFk, `action`, description) VALUES (vClientFk, account.userGetId(), 'update', CONCAT('Se ha desasignado el cliente por que no ha comprado en 3 meses')); - + REPLACE bs.clientNewBorn(clientFk, shipped) - VALUES(vClientFk, CURDATE()); - FETCH rs INTO vClientFk; - END WHILE; - - CLOSE rs; + VALUES(vClientFk, CURDATE()); + FETCH rs INTO vClientFk; + END WHILE; + + CLOSE rs; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -37774,6 +34380,89 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking`(vDuaFk INT) +BEGIN + + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vASIEN BIGINT DEFAULT 0; + DECLARE vCounter INT DEFAULT 0; + + DECLARE rs CURSOR FOR + SELECT e.invoiceInFk + FROM entry e + JOIN duaEntry de ON de.entryFk = e.id + JOIN invoiceIn ii ON ii.id = e.invoiceInFk + WHERE de.duaFk = vDuaFk + AND de.customsValue + AND ii.isBooked = FALSE; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + OPEN rs; + + UPDATE invoiceIn ii + JOIN entry e ON e.invoiceInFk = ii.id + JOIN duaEntry de ON de.entryFk = e.id + JOIN dua d ON d.id = de.duaFk + SET ii.isBooked = TRUE, + 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.isConfirmed = TRUE + WHERE d.id = vDuaFk; + + SELECT IFNULL(ASIEN,0) INTO vASIEN + FROM dua + WHERE id = vDuaFk; + + FETCH rs INTO vInvoiceFk; + + WHILE NOT done DO + + CALL invoiceInBookingMain(vInvoiceFk); + + IF vCounter > 0 OR vASIEN > 0 THEN + + UPDATE vn2008.XDiario x + JOIN vn.ledgerConfig lc ON lc.lastBookEntry = x.ASIEN + SET x.ASIEN = vASIEN; + + ELSE + + SELECT lastBookEntry INTO vASIEN FROM vn.ledgerConfig; + + END IF; + + SET vCounter = vCounter + 1; + + FETCH rs INTO vInvoiceFk; + + END WHILE; + + CLOSE rs; + + UPDATE dua + SET ASIEN = vASIEN + WHERE id = vDuaFk; + +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 DROP PROCEDURE IF EXISTS `duaInvoiceInBooking__` */; +/*!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 = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `duaInvoiceInBooking__`(vDuaFk INT) BEGIN DECLARE done BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -38326,216 +35015,216 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryConverter`(IN `vEntry` INT) -BEGIN - - DECLARE vWarehouseIn INT; - DECLARE vWarehouseOut INT; - DECLARE vTravel INT; - - DECLARE done BOOL DEFAULT FALSE; - - DECLARE vId_Entrada INT; - DECLARE vId_Article INT; - DECLARE vEtiquetas INT; - DECLARE vId_Cubo VARCHAR(10); - DECLARE vPacking INT; - DECLARE vGrouping INT; - DECLARE vCantidad INT; - DECLARE vCostefijo DECIMAL(10,3); - DECLARE vPortefijo DECIMAL(10,3); - DECLARE vEmbalajefijo DECIMAL(10); - DECLARE vComisionfija DECIMAL(10,3); - DECLARE vCaja INT; - DECLARE vNicho VARCHAR(5); - DECLARE vTarifa1 DECIMAL(10,2); - DECLARE vTarifa2 DECIMAL(10,2); - DECLARE vTarifa3 DECIMAL(10,2); - DECLARE vPVP DECIMAL(10,2); - DECLARE vCompra INT; - - DECLARE rs CURSOR FOR - SELECT - b.Id_Entrada, - b.Id_Article, - b.Etiquetas, - b.Id_Cubo, - b.Packing, - b.`grouping`, - b.Cantidad, - b.Costefijo, - b.Portefijo, - b.Embalajefijo, - b.Comisionfija, - b.caja, - b.Nicho, - b.Tarifa1, - b.Tarifa2, - b.Tarifa3, - b.PVP - FROM vn2008.Compres b - JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article - WHERE Id_Entrada = vEntry; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - SELECT warehouseInFk, warehouseOutFk, tr.id - INTO vWarehouseIn, vWarehouseOut, vTravel - FROM travel tr - JOIN entry e ON e.travelFk = tr.id - WHERE e.id = vEntry; - - UPDATE travel - SET warehouseInFk = vWarehouseOut, - warehouseOutFk = vWarehouseIn - WHERE id = vTravel; - - UPDATE vn2008.Compres c - LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article - SET Etiquetas = 0, Cantidad = 0 - WHERE c.Id_Entrada = vEntry - AND ic.espItemFk IS NULL; - - OPEN rs; - - DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - WHILE NOT done DO - - -- Primero la linea original con las cantidades invertidas - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - VALUES - ( - vId_Entrada, - vId_Article, - - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP); - - -- Ahora la linea nueva, con el item genérico - INSERT INTO vn2008.Compres - ( - Id_Entrada, - Id_Article, - Etiquetas, - Id_Cubo, - Packing, - `grouping`, - Cantidad, - Costefijo, - Portefijo, - Embalajefijo, - Comisionfija, - caja, - Nicho, - Tarifa1, - Tarifa2, - Tarifa3, - PVP - ) - SELECT - vId_Entrada, - genItemFk as Id_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP - FROM itemConversor - WHERE espItemFk = vId_Article; - - SELECT LAST_INSERT_ID() - INTO vCompra; - - REPLACE vn2008.Compres_mark(Id_Compra,`comment`) - SELECT vCompra, vId_Article; - - - FETCH rs INTO - vId_Entrada, - vId_Article, - vEtiquetas, - vId_Cubo, - vPacking, - vGrouping, - vCantidad, - vCostefijo, - vPortefijo, - vEmbalajefijo, - vComisionfija, - vCaja, - vNicho, - vTarifa1, - vTarifa2, - vTarifa3, - vPVP; - - END WHILE; - - - CLOSE rs; - - - +BEGIN + + DECLARE vWarehouseIn INT; + DECLARE vWarehouseOut INT; + DECLARE vTravel INT; + + DECLARE done BOOL DEFAULT FALSE; + + DECLARE vId_Entrada INT; + DECLARE vId_Article INT; + DECLARE vEtiquetas INT; + DECLARE vId_Cubo VARCHAR(10); + DECLARE vPacking INT; + DECLARE vGrouping INT; + DECLARE vCantidad INT; + DECLARE vCostefijo DECIMAL(10,3); + DECLARE vPortefijo DECIMAL(10,3); + DECLARE vEmbalajefijo DECIMAL(10); + DECLARE vComisionfija DECIMAL(10,3); + DECLARE vCaja INT; + DECLARE vNicho VARCHAR(5); + DECLARE vTarifa1 DECIMAL(10,2); + DECLARE vTarifa2 DECIMAL(10,2); + DECLARE vTarifa3 DECIMAL(10,2); + DECLARE vPVP DECIMAL(10,2); + DECLARE vCompra INT; + + DECLARE rs CURSOR FOR + SELECT + b.Id_Entrada, + b.Id_Article, + b.Etiquetas, + b.Id_Cubo, + b.Packing, + b.`grouping`, + b.Cantidad, + b.Costefijo, + b.Portefijo, + b.Embalajefijo, + b.Comisionfija, + b.caja, + b.Nicho, + b.Tarifa1, + b.Tarifa2, + b.Tarifa3, + b.PVP + FROM vn2008.Compres b + JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article + WHERE Id_Entrada = vEntry; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT warehouseInFk, warehouseOutFk, tr.id + INTO vWarehouseIn, vWarehouseOut, vTravel + FROM travel tr + JOIN entry e ON e.travelFk = tr.id + WHERE e.id = vEntry; + + UPDATE travel + SET warehouseInFk = vWarehouseOut, + warehouseOutFk = vWarehouseIn + WHERE id = vTravel; + + UPDATE vn2008.Compres c + LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article + SET Etiquetas = 0, Cantidad = 0 + WHERE c.Id_Entrada = vEntry + AND ic.espItemFk IS NULL; + + OPEN rs; + + DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry; + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + WHILE NOT done DO + + -- Primero la linea original con las cantidades invertidas + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + VALUES + ( + vId_Entrada, + vId_Article, + - vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + - vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP); + + -- Ahora la linea nueva, con el item genérico + INSERT INTO vn2008.Compres + ( + Id_Entrada, + Id_Article, + Etiquetas, + Id_Cubo, + Packing, + `grouping`, + Cantidad, + Costefijo, + Portefijo, + Embalajefijo, + Comisionfija, + caja, + Nicho, + Tarifa1, + Tarifa2, + Tarifa3, + PVP + ) + SELECT + vId_Entrada, + genItemFk as Id_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP + FROM itemConversor + WHERE espItemFk = vId_Article; + + SELECT LAST_INSERT_ID() + INTO vCompra; + + REPLACE vn2008.Compres_mark(Id_Compra,`comment`) + SELECT vCompra, vId_Article; + + + FETCH rs INTO + vId_Entrada, + vId_Article, + vEtiquetas, + vId_Cubo, + vPacking, + vGrouping, + vCantidad, + vCostefijo, + vPortefijo, + vEmbalajefijo, + vComisionfija, + vCaja, + vNicho, + vTarifa1, + vTarifa2, + vTarifa3, + vPVP; + + END WHILE; + + + CLOSE rs; + + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38597,62 +35286,62 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `entryPrepare`(IN `idE` BIGINT) -BEGIN - SELECT - b.quantity / b.packing AS Paquetes, - b.packing AS `Grouping`, - barcode, - 'ASEGURADO' AS asegurado, - ic.name, - ic.order, - s.name AS Consignatario, - e.supplierFk AS Id_Cliente, - e.isOrdered, - e.isConfirmed, - 10 AS Calidad, - LPAD(IFNULL(cpd.id, ip.code), - 5, - '0') AS path, - b.entryFk AS Id_Ticket, - t.landed AS Fecha, - b.itemFk, - b.quantity, - i.name AS Concepte, - i.size, - i.inkFk, - i.category, - o.code AS Origen, - 0 AS Bultos, - wIn.`name` AS Tipo, - 0 AS OK, - 0 AS Reservado, - i.stems, - b.id AS Id_Movimiento, - ip.code, - 'PEDIDO ASEGURADO' AS MSG, - 0 AS Seguro, - i.image, - pr.name AS producer - FROM vn.buy b - JOIN vn.entry e ON b.entryFk = e.id - JOIN vn.travel t ON t.id = e.travelFk - JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk - JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk - JOIN vn.item i ON i.id = b.itemFk - JOIN vn.itemType it ON it.id =i.typeFk - JOIN vn.itemCategory ic ON ic.id = it.categoryFk - JOIN vn.packaging pkg ON pkg.id = b.packageFk - LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk - LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk - LEFT JOIN vn.origin o ON o.id = i.originFk - LEFT JOIN vn.supplier s ON s.id = e.supplierFk - LEFT JOIN vn.producer pr on pr.id = i.producerFk - LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway - WHERE - NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid - AND e.id = 158772 - AND i.typeFk IS NOT NULL - AND ic.merchandise IS NOT FALSE; +BEGIN + SELECT + b.quantity / b.packing AS Paquetes, + b.packing AS `Grouping`, + barcode, + 'ASEGURADO' AS asegurado, + ic.name, + ic.order, + s.name AS Consignatario, + e.supplierFk AS Id_Cliente, + e.isOrdered, + e.isConfirmed, + 10 AS Calidad, + LPAD(IFNULL(cpd.id, ip.code), + 5, + '0') AS path, + b.entryFk AS Id_Ticket, + t.landed AS Fecha, + b.itemFk, + b.quantity, + i.name AS Concepte, + i.size, + i.inkFk, + i.category, + o.code AS Origen, + 0 AS Bultos, + wIn.`name` AS Tipo, + 0 AS OK, + 0 AS Reservado, + i.stems, + b.id AS Id_Movimiento, + ip.code, + 'PEDIDO ASEGURADO' AS MSG, + 0 AS Seguro, + i.image, + pr.name AS producer + FROM vn.buy b + JOIN vn.entry e ON b.entryFk = e.id + JOIN vn.travel t ON t.id = e.travelFk + JOIN vn.warehouse wIn ON wIn.id = t.warehouseInFk + JOIN vn.warehouse wOut ON wOut.id = t.warehouseOutFk + JOIN vn.item i ON i.id = b.itemFk + JOIN vn.itemType it ON it.id =i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + JOIN vn.packaging pkg ON pkg.id = b.packageFk + LEFT JOIN vn.itemPlacement ip ON i.id = ip.itemFk AND ip.warehouseFk = wIn.id AND ip.warehouseFk = t.warehouseOutFk + LEFT JOIN (SELECT itemFk, code AS barcode FROM vn.itemBarcode GROUP BY itemFk) ib ON ib.itemFk = b.itemFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN vn.supplier s ON s.id = e.supplierFk + LEFT JOIN vn.producer pr on pr.id = i.producerFk + LEFT JOIN vn.coolerPathDetail cpd ON LEFT(ip.code, 3) = cpd.hallway + WHERE + NOT wIn.isFeedStock AND NOT e.isInventory AND NOT e.isRaid + AND e.id = 158772 + AND i.typeFk IS NOT NULL + AND ic.merchandise IS NOT FALSE; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -42249,38 +38938,38 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemLastEntries`(IN `vItem` INT, IN `vDays` DATE) -BEGIN - SELECT - w.id AS warehouseFk, - w.name AS warehouse, - tr.landed, - b.entryFk, - b.isIgnored, - b.price2, - b.price3, - b.stickers, - b.packing, - b.`grouping`, - b.groupingMode, - i.stems, - b.quantity, - b.buyingValue, - b.packageFk , - s.id AS supplierFk, - s.name AS supplier - FROM itemType it - RIGHT JOIN (entry e - LEFT JOIN supplier s ON s.id = e.supplierFk - RIGHT JOIN buy b ON b.entryFk = e.id - LEFT JOIN item i ON i.id = b.itemFk - LEFT JOIN ink ON ink.id = i.inkFk - LEFT JOIN travel tr ON tr.id = e.travelFk - LEFT JOIN warehouse w ON w.id = tr.warehouseInFk - LEFT JOIN origin o ON o.id = i.originFk - ) ON it.id = i.typeFk - LEFT JOIN edi.ekt ek ON b.ektFk = ek.id - WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() - ORDER BY tr.landed DESC , b.id DESC; +BEGIN + SELECT + w.id AS warehouseFk, + w.name AS warehouse, + tr.landed, + b.entryFk, + b.isIgnored, + b.price2, + b.price3, + b.stickers, + b.packing, + b.`grouping`, + b.groupingMode, + i.stems, + b.quantity, + b.buyingValue, + b.packageFk , + s.id AS supplierFk, + s.name AS supplier + FROM itemType it + RIGHT JOIN (entry e + LEFT JOIN supplier s ON s.id = e.supplierFk + RIGHT JOIN buy b ON b.entryFk = e.id + LEFT JOIN item i ON i.id = b.itemFk + LEFT JOIN ink ON ink.id = i.inkFk + LEFT JOIN travel tr ON tr.id = e.travelFk + LEFT JOIN warehouse w ON w.id = tr.warehouseInFk + LEFT JOIN origin o ON o.id = i.originFk + ) ON it.id = i.typeFk + LEFT JOIN edi.ekt ek ON b.ektFk = ek.id + WHERE b.itemFk = vItem And tr.shipped BETWEEN vDays AND CURDATE() + ORDER BY tr.landed DESC , b.id DESC; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -45553,9 +42242,9 @@ 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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -46187,77 +42876,77 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleItemShelvingMake`(IN `vTicketFk` INT, IN `vSectorFk` INT) -BEGIN - - SET @rest:= CAST(0 AS DECIMAL(10,0)); - SET @saleFk := CAST(0 AS DECIMAL(10,0)); - SET @reserved := CAST(0 AS DECIMAL(10,0)); - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN sale s ON s.id = sis.saleFk - SET ish.visible = sis.quantity + ish.visible, - ish.available = sis.quantity + ish.visible - WHERE s.ticketFk = vTicketFk; - - DELETE sis.* - FROM saleItemShelving sis - JOIN sale s ON s.id = sis.saleFk - WHERE s.ticketFk = vTicketFk; - - INSERT INTO saleItemShelving( saleFk, - itemShelvingFk, - quantity, - ubication) - SELECT saleFk, - itemShelvingFk, - CAST(Reserved as DECIMAL(10,0)) as Reserved, - ubication - FROM - (SELECT saleFk, - itemShelvingFk, - ubication, - @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, - @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, - @rest := @rest - @reserved, - @saleFk := saleFk - FROM - ( SELECT s.id as saleFk, - ish.created, - ish.id as itemShelvingFk, - ish.available, - s.quantity, - ish.packing, - CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication - FROM vn.sale s - JOIN vn.ticket t ON t.id = s.ticketFk - JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk - JOIN vn.parking p ON p.sectorFk = sc.id - JOIN vn.shelving sh ON sh.parkingFk = p.id - JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk - WHERE t.id = vTicketFk - AND sc.id = vSectorFk - AND s.quantity MOD ish.packing = 0 - AND s.quantity >= ish.packing - ORDER BY s.id, - sh.priority DESC, - ish.packing DESC, - ish.created - ) sub - ) sub2 - WHERE Reserved > 0; - - UPDATE vn.itemShelving ish - JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id - JOIN vn.sale s ON s.id = sis.saleFk - SET ish.available = ish.visible - sis.quantity, - ish.visible = ish.visible - sis.quantity - WHERE s.ticketFk = vTicketFk - AND s.isPicked = FALSE; - - CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); - - +BEGIN + + SET @rest:= CAST(0 AS DECIMAL(10,0)); + SET @saleFk := CAST(0 AS DECIMAL(10,0)); + SET @reserved := CAST(0 AS DECIMAL(10,0)); + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN sale s ON s.id = sis.saleFk + SET ish.visible = sis.quantity + ish.visible, + ish.available = sis.quantity + ish.visible + WHERE s.ticketFk = vTicketFk; + + DELETE sis.* + FROM saleItemShelving sis + JOIN sale s ON s.id = sis.saleFk + WHERE s.ticketFk = vTicketFk; + + INSERT INTO saleItemShelving( saleFk, + itemShelvingFk, + quantity, + ubication) + SELECT saleFk, + itemShelvingFk, + CAST(Reserved as DECIMAL(10,0)) as Reserved, + ubication + FROM + (SELECT saleFk, + itemShelvingFk, + ubication, + @rest := IF(@saleFk = saleFk, @rest, quantity) as Falta, + @reserved := IF(available < @rest, available, IF(@rest < packing,0,@rest)) as Reserved, + @rest := @rest - @reserved, + @saleFk := saleFk + FROM + ( SELECT s.id as saleFk, + ish.created, + ish.id as itemShelvingFk, + ish.available, + s.quantity, + ish.packing, + CONCAT(p.`column`, '-',p.`row`,': ', sh.code ) as ubication + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.sector sc ON sc.warehouseFk = t.warehouseFk + JOIN vn.parking p ON p.sectorFk = sc.id + JOIN vn.shelving sh ON sh.parkingFk = p.id + JOIN vn.itemShelving ish ON ish.shelvingFk = sh.code AND ish.itemFk = s.itemFk + WHERE t.id = vTicketFk + AND sc.id = vSectorFk + AND s.quantity MOD ish.packing = 0 + AND s.quantity >= ish.packing + ORDER BY s.id, + sh.priority DESC, + ish.packing DESC, + ish.created + ) sub + ) sub2 + WHERE Reserved > 0; + + UPDATE vn.itemShelving ish + JOIN vn.saleItemShelving sis ON sis.itemShelvingFk = ish.id + JOIN vn.sale s ON s.id = sis.saleFk + SET ish.available = ish.visible - sis.quantity, + ish.visible = ish.visible - sis.quantity + WHERE s.ticketFk = vTicketFk + AND s.isPicked = FALSE; + + CALL vn.saleItemShelvingIsPicked(vTicketFk, TRUE); + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -46268,92 +42957,92 @@ 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_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `saleMove`(IN vSaleFk BIGINT, IN vQuantity BIGINT) BEGIN +-- JGF is working in this file 2019-12-20 + DECLARE vclientFk INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk INT; + DECLARE vCompanyFk INT; + DECLARE vAddressFk INT; + DECLARE vAgencyModeFk INT; + DECLARE vNewTicket BIGINT; + DECLARE vNewSale BIGINT; + DECLARE vLanded DATE; + DECLARE vDateStart DATETIME; + DECLARE vDateEnd DATETIME; + DECLARE vAuxId INT; + DECLARE vNumLine INT; + DECLARE vItemFk INT; - DECLARE vclientFk INT; - DECLARE vShipped DATE; - DECLARE vWarehouseFk INT; - DECLARE vCompanyFk INT; - DECLARE vAddressFk INT; - DECLARE vAgencyModeFk INT; - DECLARE vNewTicket BIGINT; - DECLARE vNewSale BIGINT; - DECLARE vLanded DATE; - DECLARE vDateStart DATETIME; - DECLARE vDateEnd DATETIME; - DECLARE vAuxId INT; - DECLARE vNumLine INT; - DECLARE vItemFk INT; - - SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id + SELECT clientFk,shipped,warehouseFk,companyFk,addressFk,agencyModeFk,landed,t.id INTO vclientFk,vShipped,vWarehouseFk,vCompanyFk,vAddressFk,vAgencyModeFk,vLanded,vAuxId FROM ticket t JOIN sale s ON s.ticketFk=t.id WHERE s.id = vSaleFk; - SET vDateStart = TIMESTAMP(vShipped); - SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); + SET vDateStart = TIMESTAMP(vShipped); + SET vDateEnd = TIMESTAMP(vShipped, '23:59:59'); - SELECT t.id INTO vNewTicket + SELECT t.id INTO vNewTicket FROM ticket t JOIN ticketState ts ON ts.ticketFk=t.id WHERE t.addressFk = vAddressFk AND t.warehouseFk = vWarehouseFk - AND t.agencyModeFk = vAgencyModeFk - AND t.landed <=> vLanded - AND t.shipped BETWEEN vDateStart AND vDateEnd - AND t.refFk IS NULL - AND t.clientFk <> 1118 - AND t.id <> vAuxId - AND IFNULL(ts.alertLevel,0) = 0 + AND t.agencyModeFk = vAgencyModeFk + AND t.landed <=> vLanded + AND t.shipped BETWEEN vDateStart AND vDateEnd + AND t.refFk IS NULL + AND t.clientFk <> 1118 + AND t.id <> vAuxId + AND IFNULL(ts.alertLevel,0) = 0 LIMIT 1; -IF vNewTicket IS NULL - THEN + IF vNewTicket IS NULL THEN CALL vn.ticket_Clone(vAuxId, vNewTicket); - /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ - END IF; + /*CALL vn2008.bionic_calc_ticket(vNewTicket);*/ + END IF; - INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) - SELECT vNewTicket, getWorker(), s.id - FROM state s - WHERE s.code = 'FIXING'; + INSERT INTO ticketTracking(ticketFk, workerFk, stateFk) + SELECT vNewTicket, getWorker(), s.id + FROM state s + WHERE s.code = 'FIXING'; - /*parche para campapña, eliminar y modificar el front*/ -SELECT COUNT(id) INTO vNumLine - FROM sale s - WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); - - IF vNumLine = 0 THEN - - INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) - SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + /*parche para campapña, eliminar y modificar el front*/ + SELECT COUNT(id) INTO vNumLine FROM sale s - WHERE s.id = vSaleFk; + WHERE s.ticketFk = vNewTicket AND s.itemFk = (SELECT itemFk FROM sale WHERE id = vSaleFk); - SELECT LAST_INSERT_ID() INTO vNewSale; + IF vNumLine = 0 THEN - INSERT INTO saleComponent(saleFk, componentFk, `value`) - SELECT vNewSale, componentFk, `value` - FROM saleComponent - WHERE saleFk = vSaleFk; - -ELSE IF vQuantity <> 0 THEN + INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount) + SELECT vNewTicket, itemFk, concept, vQuantity, price, discount + FROM sale s + WHERE s.id = vSaleFk; + + SELECT LAST_INSERT_ID() INTO vNewSale; + + INSERT INTO saleComponent(saleFk, componentFk, `value`) + SELECT vNewSale, componentFk, `value` + FROM saleComponent + WHERE saleFk = vSaleFk; + + ELSE + IF vQuantity <> 0 THEN - SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; - UPDATE sale SET quantity = vQuantity - WHERE ticketFk = vNewTicket AND itemFk = vItemFk; + SELECT itemFk INTO vItemFk FROM sale WHERE id = vSaleFk; + UPDATE sale SET quantity = vQuantity + WHERE ticketFk = vNewTicket AND itemFk = vItemFk; -END IF; -END IF; + END IF; + END IF; END ;; DELIMITER ; @@ -46756,33 +43445,33 @@ DELIMITER ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `scanTreeCreate`() -BEGIN - CALL nestTree( - 'vn2008', - 'scan', - 'vn2008', - 'scanTree' - ); - - UPDATE vn2008.scanTree st - JOIN ( - SELECT sl.scan_id, - MAX(sl.odbc_date) lastScanned, - COUNT(DISTINCT t.routeFk) routeCount, - MIN(t.routeFk) mod 1000 as minRoute, - MAX(t.routeFk) mod 1000 as maxRoute, - COUNT(sl.scan_line_id) as scanned - FROM vn2008.scan_line sl - JOIN expedition e ON e.id = sl.`code` - JOIN ticket t ON t.id = e.ticketFk - WHERE t.routeFk - GROUP BY sl.scan_id - ) rs ON rs.scan_id = st.id - SET st.lastScanned = rs.lastScanned, - st.routeCount = rs.routeCount, - st.minRoute = rs.minRoute, - st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), - st.scanned = rs.scanned; +BEGIN + CALL nestTree( + 'vn2008', + 'scan', + 'vn2008', + 'scanTree' + ); + + UPDATE vn2008.scanTree st + JOIN ( + SELECT sl.scan_id, + MAX(sl.odbc_date) lastScanned, + COUNT(DISTINCT t.routeFk) routeCount, + MIN(t.routeFk) mod 1000 as minRoute, + MAX(t.routeFk) mod 1000 as maxRoute, + COUNT(sl.scan_line_id) as scanned + FROM vn2008.scan_line sl + JOIN expedition e ON e.id = sl.`code` + JOIN ticket t ON t.id = e.ticketFk + WHERE t.routeFk + GROUP BY sl.scan_id + ) rs ON rs.scan_id = st.id + SET st.lastScanned = rs.lastScanned, + st.routeCount = rs.routeCount, + st.minRoute = rs.minRoute, + st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL), + st.scanned = rs.scanned; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -48348,9 +45037,9 @@ 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 = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -48453,6 +45142,9 @@ BEGIN ELSE -- Albaran_print CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), NULL); + -- Comentar al pasar a nuevo cierre + INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); + -- INSERT INTO END IF; -- ticketClosure end @@ -55655,156 +52347,6 @@ USE `bi`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; --- --- Current Database: `bs` --- - -USE `bs`; - --- --- Final view structure for view `bajasLaborales` --- - -/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; -/*!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 = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `bajasLaborales` AS select `p`.`firstname` AS `firstname`,`p`.`name` AS `name`,`b`.`business_id` AS `business_id`,max(`ce`.`date`) AS `lastDate`,max(ifnull(`b`.`date_end`,curdate())) AS `endContract`,`cs`.`type` AS `type`,cast(count(0) as decimal(10,0)) AS `dias`,`w`.`userFk` AS `userFk` from (((((`postgresql`.`calendar_employee` `ce` join `postgresql`.`business` `b` on((`b`.`business_id` = `ce`.`business_id`))) join `postgresql`.`profile` `pr` on((`pr`.`profile_id` = `b`.`client_id`))) join `postgresql`.`person` `p` on((`p`.`person_id` = `pr`.`person_id`))) join `postgresql`.`calendar_state` `cs` on((`cs`.`calendar_state_id` = `ce`.`calendar_state_id`))) join `vn`.`worker` `w` on((`w`.`id` = `p`.`id_trabajador`))) where ((`ce`.`date` >= (curdate() + interval -(1) year)) and (`cs`.`type` not in ('Vacaciones','Vacaciones 1/2 día','Compensar','Festivo'))) group by `p`.`firstname`,`p`.`name`,`cs`.`type` having (`endContract` >= curdate()) */; -/*!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 `lastIndicators` --- - -/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; -/*!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 = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,(`i`.`lastYearSales` - `yi`.`lastYearSales`) AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,(`i`.`totalGreuge` - `yi`.`totalGreuge`) AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,(`i`.`latePaymentRate` - `yi`.`latePaymentRate`) AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,(`i`.`countEmployee` - `yi`.`countEmployee`) AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,(`i`.`averageMana` - `yi`.`averageMana`) AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,(`i`.`bankingPool` - `yi`.`bankingPool`) AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,(`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients`) AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,(`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients`) AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,(`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients`) AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,(`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate`) AS `incLastMonthWebBuyingRate`,`i`.`productionHours` AS `productionHours`,`i`.`dailyWorkersCost` AS `dailyWorkersCost`,`i`.`volumeM3` AS `volumeM3`,`i`.`salesValue` AS `salesValue`,`i`.`valueM3` AS `valueM3`,`i`.`hoursM3` AS `hoursM3`,`i`.`workerCostM3` AS `workerCostM3`,`i`.`salesWorkersCostRate` AS `salesWorkersCostRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on((`yi`.`updated` = (select (max(`indicators`.`updated`) + interval -(1) day) from `indicators`)))) where (`i`.`updated` = (select max(`indicators`.`updated`) from `indicators`)) */; -/*!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 `m3Silla` --- - -/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; -/*!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_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `m3Silla` AS select `m3`.`fecha` AS `fecha`,`m3`.`year` AS `year`,`m3`.`month` AS `month`,`m3`.`week` AS `week`,`m3`.`day` AS `day`,`m3`.`dayName` AS `dayName`,cast(sum(`m3`.`m3`) as decimal(10,0)) AS `Volumen`,cast(sum(`m3`.`euros`) as decimal(10,0)) AS `Euros` from `m3` where (`m3`.`warehouseFk` in (1,44)) group by `m3`.`fecha` */; -/*!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 `m3analisis` --- - -/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; -/*!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 = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `m3analisis` AS select `m`.`fecha` AS `fecha`,`m`.`year` AS `year`,`m`.`month` AS `month`,`m`.`week` AS `week`,`m`.`day` AS `day`,`m`.`dayName` AS `dayName`,`m`.`Volumen` AS `Volumen`,`m`.`Euros` AS `Euros`,`h`.`Departamento` AS `Departamento`,`h`.`Horas` AS `Horas`,`h`.`Salarios` AS `Salarios`,(`h`.`Horas` / `m`.`Volumen`) AS `tiempoM3`,(`m`.`Euros` / `m`.`Volumen`) AS `valorM3`,(`h`.`Salarios` / `m`.`Volumen`) AS `costeLaboralM3`,(`h`.`Salarios` / `m`.`Euros`) AS `costeEuros`,(`h`.`Salarios` / `h`.`Horas`) AS `precioHora` from (`bs`.`m3Silla` `m` join `bs`.`horasSilla` `h` on((`h`.`Fecha` = `m`.`fecha`))) */; -/*!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 `manaSpellersExcluded` --- - -/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; -/*!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 = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `manaSpellersExcluded` AS select `m`.`Id_Trabajador` AS `workerFk` from `mana_spellers_excluded` `m` */; -/*!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 `mana_spellers` --- - -/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; -/*!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_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mana_spellers` AS select `wm`.`workerFk` AS `Id_Trabajador`,`wm`.`size` AS `size`,`wm`.`amount` AS `used`,`wm`.`pricesModifierRate` AS `prices_modifier_rate`,`wm`.`isPricesModifierActivated` AS `prices_modifier_activated`,`wm`.`minRate` AS `minRate`,`wm`.`maxRate` AS `maxRate` from `vn`.`workerMana` `wm` */; -/*!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 `mermas` --- - -/*!50001 DROP VIEW IF EXISTS `mermas`*/; -/*!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_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `mermas` AS select `w`.`code` AS `Comprador`,`it`.`name` AS `Familia`,`i`.`id` AS `Referencia`,`i`.`name` AS `Item`,`s`.`quantity` AS `Cantidad`,(((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) AS `Coste_Unitario`,(`s`.`quantity` * (((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`)) AS `Importe`,`c`.`name` AS `Cliente`,`s`.`ticketFk` AS `ticketFk`,`t`.`shipped` AS `Fecha` from (((((((`vn`.`worker` `w` join `vn`.`itemType` `it` on((`it`.`workerFk` = `w`.`id`))) join `vn`.`item` `i` on((`i`.`typeFk` = `it`.`id`))) join `vn`.`sale` `s` on((`s`.`itemFk` = `i`.`id`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) left join `bi`.`Last_buy_id` `lb` on(((`lb`.`Id_Article` = `s`.`itemFk`) and (`lb`.`warehouse_id` = `t`.`warehouseFk`)))) left join `vn`.`buy` `b` on((`b`.`id` = `lb`.`Id_Compra`))) where ((`t`.`shipped` > '2018-01-01') and (`c`.`isRelevant` or (`c`.`id` in (200,400)))) */; -/*!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 `workerMana` --- - -/*!50001 DROP VIEW IF EXISTS `workerMana`*/; -/*!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 = utf8 */; -/*!50001 SET character_set_results = utf8 */; -/*!50001 SET collation_connection = utf8_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `workerMana` AS select `m`.`Id_Trabajador` AS `workerFk`,`m`.`used` AS `amount` from `bs`.`mana_spellers` `m` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - -- -- Current Database: `cache` -- @@ -56430,10 +52972,10 @@ USE `vn`; /*!50001 SET collation_connection = @saved_col_connection */; -- --- Final view structure for view `clientManaCache` +-- Final view structure for view `clientManaCache__` -- -/*!50001 DROP VIEW IF EXISTS `clientManaCache`*/; +/*!50001 DROP VIEW IF EXISTS `clientManaCache__`*/; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; @@ -56442,7 +52984,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `clientManaCache` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; +/*!50001 VIEW `clientManaCache__` AS select `mc`.`Id_Cliente` AS `clientFk`,`mc`.`Mana` AS `mana`,`mc`.`dated` AS `dated` from `bs`.`manaCustomer` `mc` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -57632,4 +54174,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-20 11:02:02 +-- Dump completed on 2019-12-23 14:34:48 diff --git a/db/export-structure.sh b/db/export-structure.sh index 1959463ff..5e1b62f03 100755 --- a/db/export-structure.sh +++ b/db/export-structure.sh @@ -3,7 +3,6 @@ SCHEMAS=( account bi - bs cache edi hedera diff --git a/modules/client/back/methods/client/updateFiscalData.js b/modules/client/back/methods/client/updateFiscalData.js index ea6a787b0..0f7810ed2 100644 --- a/modules/client/back/methods/client/updateFiscalData.js +++ b/modules/client/back/methods/client/updateFiscalData.js @@ -56,7 +56,6 @@ module.exports = Self => { ]; for (const key in params) { - console.log('key', key); if (validUpdateParams.indexOf(key) === -1) throw new UserError(`You don't have enough privileges to do that`); } diff --git a/modules/worker/back/models/worker-mana.json b/modules/worker/back/models/worker-mana.json index 8de7c1fe1..b98b2a325 100644 --- a/modules/worker/back/models/worker-mana.json +++ b/modules/worker/back/models/worker-mana.json @@ -3,7 +3,7 @@ "base": "VnModel", "options": { "mysql": { - "table": "bs.workerMana" + "table": "workerMana" } }, "properties": { From 5273e90a30a093dced38988d639d726fc7b2d61b Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 26 Dec 2019 07:12:34 +0100 Subject: [PATCH 48/59] Added params to ticket method & updated unit tests --- .../back/methods/claim/regularizeClaim.js | 35 +++--- modules/claim/front/dms/index/index.html | 2 +- modules/item/back/methods/item/regularize.js | 35 +++--- modules/ticket/back/methods/ticket/new.js | 107 +++++++++++------- .../back/methods/ticket/specs/new.spec.js | 70 ++++++++---- modules/ticket/front/create/card.html | 19 ++-- modules/ticket/front/create/card.js | 73 +++++++----- 7 files changed, 209 insertions(+), 132 deletions(-) diff --git a/modules/claim/back/methods/claim/regularizeClaim.js b/modules/claim/back/methods/claim/regularizeClaim.js index 136016b1e..e1e95728b 100644 --- a/modules/claim/back/methods/claim/regularizeClaim.js +++ b/modules/claim/back/methods/claim/regularizeClaim.js @@ -18,7 +18,6 @@ module.exports = Self => { }); Self.regularizeClaim = async(ctx, params) => { - const userId = ctx.req.accessToken.userId; const models = Self.app.models; const resolvedState = 3; @@ -55,11 +54,10 @@ module.exports = Self => { if (!ticketFk) { ticketFk = await createTicket(ctx, { - clientFk: address.clientFk, - addressFk: addressFk, - warehouseFk: sale.ticket().warehouseFk, - companyFk: sale.ticket().companyFk, - userId: userId + clientId: address.clientFk, + warehouseId: sale.ticket().warehouseFk, + companyId: sale.ticket().companyFk, + addressId: addressFk }, options); } @@ -140,16 +138,21 @@ module.exports = Self => { } async function createTicket(ctx, params, options) { - let ticket = await Self.app.models.Ticket.new(ctx, - { - shipped: new Date(), - landed: new Date(), - clientFk: params.clientFk, - warehouseFk: params.warehouseFk, - companyFk: params.companyFk, - addressFk: params.addressFk, - userId: params.userId - }, options); + params.shipped = new Date(); + params.landed = new Date(); + params.agencyModeId = null; + params.routeId = null; + + const ticket = await Self.app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyId, + params.addressId, + params.agencyModeId, + params.routeId, + options); return ticket.id; } diff --git a/modules/claim/front/dms/index/index.html b/modules/claim/front/dms/index/index.html index e3cd5da5b..bd6b9a21d 100644 --- a/modules/claim/front/dms/index/index.html +++ b/modules/claim/front/dms/index/index.html @@ -11,7 +11,7 @@
+ class="vn-w-xl">
{ }); Self.regularize = async(ctx, itemFk, quantity, warehouseFk) => { - const userId = ctx.req.accessToken.userId; const models = Self.app.models; const itemDestination = await models.ClaimDestination.findOne({ @@ -56,10 +55,9 @@ module.exports = Self => { if (!ticketFk) { ticketFk = await createTicket(ctx, { - clientFk: itemDestination.address().clientFk, - addressFk: itemDestination.addressFk, - warehouseFk: warehouseFk, - userId: userId + clientId: itemDestination.address().clientFk, + warehouseId: warehouseFk, + addressId: itemDestination.addressFk }, options); } @@ -88,17 +86,22 @@ module.exports = Self => { } async function createTicket(ctx, params, options) { - let ticket = await Self.app.models.Ticket.new( - ctx, - { - shipped: new Date(), - landed: new Date(), - clientFk: params.clientFk, - warehouseFk: params.warehouseFk, - companyFk: params.companyFk, - addressFk: params.addressFk, - userId: params.userId - }, options); + params.shipped = new Date(); + params.landed = new Date(); + params.companyId = null; + params.agencyModeId = null; + params.routeId = null; + + const ticket = await Self.app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyId, + params.addressId, + params.agencyModeId, + params.routeId, + options); return ticket.id; } diff --git a/modules/ticket/back/methods/ticket/new.js b/modules/ticket/back/methods/ticket/new.js index 7ddde8785..db5310f7c 100644 --- a/modules/ticket/back/methods/ticket/new.js +++ b/modules/ticket/back/methods/ticket/new.js @@ -2,14 +2,50 @@ let UserError = require('vn-loopback/util/user-error'); module.exports = Self => { Self.remoteMethodCtx('new', { - description: 'Create a newticket and returns the new ID', + description: 'Creates a new ticket and returns the id', accessType: 'WRITE', accepts: [{ - arg: 'params', - type: 'object', - required: true, - description: 'ClientFk, Shipped, WarehouseFk, CompanyFk, AddressFk, AgencyModeFk, RouteFk, Landed, userId', - http: {source: 'body'} + arg: 'clientId', + type: 'Number', + description: `The client id filter`, + required: true + }, + { + arg: 'shipped', + type: 'Date', + description: `The shipment date filter` + }, + { + arg: 'landed', + type: 'Date', + description: `The landing date filter` + }, + { + arg: 'warehouseId', + type: 'Number', + description: `The warehouse id filter`, + required: true + }, + { + arg: 'companyId', + type: 'Number', + description: `The company id filter` + }, + { + arg: 'addressId', + type: 'Number', + description: `The address id filter`, + required: true + }, + { + arg: 'agencyModeId', + type: 'Number', + description: `The agencyMode id filter` + }, + { + arg: 'routeId', + type: 'Number', + description: `The route id filter` }], returns: { type: 'number', @@ -21,10 +57,12 @@ module.exports = Self => { } }); - Self.new = async(ctx, params, options) => { - let models = Self.app.models; - let address = await models.Address.findOne({ - where: {id: params.addressFk}, + Self.new = async(ctx, clientId, shipped, landed, warehouseId, + companyId, addressId, agencyModeId, routeId, options) => { + const myUserId = ctx.req.accessToken.userId; + const models = Self.app.models; + const address = await models.Address.findOne({ + where: {id: addressId}, fields: ['id', 'clientFk'], include: { relation: 'client', @@ -36,18 +74,12 @@ module.exports = Self => { } }); - // FIXME: #1953 Params should be declared with it's correct argument type - if (params.shipped) - params.shipped = new Date(params.shipped); - if (params.landed) - params.landed = new Date(params.landed); - if (!address) throw new UserError(`This address doesn't exist`); let agencyMode; - if (params && params.agencyModeFk) - agencyMode = await models.AgencyMode.findById(params.agencyModeFk); + if (agencyModeId) + agencyMode = await models.AgencyMode.findById(agencyModeId); if (address.client().type().code === 'normal' && (!agencyMode || agencyMode.code != 'refund')) { if (!address.client().isActive) @@ -65,33 +97,30 @@ module.exports = Self => { } try { - if (!params.shipped && params.landed) { - const shippedResult = await models.Agency.getShipped(params.landed, - address.id, params.agencyModeFk, params.warehouseFk); - params.shipped = shippedResult && shippedResult.shipped; + if (!shipped && landed) { + const shippedResult = await models.Agency.getShipped(landed, + address.id, agencyModeId, warehouseId); + shipped = shippedResult && shippedResult.shipped; } - if (params.shipped && !params.landed) { - const landedResult = await models.Agency.getLanded(params.shipped, - address.id, params.agencyModeFk, params.warehouseFk); - params.landed = landedResult && landedResult.landed; + if (shipped && !landed) { + const landedResult = await models.Agency.getLanded(shipped, + address.id, agencyModeId, warehouseId); + landed = landedResult && landedResult.landed; } - if (!params.userId && ctx.req && ctx.req.accessToken.userId) - params.userId = ctx.req.accessToken.userId; - query = `CALL vn.ticketCreateWithUser(?, ?, ?, ?, ?, ?, ?, ?, ?, @result); SELECT @result newTicketId;`; let result = await Self.rawSql(query, [ - params.clientFk, - params.shipped, - params.warehouseFk, - params.companyFk || 442, - params.addressFk, - params.agencyModeFk || null, - params.routeFk || null, - params.landed, - params.userId + clientId, + shipped, + warehouseId, + companyId || 442, + addressId, + agencyModeId || null, + routeId || null, + landed, + myUserId ], options); let ticket = await models.Ticket.findById(result[1][0].newTicketId, null, options); @@ -99,7 +128,7 @@ module.exports = Self => { let logRecord = { originFk: cleanInstance.id, - userFk: params.userId, + userFk: myUserId, action: 'create', changedModel: 'Ticket', changedModelId: cleanInstance.id, diff --git a/modules/ticket/back/methods/ticket/specs/new.spec.js b/modules/ticket/back/methods/ticket/specs/new.spec.js index 80147c2f2..87bc89b12 100644 --- a/modules/ticket/back/methods/ticket/specs/new.spec.js +++ b/modules/ticket/back/methods/ticket/specs/new.spec.js @@ -15,42 +15,74 @@ describe('ticket new()', () => { it('should throw an error if the client isnt frozen and isnt active', async() => { let error; - let params = {addressFk: 6}; + let params = { + clientId: 106, + shipped: today, + landed: null, + warehouseId: 1, + companyId: 442, + addressId: 6 + }; - await app.models.Ticket.new(ctx, params) - .catch(e => { - error = e; - }); + await app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyFk, + params.addressId + ).catch(e => { + error = e; + }); expect(error).toEqual(new UserError(`You can't create a ticket for a inactive client`)); }); it('should throw an error if the address doesnt exist', async() => { let error; - let params = {addressFk: 'invalid address', clientFk: 104}; + let params = { + clientId: 104, + shipped: today, + landed: null, + warehouseId: 1, + companyId: 442, + addressId: 'invalid address' + }; - await app.models.Ticket.new(ctx, params) - .catch(response => { - expect(response.message).toEqual(`This address doesn't exist`); - error = response; - }); + await app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyFk, + params.addressId + ).catch(response => { + expect(response.message).toEqual(`This address doesn't exist`); + error = response; + }); expect(error).toBeDefined(); }); it('should return the id of the created ticket', async() => { let params = { - warehouseFk: 1, - clientFk: 104, - companyFk: 442, - addressFk: 4, - agencyModeFk: 1, - userId: 9, + clientId: 104, shipped: today, - landed: today + landed: today, + warehouseId: 1, + companyId: 442, + addressId: 4, + agencyModeId: 1 }; - ticket = await app.models.Ticket.new(ctx, params); + ticket = await app.models.Ticket.new(ctx, + params.clientId, + params.shipped, + params.landed, + params.warehouseId, + params.companyFk, + params.addressId, + params.agencyModeId); let newestTicketIdInFixtures = 21; diff --git a/modules/ticket/front/create/card.html b/modules/ticket/front/create/card.html index cd26f21e7..6e6b5de62 100644 --- a/modules/ticket/front/create/card.html +++ b/modules/ticket/front/create/card.html @@ -1,20 +1,19 @@ - {{id}}: {{name}} @@ -25,18 +24,18 @@ ng-model="$ctrl.landed"> + ng-model="$ctrl.agencyModeId"> \ No newline at end of file diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js index 629647416..48790ed10 100644 --- a/modules/ticket/front/create/card.js +++ b/modules/ticket/front/create/card.js @@ -19,16 +19,20 @@ class Controller { this.warehouseFk = this.vnConfig.warehouseFk; } + get ticket() { + return this._ticket; + } + set ticket(value) { if (value) this._ticket = value; } - get ticket() { - return this._ticket; + get clientId() { + return this.ticket.clientFk; } - set clientFk(value) { + set clientId(value) { this.ticket.clientFk = value; if (value) { @@ -36,7 +40,7 @@ class Controller { include: { relation: 'defaultAddress', scope: { - fields: 'id' + fields: ['id', 'agencyModeFk'] } }, where: {id: value} @@ -44,32 +48,21 @@ class Controller { filter = encodeURIComponent(JSON.stringify(filter)); let query = `Clients?filter=${filter}`; this.$http.get(query).then(res => { - if (res.data) { - let client = res.data[0]; - let defaultAddress = client.defaultAddress; - this.addressFk = defaultAddress.id; - } + const [client] = res.data; + this.defaultAddress = client.defaultAddress; + this.addressId = this.defaultAddress.id; }); } else - this.addressFk = null; + this.addressId = null; this.getAvailableAgencies(); } - get clientFk() { - return this.ticket.clientFk; - } - - set addressFk(value) { - this.ticket.addressFk = value; - this.getAvailableAgencies(); - } - - get addressFk() { + get addressId() { return this.ticket.addressFk; } - set landed(value) { - this.ticket.landed = value; + set addressId(value) { + this.ticket.addressFk = value; this.getAvailableAgencies(); } @@ -77,12 +70,26 @@ class Controller { return this.ticket.landed; } - set warehouseFk(value) { + set landed(value) { + this.ticket.landed = value; + this.getAvailableAgencies(); + } + + get warehouseId() { + return this.ticket.warehouseFk; + } + + set warehouseId(value) { this.ticket.warehouseFk = value; this.getAvailableAgencies(); } - get warehouseFk() { - return this.ticket.warehouseFk; + + get agencyModeId() { + return this.ticket.agencyModeFk; + } + + set agencyModeId(value) { + this.ticket.agencyModeFk = value; } getAvailableAgencies() { @@ -96,8 +103,12 @@ class Controller { if (params.warehouseFk && params.addressFk && params.landed) { ticket.agencyModeFk = null; - this.$http.get(`Agencies/getAgenciesWithWarehouse`, {params}) - .then(res => this._availableAgencies = res.data); + this.$http.get(`Agencies/getAgenciesWithWarehouse`, {params}).then(res => { + this._availableAgencies = res.data; + + this.agencyModeId = this.defaultAddress.agencyModeFk; + console.log(this.agencyModeId); + }); } } @@ -107,11 +118,11 @@ class Controller { createTicket() { let params = { - clientFk: this.ticket.clientFk, + clientId: this.ticket.clientFk, landed: this.ticket.landed, - addressFk: this.ticket.addressFk, - agencyModeFk: this.ticket.agencyModeFk, - warehouseFk: this.ticket.warehouseFk, + addressId: this.ticket.addressFk, + agencyModeId: this.ticket.agencyModeFk, + warehouseId: this.ticket.warehouseFk, }; this.$http.post(`Tickets/new`, params).then(res => { this.vnApp.showSuccess(this.translate.instant('Data saved!')); From 0a37f3a1b2356de9b32fd25a4d35197a9e40355f Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Thu, 26 Dec 2019 08:20:16 +0100 Subject: [PATCH 49/59] update index filter --- modules/client/front/index/index.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/client/front/index/index.js b/modules/client/front/index/index.js index 56ab594ff..51dd41dea 100644 --- a/modules/client/front/index/index.js +++ b/modules/client/front/index/index.js @@ -24,10 +24,11 @@ export default class Controller { case 'socialName': case 'city': return {[param]: {like: `%${value}%`}}; + case 'email': + return {[param]: {like: `%${value}%`}}; case 'id': case 'fi': case 'postcode': - case 'email': case 'salesPersonFk': return {[param]: value}; } From c95c7192dac2db6b2721d653246f7934717ba81a Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 26 Dec 2019 08:21:08 +0100 Subject: [PATCH 50/59] Added template to specie autocomplete --- modules/item/front/botanical/index.html | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/modules/item/front/botanical/index.html b/modules/item/front/botanical/index.html index 8353841b3..55a25e268 100644 --- a/modules/item/front/botanical/index.html +++ b/modules/item/front/botanical/index.html @@ -29,14 +29,21 @@ value-field="genus_id" label="Genus"> - + label="Species" + fields="['genus_id']" + include="'genus'"> + +
{{latin_species_name}}
+
+ {{genus.latin_genus_name}} +
+
From d2c5ab7297ec6d51b031e2c39fbbd4d10e675afb Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 26 Dec 2019 08:43:34 +0100 Subject: [PATCH 51/59] trigger unit tests --- modules/item/front/botanical/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/item/front/botanical/index.html b/modules/item/front/botanical/index.html index 55a25e268..b6d836b30 100644 --- a/modules/item/front/botanical/index.html +++ b/modules/item/front/botanical/index.html @@ -30,12 +30,12 @@ label="Genus"> From fd8eeb626dcc5559ccbe823daba665efe8fdf200 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 26 Dec 2019 08:45:55 +0100 Subject: [PATCH 52/59] removed console.log --- modules/ticket/front/create/card.js | 1 - 1 file changed, 1 deletion(-) diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js index 48790ed10..20def7b72 100644 --- a/modules/ticket/front/create/card.js +++ b/modules/ticket/front/create/card.js @@ -107,7 +107,6 @@ class Controller { this._availableAgencies = res.data; this.agencyModeId = this.defaultAddress.agencyModeFk; - console.log(this.agencyModeId); }); } } From f2e9dbd597d43686fee9775e2a7fbe049f43b9ee Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 26 Dec 2019 11:27:44 +0100 Subject: [PATCH 53/59] added category name to item type autocompletes --- modules/item/front/basic-data/index.html | 10 +++++++++- modules/item/front/create/index.html | 16 +++++++++++----- modules/item/front/search-panel/index.html | 13 ++++++++++--- .../back/methods/order/getItemTypeAvailable.js | 3 ++- modules/order/front/filter/index.html | 10 +++++++++- 5 files changed, 41 insertions(+), 11 deletions(-) diff --git a/modules/item/front/basic-data/index.html b/modules/item/front/basic-data/index.html index 4fe9bfe21..bd0cec86d 100644 --- a/modules/item/front/basic-data/index.html +++ b/modules/item/front/basic-data/index.html @@ -31,7 +31,15 @@ show-field="name" value-field="id" ng-model="$ctrl.item.typeFk" - initial-data="$ctrl.item.itemType"> + initial-data="$ctrl.item.itemType" + fields="['categoryFk']" + include="'category'"> + +
{{name}}
+
+ {{category.name}} +
+
diff --git a/modules/item/front/create/index.html b/modules/item/front/create/index.html index 0c00aa8e9..e57da198c 100644 --- a/modules/item/front/create/index.html +++ b/modules/item/front/create/index.html @@ -19,13 +19,19 @@ - -
{{::code}}
-
{{::name}}
+ search-function="{or: [{code: {like: $search +'%'}}, {name: {like: '%'+ $search +'%'}}]}" + include="'category'"> + +
+
{{::code}}
+
{{::name}}
+
+
+ {{category.name}} +
- + ng-model="filter.typeFk" + fields="['categoryFk']" + include="'category'"> + +
{{name}}
+
+ {{category.name}} +
+
>
diff --git a/modules/order/back/methods/order/getItemTypeAvailable.js b/modules/order/back/methods/order/getItemTypeAvailable.js index 977a2cf85..de0a5511c 100644 --- a/modules/order/back/methods/order/getItemTypeAvailable.js +++ b/modules/order/back/methods/order/getItemTypeAvailable.js @@ -38,11 +38,12 @@ module.exports = Self => { order.agencyModeFk ]); stmts.push(stmt); - stmt = new ParameterizedSQL(`SELECT it.id, it.name + stmt = new ParameterizedSQL(`SELECT it.id, it.name, ic.name categoryName FROM tmp.availableCalc ac JOIN cache.available a ON a.calc_id = ac.calcFk JOIN item i ON i.id = a.item_id JOIN itemType it ON it.id = i.typeFk + JOIN itemCategory ic ON ic.id = it.categoryFk WHERE it.categoryFk = ? GROUP BY it.id`, [ itemCategoryId diff --git a/modules/order/front/filter/index.html b/modules/order/front/filter/index.html index 68691e0a7..2b92b5f4a 100644 --- a/modules/order/front/filter/index.html +++ b/modules/order/front/filter/index.html @@ -29,7 +29,15 @@ ng-model="$ctrl.type.id" show-field="name" value-field="id" - label="Type"> + label="Type" + fields="['categoryFk']" + include="'category'"> + +
{{name}}
+
+ {{categoryName}} +
+
From b74de37c82a243f279ed4a0ad6d4f08b85e71736 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Thu, 26 Dec 2019 13:29:50 +0100 Subject: [PATCH 54/59] updated selectors --- e2e/helpers/selectors.js | 8 ++++---- modules/ticket/front/create/card.js | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index f9d69123f..347590a74 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -345,11 +345,11 @@ export default { acceptDeleteTurn: '.vn-confirm.shown button[response="accept"]' }, createTicketView: { - clientAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.clientFk"]', - addressAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.addressFk"]', + clientAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.clientId"]', + addressAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.addressId"]', deliveryDateInput: 'vn-ticket-create vn-date-picker[ng-model="$ctrl.landed"]', - warehouseAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.warehouseFk"]', - agencyAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.ticket.agencyModeFk"]', + warehouseAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.warehouseId"]', + agencyAutocomplete: 'vn-ticket-create vn-autocomplete[ng-model="$ctrl.agencyModeId"]', createButton: `button[type=submit]` }, ticketDescriptor: { diff --git a/modules/ticket/front/create/card.js b/modules/ticket/front/create/card.js index 20def7b72..2e775c18b 100644 --- a/modules/ticket/front/create/card.js +++ b/modules/ticket/front/create/card.js @@ -14,9 +14,9 @@ class Controller { $onInit() { if (this.$stateParams && this.$stateParams.clientFk) - this.clientFk = this.$stateParams.clientFk; + this.clientId = this.$stateParams.clientFk; - this.warehouseFk = this.vnConfig.warehouseFk; + this.warehouseId = this.vnConfig.warehouseFk; } get ticket() { From e9d3b14da74caa22a64f949cb1f0a75bc4f34a60 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Fri, 27 Dec 2019 08:01:53 +0100 Subject: [PATCH 55/59] refactor models component and componentType --- .../back/methods/sale/specs/updatePrice.spec.js | 4 ++-- modules/ticket/back/methods/sale/updatePrice.js | 2 +- .../methods/ticket/specs/componentUpdate.spec.js | 2 +- .../back/methods/ticket/specs/updateDiscount.spec.js | 2 +- modules/ticket/back/methods/ticket/updateDiscount.js | 2 +- modules/ticket/back/model-config.json | 4 ++-- ...{component-type-rate.json => component-type.json} | 2 +- .../models/{component-rate.json => component.json} | 4 ++-- modules/ticket/back/models/sale-component.json | 4 ++-- modules/ticket/front/component/index.html | 10 +++++----- modules/ticket/front/component/index.js | 8 ++++---- modules/ticket/front/component/index.spec.js | 12 ++++++------ 12 files changed, 28 insertions(+), 28 deletions(-) rename modules/ticket/back/models/{component-type-rate.json => component-type.json} (92%) rename modules/ticket/back/models/{component-rate.json => component.json} (92%) diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 37930f1b3..2a751697f 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -8,8 +8,8 @@ describe('sale updatePrice()', () => { let manaComponentId; beforeAll(async done => { - let componentRate = await app.models.ComponentRate.findOne({where: {code: 'mana'}}); - manaComponentId = componentRate.id; + let component = await app.models.Component.findOne({where: {code: 'mana'}}); + manaComponentId = component.id; originalSale = await app.models.Sale.findById(saleId); originalSalesPersonMana = await app.models.WorkerMana.findById(18); diff --git a/modules/ticket/back/methods/sale/updatePrice.js b/modules/ticket/back/methods/sale/updatePrice.js index 60a171e17..75e226c42 100644 --- a/modules/ticket/back/methods/sale/updatePrice.js +++ b/modules/ticket/back/methods/sale/updatePrice.js @@ -59,7 +59,7 @@ module.exports = Self => { let usesMana = await models.WorkerMana.findOne({where: {workerFk: salesPerson}, fields: 'amount'}, options); let componentCode = usesMana ? 'mana' : 'buyerDiscount'; - let discount = await models.ComponentRate.findOne({where: {code: componentCode}}, options); + let discount = await models.Component.findOne({where: {code: componentCode}}, options); let componentId = discount.id; let componentValue = newPrice - sale.price; diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index 25ce90946..04570390d 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -13,7 +13,7 @@ describe('ticket componentUpdate()', () => { let componentOfSaleEight; beforeAll(async done => { - let deliveryComponenet = await app.models.ComponentRate.findOne({where: {code: 'delivery'}}); + let deliveryComponenet = await app.models.Component.findOne({where: {code: 'delivery'}}); deliveryComponentId = deliveryComponenet.id; componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 75de1f538..111897efe 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -8,7 +8,7 @@ describe('sale updateDiscount()', () => { beforeAll(async done => { originalSale = await app.models.Sale.findById(originalSaleId); - let manaDiscount = await app.models.ComponentRate.findOne({where: {code: 'mana'}}); + let manaDiscount = await app.models.Component.findOne({where: {code: 'mana'}}); componentId = manaDiscount.id; let ticket = await app.models.Ticket.findById(originalSale.ticketFk); diff --git a/modules/ticket/back/methods/ticket/updateDiscount.js b/modules/ticket/back/methods/ticket/updateDiscount.js index 94ada046f..66b4d6f95 100644 --- a/modules/ticket/back/methods/ticket/updateDiscount.js +++ b/modules/ticket/back/methods/ticket/updateDiscount.js @@ -88,7 +88,7 @@ module.exports = Self => { fields: 'amount'}, options); const componentCode = usesMana ? 'mana' : 'buyerDiscount'; - const discountComponent = await models.ComponentRate.findOne({ + const discountComponent = await models.Component.findOne({ where: {code: componentCode}}, options); const componentId = discountComponent.id; diff --git a/modules/ticket/back/model-config.json b/modules/ticket/back/model-config.json index 3b38f1a16..10c10b134 100644 --- a/modules/ticket/back/model-config.json +++ b/modules/ticket/back/model-config.json @@ -5,10 +5,10 @@ "AnnualAverageInvoiced": { "dataSource": "vn" }, - "ComponentRate": { + "Component": { "dataSource": "vn" }, - "ComponentTypeRate": { + "ComponentType": { "dataSource": "vn" }, "Expedition": { diff --git a/modules/ticket/back/models/component-type-rate.json b/modules/ticket/back/models/component-type.json similarity index 92% rename from modules/ticket/back/models/component-type-rate.json rename to modules/ticket/back/models/component-type.json index c9b80f45c..ced725309 100644 --- a/modules/ticket/back/models/component-type-rate.json +++ b/modules/ticket/back/models/component-type.json @@ -1,5 +1,5 @@ { - "name": "ComponentTypeRate", + "name": "ComponentType", "base": "VnModel", "options": { "mysql": { diff --git a/modules/ticket/back/models/component-rate.json b/modules/ticket/back/models/component.json similarity index 92% rename from modules/ticket/back/models/component-rate.json rename to modules/ticket/back/models/component.json index 535b6086f..002b4804f 100644 --- a/modules/ticket/back/models/component-rate.json +++ b/modules/ticket/back/models/component.json @@ -1,5 +1,5 @@ { - "name": "ComponentRate", + "name": "Component", "base": "VnModel", "options": { "mysql": { @@ -34,7 +34,7 @@ "relations": { "componentType": { "type": "belongsTo", - "model": "ComponentTypeRate", + "model": "ComponentType", "foreignKey": "typeFk" } }, diff --git a/modules/ticket/back/models/sale-component.json b/modules/ticket/back/models/sale-component.json index 49edab2ae..3b7991fbb 100644 --- a/modules/ticket/back/models/sale-component.json +++ b/modules/ticket/back/models/sale-component.json @@ -25,9 +25,9 @@ "model": "Sale", "foreignKey": "saleFk" }, - "componentRate": { + "component": { "type": "belongsTo", - "model": "ComponentRate", + "model": "Component", "foreignKey": "componentFk" } } diff --git a/modules/ticket/front/component/index.html b/modules/ticket/front/component/index.html index 2a70baa9d..16db43a2e 100644 --- a/modules/ticket/front/component/index.html +++ b/modules/ticket/front/component/index.html @@ -45,19 +45,19 @@ - {{::component.componentRate.componentType.type}} + {{::saleComponent.component.componentType.type}} - {{::component.componentRate.name}} + {{::saleComponent.component.name}} - {{::component.value | currency: 'EUR':3}} + {{::saleComponent.value | currency: 'EUR':3}} - {{::sale.quantity * component.value | currency: 'EUR':3}} + {{::sale.quantity * saleComponent.value | currency: 'EUR':3}} diff --git a/modules/ticket/front/component/index.js b/modules/ticket/front/component/index.js index 9854305f6..027fdad77 100644 --- a/modules/ticket/front/component/index.js +++ b/modules/ticket/front/component/index.js @@ -15,7 +15,7 @@ class Controller { scope: { fields: ['componentFk', 'value'], include: { - relation: 'componentRate', + relation: 'component', scope: { fields: ['typeFk', 'name'], include: { @@ -38,9 +38,9 @@ class Controller { if (!sales) return; for (let sale of sales) { - for (let component of sale.components) { - if (component.componentRate.componentType.isBase) - sum += sale.quantity * component.value; + for (let saleComponent of sale.components) { + if (saleComponent.component.componentType.isBase) + sum += sale.quantity * saleComponent.value; } } diff --git a/modules/ticket/front/component/index.spec.js b/modules/ticket/front/component/index.spec.js index e75bf2bdb..4dd361b27 100644 --- a/modules/ticket/front/component/index.spec.js +++ b/modules/ticket/front/component/index.spec.js @@ -14,7 +14,7 @@ describe('ticket', () => { $scope.model.data = [{ components: [ { - componentRate: { + component: { name: 'valor de compra', componentType: { isBase: 1 @@ -23,7 +23,7 @@ describe('ticket', () => { value: 5 }, { - componentRate: { + component: { name: 'reparto', componentType: { isBase: 0 @@ -32,7 +32,7 @@ describe('ticket', () => { value: 5 }, { - componentRate: { + component: { name: 'recobro', componentType: { isBase: 0 @@ -46,7 +46,7 @@ describe('ticket', () => { { components: [ { - componentRate: { + component: { name: 'valor de compra', componentType: { isBase: 1 @@ -55,7 +55,7 @@ describe('ticket', () => { value: 1 }, { - componentRate: { + component: { name: 'reparto', componentType: { isBase: 0 @@ -64,7 +64,7 @@ describe('ticket', () => { value: 1 }, { - componentRate: { + component: { name: 'recobro', componentType: { isBase: 0 From 0ece53a35ea1bcdaf056e88c3659925484e3bc3e Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 27 Dec 2019 08:49:51 +0100 Subject: [PATCH 56/59] Send chat message with user avatar --- back/methods/chat/sendMessage.js | 98 +++++++++++++------ back/models/chat-config.json | 5 +- db/changes/10130-christmas/00-chatConfig.sql | 5 + db/dump/fixtures.sql | 4 +- .../ticket/back/methods/ticket/setDeleted.js | 2 +- 5 files changed, 82 insertions(+), 32 deletions(-) create mode 100644 db/changes/10130-christmas/00-chatConfig.sql diff --git a/back/methods/chat/sendMessage.js b/back/methods/chat/sendMessage.js index 2ab07af8c..a861ba07e 100644 --- a/back/methods/chat/sendMessage.js +++ b/back/methods/chat/sendMessage.js @@ -31,26 +31,23 @@ module.exports = Self => { const recipient = to.replace('@', ''); if (sender.name != recipient) - return sendMessage(to, `@${sender.name}: ${message}`); + return sendMessage(sender, to, `@${sender.name}: ${message} `); }; - async function sendMessage(name, message) { - const models = Self.app.models; - const chatConfig = await models.ChatConfig.findOne(); + async function sendMessage(sender, channel, message) { + const config = await getConfig(); - if (!Self.token) - Self.token = await login(); - - const uri = `${chatConfig.uri}/chat.postMessage`; - return send(uri, { - 'channel': name, + const avatar = `${config.host}/avatar/${sender.name}`; + const uri = `${config.api}/chat.postMessage`; + return sendAuth(uri, { + 'channel': channel, + 'avatar': avatar, 'text': message }).catch(async error => { - if (error.statusCode === 401 && !Self.loginAttempted) { - Self.token = await login(); - Self.loginAttempted = true; + if (error.statusCode === 401 && !this.resendAttempted) { + this.resendAttempted = true; - return sendMessage(name, message); + return sendMessage(sender, channel, message); } throw new Error(error.message); @@ -61,24 +58,51 @@ module.exports = Self => { * Returns a rocketchat token * @return {Object} userId and authToken */ - async function login() { - const models = Self.app.models; - const chatConfig = await models.ChatConfig.findOne(); - const uri = `${chatConfig.uri}/login`; - return send(uri, { - user: chatConfig.user, - password: chatConfig.password - }).then(res => res.data); + async function getAuthToken() { + if (!this.auth || this.auth && !this.auth.authToken) { + const config = await getConfig(); + const uri = `${config.api}/login`; + const res = await send(uri, { + user: config.user, + password: config.password + }); + + this.auth = res.data; + } + + return this.auth; } - function send(uri, body) { + /** + * Returns a rocketchat config + * @return {Object} Auth config + */ + async function getConfig() { + if (!this.chatConfig) { + const models = Self.app.models; + + this.chatConfig = await models.ChatConfig.findOne(); + } + + return this.chatConfig; + } + + /** + * Send unauthenticated request + * @param {*} uri - Request uri + * @param {*} body - Request params + * @param {*} options - Request options + * + * @return {Object} Request response + */ + async function send(uri, body, options) { if (process.env.NODE_ENV !== 'production') { return new Promise(resolve => { return resolve({statusCode: 200, message: 'Fake notification sent'}); }); } - const options = { + const defaultOptions = { method: 'POST', uri: uri, body: body, @@ -86,11 +110,29 @@ module.exports = Self => { json: true }; - if (Self.token) { - options.headers['X-Auth-Token'] = Self.token.authToken; - options.headers['X-User-Id'] = Self.token.userId; + if (options) Object.assign(defaultOptions, options); + + return request(defaultOptions); + } + + /** + * Send authenticated request + * @param {*} uri - Request uri + * @param {*} body - Request params + * + * @return {Object} Request response + */ + async function sendAuth(uri, body) { + const login = await getAuthToken(); + const options = { + headers: {'content-type': 'application/json'} + }; + + if (login) { + options.headers['X-Auth-Token'] = login.authToken; + options.headers['X-User-Id'] = login.userId; } - return request(options); + return send(uri, body, options); } }; diff --git a/back/models/chat-config.json b/back/models/chat-config.json index 12cd021cb..d4f708b7a 100644 --- a/back/models/chat-config.json +++ b/back/models/chat-config.json @@ -13,7 +13,10 @@ "type": "Number", "description": "Identifier" }, - "uri": { + "host": { + "type": "String" + }, + "api": { "type": "String" }, "user": { diff --git a/db/changes/10130-christmas/00-chatConfig.sql b/db/changes/10130-christmas/00-chatConfig.sql new file mode 100644 index 000000000..beff3bde4 --- /dev/null +++ b/db/changes/10130-christmas/00-chatConfig.sql @@ -0,0 +1,5 @@ +ALTER TABLE `vn`.`chatConfig` +ADD COLUMN `host` VARCHAR(255) NOT NULL AFTER `id`, +CHANGE COLUMN `uri` `api` VARCHAR(255) CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci' NOT NULL ; + +UPDATE `vn`.`chatConfig` SET `host` = 'https://chat.verdnatura.es' WHERE (`id` = '1'); diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 85d510f28..a10b2003c 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -20,9 +20,9 @@ INSERT INTO `vn`.`bionicConfig` (`generalInflationCoeficient`, `minimumDensityVo VALUES (1.30, 167.00, 138000, 71); -INSERT INTO `vn`.`chatConfig` (`uri`) +INSERT INTO `vn`.`chatConfig` (`host`, `api`) VALUES - ('https://chat.verdnatura.es/api/v1'); + ('https://chat.verdnatura.es', 'https://chat.verdnatura.es/api/v1'); INSERT IGNORE INTO `vn`.`greugeConfig`(`id`, `freightPickUpPrice`) VALUES diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index fb72c7dbc..6080992aa 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -94,7 +94,7 @@ module.exports = Self => { id: id, url: `${origin}/#!/ticket/${id}/summary` }); - await models.Chat.sendMessage(ctx, `@${salesPersonUser}`, message); + await models.Chat.sendMessage(ctx, `@joan`, message); } return ticket.updateAttribute('isDeleted', true); From d880ca24277b1707934fb4c2f06369c0fc795bd8 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 27 Dec 2019 09:02:37 +0100 Subject: [PATCH 57/59] changed param --- modules/ticket/back/methods/ticket/setDeleted.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/ticket/back/methods/ticket/setDeleted.js b/modules/ticket/back/methods/ticket/setDeleted.js index 6080992aa..fb72c7dbc 100644 --- a/modules/ticket/back/methods/ticket/setDeleted.js +++ b/modules/ticket/back/methods/ticket/setDeleted.js @@ -94,7 +94,7 @@ module.exports = Self => { id: id, url: `${origin}/#!/ticket/${id}/summary` }); - await models.Chat.sendMessage(ctx, `@joan`, message); + await models.Chat.sendMessage(ctx, `@${salesPersonUser}`, message); } return ticket.updateAttribute('isDeleted', true); From b4e7a1e3e019911b68df50de779a07437d6ca296 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Fri, 27 Dec 2019 10:29:20 +0100 Subject: [PATCH 58/59] Changed sepa-core title --- print/templates/reports/sepa-core/locale/fr.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/print/templates/reports/sepa-core/locale/fr.yml b/print/templates/reports/sepa-core/locale/fr.yml index 9489fa277..b5cddc38b 100644 --- a/print/templates/reports/sepa-core/locale/fr.yml +++ b/print/templates/reports/sepa-core/locale/fr.yml @@ -1,4 +1,4 @@ -title: Mandat de domiciliation Européene +title: Direct Debit description: En signant ce formulaire de mandat, vous autorisez VERDNATURA LEVANTE SL à envoyer des instructions à votre banque pour débiter votre compte, et (B) votre banque à débiter votre compte conformément aux instructions de VERDNATURA LEVANTE SL. From 417642ac9e7cb16c2291bd961990b54ba58bd848 Mon Sep 17 00:00:00 2001 From: Joan Sanchez Date: Tue, 31 Dec 2019 11:07:46 +0100 Subject: [PATCH 59/59] updated UserPhone acl --- db/dump/dumpedFixtures.sql | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index 687f05518..e9b5af23b 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -119,7 +119,7 @@ USE `salix`; LOCK TABLES `ACL` WRITE; /*!40000 ALTER TABLE `ACL` DISABLE KEYS */; -INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','WRITE','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','employee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','employee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','employee'),(18,'State','*','READ','ALLOW','ROLE','employee'),(20,'TicketState','*','*','ALLOW','ROLE','employee'),(24,'Delivery','*','READ','ALLOW','ROLE','employee'),(25,'Zone','*','READ','ALLOW','ROLE','employee'),(26,'ClientCredit','*','*','ALLOW','ROLE','employee'),(27,'ClientCreditLimit','*','READ','ALLOW','ROLE','employee'),(30,'GreugeType','*','READ','ALLOW','ROLE','employee'),(31,'Mandate','*','READ','ALLOW','ROLE','employee'),(32,'MandateType','*','READ','ALLOW','ROLE','employee'),(33,'Company','*','READ','ALLOW','ROLE','employee'),(34,'Greuge','*','READ','ALLOW','ROLE','employee'),(35,'AddressObservation','*','*','ALLOW','ROLE','employee'),(36,'ObservationType','*','*','ALLOW','ROLE','employee'),(37,'Greuge','*','WRITE','ALLOW','ROLE','employee'),(38,'AgencyMode','*','READ','ALLOW','ROLE','employee'),(39,'ItemTag','*','WRITE','ALLOW','ROLE','buyer'),(40,'ItemBotanical','*','WRITE','ALLOW','ROLE','buyer'),(41,'ItemBotanical','*','READ','ALLOW','ROLE','employee'),(42,'ItemPlacement','*','WRITE','ALLOW','ROLE','buyer'),(43,'ItemPlacement','*','WRITE','ALLOW','ROLE','replenisher'),(44,'ItemPlacement','*','READ','ALLOW','ROLE','employee'),(45,'ItemBarcode','*','READ','ALLOW','ROLE','employee'),(46,'ItemBarcode','*','WRITE','ALLOW','ROLE','buyer'),(47,'ItemBarcode','*','WRITE','ALLOW','ROLE','replenisher'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','employee'),(56,'Recovery','*','WRITE','ALLOW','ROLE','administrative'),(58,'CreditClassification','*','*','ALLOW','ROLE','insurance'),(60,'CreditInsurance','*','*','ALLOW','ROLE','insurance'),(61,'InvoiceOut','*','READ','ALLOW','ROLE','employee'),(62,'Ticket','*','*','ALLOW','ROLE','employee'),(63,'TicketObservation','*','*','ALLOW','ROLE','employee'),(64,'Route','*','READ','ALLOW','ROLE','employee'),(65,'Sale','*','READ','ALLOW','ROLE','employee'),(66,'TicketTracking','*','READ','ALLOW','ROLE','employee'),(68,'TicketPackaging','*','*','ALLOW','ROLE','employee'),(69,'Packaging','*','READ','ALLOW','ROLE','employee'),(70,'Packaging','*','WRITE','ALLOW','ROLE','logistic'),(71,'SaleChecked','*','READ','ALLOW','ROLE','employee'),(72,'SaleComponent','*','READ','ALLOW','ROLE','employee'),(73,'Expedition','*','READ','ALLOW','ROLE','employee'),(74,'Expedition','*','WRITE','ALLOW','ROLE','deliveryBoss'),(75,'Expedition','*','WRITE','ALLOW','ROLE','production'),(76,'AnnualAverageInvoiced','*','READ','ALLOW','ROLE','employee'),(77,'WorkerMana','*','READ','ALLOW','ROLE','employee'),(78,'TicketTracking','*','WRITE','ALLOW','ROLE','production'),(79,'TicketTracking','changeState','*','ALLOW','ROLE','employee'),(80,'Sale','removes','*','ALLOW','ROLE','employee'),(81,'Sale','moveToTicket','*','ALLOW','ROLE','employee'),(82,'Sale','updateQuantity','*','ALLOW','ROLE','employee'),(83,'Sale','updatePrice','*','ALLOW','ROLE','employee'),(84,'Sale','updateDiscount','*','ALLOW','ROLE','employee'),(85,'SaleTracking','*','READ','ALLOW','ROLE','employee'),(86,'Order','*','*','ALLOW','ROLE','employee'),(87,'OrderRow','*','*','ALLOW','ROLE','employee'),(88,'ClientContact','*','*','ALLOW','ROLE','employee'),(89,'Sale','moveToNewTicket','*','ALLOW','ROLE','employee'),(90,'Sale','reserve','*','ALLOW','ROLE','employee'),(91,'TicketWeekly','*','*','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','employee'),(111,'ClientLog','*','READ','ALLOW','ROLE','employee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','employee'),(114,'Receipt','*','READ','ALLOW','ROLE','employee'),(115,'Receipt','*','WRITE','ALLOW','ROLE','administrative'),(116,'BankEntity','*','*','ALLOW','ROLE','employee'),(117,'ClientSample','*','*','ALLOW','ROLE','employee'),(118,'WorkerTeam','*','*','ALLOW','ROLE','salesPerson'),(119,'Travel','*','READ','ALLOW','ROLE','employee'),(120,'Travel','*','WRITE','ALLOW','ROLE','buyer'),(121,'Item','regularize','*','ALLOW','ROLE','employee'),(122,'TicketRequest','*','*','ALLOW','ROLE','employee'),(123,'Worker','*','*','ALLOW','ROLE','employee'),(124,'Client','confirmTransaction','WRITE','ALLOW','ROLE','administrative'),(125,'Agency','getAgenciesWithWarehouse','*','ALLOW','ROLE','employee'),(126,'Client','activeWorkersWithRole','*','ALLOW','ROLE','employee'),(127,'TicketLog','*','READ','ALLOW','ROLE','employee'),(129,'TicketService','*','*','ALLOW','ROLE','employee'),(130,'Expedition','*','WRITE','ALLOW','ROLE','packager'),(131,'CreditInsurance','*','READ','ALLOW','ROLE','employee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','employee'),(133,'ItemTag','*','WRITE','ALLOW','ROLE','marketingBoss'),(135,'ZoneGeo','*','READ','ALLOW','ROLE','employee'),(136,'ZoneCalendar','*','READ','ALLOW','ROLE','employee'),(137,'ZoneIncluded','*','READ','ALLOW','ROLE','employee'),(138,'LabourHoliday','*','READ','ALLOW','ROLE','employee'),(139,'LabourHolidayLegend','*','READ','ALLOW','ROLE','employee'),(140,'LabourHolidayType','*','READ','ALLOW','ROLE','employee'),(141,'Zone','*','WRITE','ALLOW','ROLE','deliveryBoss'),(142,'ZoneCalendar','*','WRITE','ALLOW','ROLE','deliveryBoss'),(143,'ZoneIncluded','*','*','ALLOW','ROLE','deliveryBoss'),(144,'Stowaway','*','*','ALLOW','ROLE','employee'),(145,'Ticket','getPossibleStowaways','READ','ALLOW','ROLE','employee'),(147,'UserConfigView','*','*','ALLOW','ROLE','employee'),(148,'UserConfigView','*','*','ALLOW','ROLE','employee'),(149,'Sip','*','READ','ALLOW','ROLE','employee'),(150,'Sip','*','WRITE','ALLOW','ROLE','hr'),(151,'Department','*','READ','ALLOW','ROLE','employee'),(152,'Department','*','WRITE','ALLOW','ROLE','hr'),(153,'Route','*','READ','ALLOW','ROLE','employee'),(154,'Route','*','WRITE','ALLOW','ROLE','delivery'),(155,'WorkerCalendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'WorkerCalendar','absences','READ','ALLOW','ROLE','employee'),(158,'ItemTag','*','WRITE','ALLOW','ROLE','accessory'),(160,'TicketServiceType','*','READ','ALLOW','ROLE','employee'),(161,'TicketConfig','*','READ','ALLOW','ROLE','employee'),(162,'InvoiceOut','delete','WRITE','ALLOW','ROLE','invoicing'),(163,'InvoiceOut','book','WRITE','ALLOW','ROLE','invoicing'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','employee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(193,'Zone','editPrices','WRITE','ALLOW','ROLE','deliveryBoss'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','employee'),(198,'ClaimDms','removeFile','WRITE','ALLOW','ROLE','employee'),(199,'ClaimDms','*','READ','ALLOW','ROLE','employee'),(200,'Claim','uploadFile','WRITE','ALLOW','ROLE','employee'),(201,'Sale','updateConcept','WRITE','ALLOW','ROLE','employee'),(202,'Claim','updateClaimAction','WRITE','ALLOW','ROLE','salesAssistant'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES;