From fba09e8c40bd66f4e1f2471ffb6a2de1b3d42dee Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 12 Jan 2022 14:02:58 +0100 Subject: [PATCH 1/5] feat(ticket_volume): volume for packingType --- db/changes/10410-january/00-saleVolume.sql | 35 ++++++++++++++++++ .../00-smsConfig.sql | 0 .../01-smsConfig_update.sql | 0 db/dump/fixtures.sql | 36 +++++++++---------- .../ticket/back/methods/ticket/getVolume.js | 22 +++++++++--- modules/ticket/front/locale/es.yml | 1 + modules/ticket/front/volume/index.html | 23 ++++++------ modules/ticket/front/volume/index.js | 24 +++++-------- 8 files changed, 90 insertions(+), 51 deletions(-) create mode 100644 db/changes/10410-january/00-saleVolume.sql rename db/changes/{10410-noname => 10410-january}/00-smsConfig.sql (100%) rename db/changes/{10410-noname => 10410-january}/01-smsConfig_update.sql (100%) diff --git a/db/changes/10410-january/00-saleVolume.sql b/db/changes/10410-january/00-saleVolume.sql new file mode 100644 index 000000000..d31a68a59 --- /dev/null +++ b/db/changes/10410-january/00-saleVolume.sql @@ -0,0 +1,35 @@ +CREATE OR REPLACE +ALGORITHM = UNDEFINED VIEW `vn`.`saleVolume` AS +select + `s`.`ticketFk` AS `ticketFk`, + `s`.`id` AS `saleFk`, + round(`ic`.`cm3delivery` * `s`.`quantity` / 1000, 0) AS `litros`, + `t`.`routeFk` AS `routeFk`, + `t`.`shipped` AS `shipped`, + `t`.`landed` AS `landed`, + `s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `volume`, + `s`.`quantity` * `ic`.`grams` / 1000 AS `physicalWeight`, + `s`.`quantity` * `ic`.`cm3delivery` * greatest(`i`.`density`, 167) / 1000000 AS `weight`, + `s`.`quantity` * `ic`.`cm3delivery` / 1000000 AS `physicalVolume`, + `s`.`quantity` * `ic`.`cm3delivery` * ifnull(`t`.`zonePrice`, `z`.`price`) / (`vc`.`standardFlowerBox` * 1000) AS `freight`, + `t`.`zoneFk` AS `zoneFk`, + `t`.`clientFk` AS `clientFk`, + `s`.`isPicked` AS `isPicked`, + `s`.`quantity` * `s`.`price` * (100 - `s`.`discount`) / 100 AS `eurosValue`, + `i`.`itemPackingTypeFk` AS `itemPackingTypeFk` +from + (((((`sale` `s` +join `item` `i` on + (`i`.`id` = `s`.`itemFk`)) +join `ticket` `t` on + (`t`.`id` = `s`.`ticketFk`)) +join `zone` `z` on + (`z`.`id` = `t`.`zoneFk`)) +join `volumeConfig` `vc`) +join `itemCost` `ic` on + (`ic`.`itemFk` = `s`.`itemFk` + and `ic`.`warehouseFk` = `t`.`warehouseFk`)) +where + `s`.`quantity` > 0; + + -- NO FUNCIONA diff --git a/db/changes/10410-noname/00-smsConfig.sql b/db/changes/10410-january/00-smsConfig.sql similarity index 100% rename from db/changes/10410-noname/00-smsConfig.sql rename to db/changes/10410-january/00-smsConfig.sql diff --git a/db/changes/10410-noname/01-smsConfig_update.sql b/db/changes/10410-january/01-smsConfig_update.sql similarity index 100% rename from db/changes/10410-noname/01-smsConfig_update.sql rename to db/changes/10410-january/01-smsConfig_update.sql diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index 8274da0e1..b657d7613 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -799,25 +799,25 @@ INSERT INTO `vn`.`itemFamily`(`code`, `description`) ('VT', 'Sales'); INSERT INTO `vn`.`item`(`id`, `typeFk`, `size`, `inkFk`, `stems`, `originFk`, `description`, `producerFk`, `intrastatFk`, `expenceFk`, - `comment`, `relevancy`, `image`, `subName`, `minPrice`, `stars`, `family`, `isFloramondo`, `genericFk`) + `comment`, `relevancy`, `image`, `subName`, `minPrice`, `stars`, `family`, `isFloramondo`, `genericFk`, `itemPackingTypeFk`) VALUES - (1, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 1, 'VT', 0, NULL), - (2, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '2', NULL, 0, 2, 'VT', 0, NULL), - (3, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '3', NULL, 0, 5, 'VT', 0, NULL), - (4, 1, 60, 'YEL', 1, 1, 'Increases block', 1, 05080000, 4751000000, NULL, 0, '4', NULL, 0, 3, 'VT', 0, NULL), - (5, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '5', NULL, 0, 3, 'VT', 0, NULL), - (6, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '6', NULL, 0, 4, 'VT', 0, NULL), - (7, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '7', NULL, 0, 4, 'VT', 0, NULL), - (8, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '8', NULL, 0, 5, 'VT', 0, NULL), - (9, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '9', NULL, 0, 4, 'VT', 1, NULL), - (10, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '10', NULL, 0, 4, 'VT', 0, NULL), - (11, 1, 60, 'YEL', 1, 1, NULL, 1, 05080000, 4751000000, NULL, 0, '11', NULL, 0, 4, 'VT', 0, NULL), - (12, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '12', NULL, 0, 3, 'VT', 0, NULL), - (13, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '13', NULL, 0, 2, 'VT', 1, NULL), - (14, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 4, 'VT', 1, NULL), - (15, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 0, 'EMB', 0, NULL), - (16, 6, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 0, 'EMB', 0, NULL), - (71, 6, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 0, 'VT', 0, NULL); + (1, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '1', NULL, 0, 1, 'VT', 0, NULL, 'V'), + (2, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '2', NULL, 0, 2, 'VT', 0, NULL, 'H'), + (3, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '3', NULL, 0, 5, 'VT', 0, NULL, NULL), + (4, 1, 60, 'YEL', 1, 1, 'Increases block', 1, 05080000, 4751000000, NULL, 0, '4', NULL, 0, 3, 'VT', 0, NULL, NULL), + (5, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '5', NULL, 0, 3, 'VT', 0, NULL, NULL), + (6, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '6', NULL, 0, 4, 'VT', 0, NULL, NULL), + (7, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '7', NULL, 0, 4, 'VT', 0, NULL, NULL), + (8, 2, 70, 'YEL', 1, 1, NULL, 1, 06021010, 2000000000, NULL, 0, '8', NULL, 0, 5, 'VT', 0, NULL, NULL), + (9, 2, 70, 'BLU', 1, 2, NULL, 1, 06021010, 2000000000, NULL, 0, '9', NULL, 0, 4, 'VT', 1, NULL, NULL), + (10, 1, 60, 'YEL', 1, 3, NULL, 1, 05080000, 4751000000, NULL, 0, '10', NULL, 0, 4, 'VT', 0, NULL, NULL), + (11, 1, 60, 'YEL', 1, 1, NULL, 1, 05080000, 4751000000, NULL, 0, '11', NULL, 0, 4, 'VT', 0, NULL, NULL), + (12, 3, 30, 'RED', 1, 2, NULL, 2, 06021010, 4751000000, NULL, 0, '12', NULL, 0, 3, 'VT', 0, NULL, NULL), + (13, 5, 30, 'RED', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '13', NULL, 0, 2, 'VT', 1, NULL, NULL), + (14, 5, 90, 'BLU', 1, 2, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 4, 'VT', 1, NULL, NULL), + (15, 4, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 0, 'EMB', 0, NULL, NULL), + (16, 6, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 0, 'EMB', 0, NULL, NULL), + (71, 6, NULL, NULL, NULL, 1, NULL, NULL, 06021010, 4751000000, NULL, 0, '', NULL, 0, 0, 'VT', 0, NULL, NULL); -- Update the taxClass after insert of the items UPDATE `vn`.`itemTaxCountry` SET `taxClassFk` = 2 diff --git a/modules/ticket/back/methods/ticket/getVolume.js b/modules/ticket/back/methods/ticket/getVolume.js index 376c9ee4e..785f62f2c 100644 --- a/modules/ticket/back/methods/ticket/getVolume.js +++ b/modules/ticket/back/methods/ticket/getVolume.js @@ -9,10 +9,14 @@ module.exports = Self => { description: 'ticket id', http: {source: 'path'} }], - returns: { - type: ['Object'], - root: true + returns: [{ + arg: 'saleVolume', + type: ['Object'] }, + { + arg: 'packingTypeVolume', + type: ['Object'] + }], http: { path: `/:id/getVolume`, verb: 'GET' @@ -25,7 +29,17 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - return Self.rawSql(`SELECT * FROM vn.saleVolume + const saleVolume = await Self.rawSql(`SELECT * FROM vn.saleVolume WHERE ticketFk = ?`, [ticketFk], myOptions); + + const packingTypeVolume = await Self.rawSql(` + SELECT s.itemPackingTypeFk code, i.description, SUM(s.volume) volume + FROM vn.saleVolume s + LEFT JOIN vn.itemPackingType i + ON i.code = s.itemPackingTypeFk + WHERE s.ticketFk = ? + GROUP BY s.itemPackingTypeFk`, [ticketFk], myOptions); + + return [saleVolume, packingTypeVolume] }; }; diff --git a/modules/ticket/front/locale/es.yml b/modules/ticket/front/locale/es.yml index 6e502ed7d..752dd7b36 100644 --- a/modules/ticket/front/locale/es.yml +++ b/modules/ticket/front/locale/es.yml @@ -37,6 +37,7 @@ Observation type: Tipo de observación Original: Original Package size: Bultos Package type: Tipo de porte +Packing type: Encajado Phone: Teléfono PPU: Ud. Price: Precio diff --git a/modules/ticket/front/volume/index.html b/modules/ticket/front/volume/index.html index 70bd4f5fb..8f17a9475 100644 --- a/modules/ticket/front/volume/index.html +++ b/modules/ticket/front/volume/index.html @@ -6,22 +6,17 @@ data="$ctrl.sales" limit="20"> - - - -
- - - - -
+
+ + + + +
@@ -29,6 +24,7 @@ Item Description + Packing type Quantity m³ per quantity @@ -55,6 +51,7 @@ tabindex="-1"> + {{::sale.item.itemPackingTypeFk}} {{::sale.quantity}} {{::sale.saleVolume.volume | number:3}} diff --git a/modules/ticket/front/volume/index.js b/modules/ticket/front/volume/index.js index ead46024b..33fe66bdb 100644 --- a/modules/ticket/front/volume/index.js +++ b/modules/ticket/front/volume/index.js @@ -23,24 +23,16 @@ class Controller extends Section { if (value) this.applyVolumes(); } - get volumes() { - return this._volumes; - } - - set volumes(value) { - this._volumes = value; - - if (value) this.applyVolumes(); - } - applyVolumes() { - if (!this.sales || !this.volumes) return; - - this.sales.forEach(sale => { - this.volumes.forEach(volume => { - if (sale.id === volume.saleFk) - sale.saleVolume = volume; + const ticket = this.sales[0].ticketFk + this.$http.get(`Tickets/${ticket}/getVolume`).then(res => { + this.sales.forEach(sale => { + res.data.saleVolume.forEach(volume => { + if (sale.id === volume.saleFk) + sale.saleVolume = volume; + }); }); + this.packingTypeVolume = res.data.packingTypeVolume }); } } From c9564e817a1e55f01a8dab123894b4b6cbc727e1 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 12 Jan 2022 14:04:16 +0100 Subject: [PATCH 2/5] test(ticket_volume): frontTest --- modules/ticket/front/volume/index.spec.js | 43 ++++++++++++++++------- 1 file changed, 31 insertions(+), 12 deletions(-) diff --git a/modules/ticket/front/volume/index.spec.js b/modules/ticket/front/volume/index.spec.js index 5f6f433fb..578c6109c 100644 --- a/modules/ticket/front/volume/index.spec.js +++ b/modules/ticket/front/volume/index.spec.js @@ -33,17 +33,20 @@ describe('ticket', () => { }); }); - describe('volumes() setter', () => { - it('should set volumes property on controller an then call applyVolumes() method', () => { - jest.spyOn(controller, 'applyVolumes'); - - controller.volumes = [{id: 1}]; - - expect(controller.applyVolumes).toHaveBeenCalledWith(); - }); - }); - describe('applyVolumes()', () => { + const ticket = 1; + const respondGet = + { + saleVolume: [ + {saleFk: 1, volume: 0.012}, + {saleFk: 2, volume: 0.015} + ], + packingTypeVolume: [ + {code: 'V', volume: 1}, + {code: 'H',volume: 2}, + ] + }; + it(`should not apply volumes to the sales if sales property is not defined on controller`, () => { controller.sales = [{id: 1, name: 'Sale one'}, {id: 2, name: 'Sale two'}]; @@ -58,12 +61,28 @@ describe('ticket', () => { }); it(`should apply volumes to the sales if sales and volumes properties are defined on controller`, () => { - controller.sales = [{id: 1, name: 'Sale one'}, {id: 2, name: 'Sale two'}]; - controller.volumes = [{saleFk: 1, volume: 0.012}, {saleFk: 2, volume: 0.015}]; + $httpBackend.expectGET(`Tickets/${ticket}/getVolume`).respond(respondGet); + controller.sales = [ + {id: 1, name: 'Sale one', ticketFk: ticket}, + {id: 2, name: 'Sale two'} + ]; + $httpBackend.flush(); expect(controller.sales[0].saleVolume.volume).toEqual(0.012); expect(controller.sales[1].saleVolume.volume).toEqual(0.015); }); + + it(`should apply packing volumes to the sales if sales and volumes properties are defined on controller`, () => { + $httpBackend.expectGET(`Tickets/${ticket}/getVolume`).respond(respondGet); + controller.sales = [ + {id: 1, name: 'Sale one', ticketFk: ticket}, + {id: 2, name: 'Sale two'} + ]; + $httpBackend.flush(); + + expect(controller.packingTypeVolume[0]).toBeDefined; + expect(controller.packingTypeVolume[1]).toBeDefined + }); }); /* From 757fe73ecd1826b76ca8d424dbad383ac0fa7735 Mon Sep 17 00:00:00 2001 From: alexm Date: Wed, 12 Jan 2022 14:55:20 +0100 Subject: [PATCH 3/5] test(ticket_volume): backTest --- db/changes/10410-january/00-saleVolume.sql | 7 +++++-- modules/ticket/back/methods/ticket/getVolume.js | 10 +++++++--- .../ticket/back/methods/ticket/specs/getVolume.spec.js | 5 ++++- 3 files changed, 16 insertions(+), 6 deletions(-) diff --git a/db/changes/10410-january/00-saleVolume.sql b/db/changes/10410-january/00-saleVolume.sql index d31a68a59..e8a5e3433 100644 --- a/db/changes/10410-january/00-saleVolume.sql +++ b/db/changes/10410-january/00-saleVolume.sql @@ -1,3 +1,6 @@ +USE vn; +DELIMITER $$ +$$ CREATE OR REPLACE ALGORITHM = UNDEFINED VIEW `vn`.`saleVolume` AS select @@ -31,5 +34,5 @@ join `itemCost` `ic` on and `ic`.`warehouseFk` = `t`.`warehouseFk`)) where `s`.`quantity` > 0; - - -- NO FUNCIONA +$$ +DELIMITER ; diff --git a/modules/ticket/back/methods/ticket/getVolume.js b/modules/ticket/back/methods/ticket/getVolume.js index 785f62f2c..57493a5e3 100644 --- a/modules/ticket/back/methods/ticket/getVolume.js +++ b/modules/ticket/back/methods/ticket/getVolume.js @@ -29,11 +29,15 @@ module.exports = Self => { if (typeof options == 'object') Object.assign(myOptions, options); - const saleVolume = await Self.rawSql(`SELECT * FROM vn.saleVolume - WHERE ticketFk = ?`, [ticketFk], myOptions); + const saleVolume = await Self.rawSql(` + SELECT saleFk, volume + FROM vn.saleVolume + WHERE ticketFk = ?`, [ticketFk], myOptions); const packingTypeVolume = await Self.rawSql(` - SELECT s.itemPackingTypeFk code, i.description, SUM(s.volume) volume + SELECT s.itemPackingTypeFk code, + i.description, + SUM(s.volume) volume FROM vn.saleVolume s LEFT JOIN vn.itemPackingType i ON i.code = s.itemPackingTypeFk diff --git a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js index 35134e4d0..af171c8eb 100644 --- a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js @@ -9,8 +9,11 @@ describe('ticket getVolume()', () => { const ticketId = 1; const result = await models.Ticket.getVolume(ticketId, options); + const saleVolume = result[0]; + const packingTypeVolume = result[1]; - expect(result[0].volume).toEqual(1.09); + expect(saleVolume).toBeDefined; + expect(packingTypeVolume).toBeDefined; await tx.rollback(); } catch (e) { From 245161375cd307adb4fddc18a3e2f1244992878c Mon Sep 17 00:00:00 2001 From: alexm Date: Thu, 13 Jan 2022 08:27:56 +0100 Subject: [PATCH 4/5] update database --- db/changes/10360-september/00-ACL.sql | 4 - .../10360-september/00-sale_problems.sql | 197 - .../10360-september/00-ticket_getProblems.sql | 48 - .../10360-september/01-travelThermograph.sql | 1 - db/changes/10370-pickles/00-ACL.sql | 1 - .../10370-pickles/00-accountingType.sql | 3 - db/changes/10370-pickles/00-payMethod.sql | 4 - db/changes/10370-pickles/00-silexACL.sql | 2 - .../10370-pickles/00-ticket_getProblems.sql | 48 - .../10380-allsaints/00-defaultViewConfig.sql | 14 - .../00-smsConfig.sql | 0 .../01-smsConfig_update.sql | 0 db/dump/dumpedFixtures.sql | 20 +- db/dump/structure.sql | 3716 ++++++++--------- 14 files changed, 1712 insertions(+), 2346 deletions(-) delete mode 100644 db/changes/10360-september/00-ACL.sql delete mode 100644 db/changes/10360-september/00-sale_problems.sql delete mode 100644 db/changes/10360-september/00-ticket_getProblems.sql delete mode 100644 db/changes/10360-september/01-travelThermograph.sql delete mode 100644 db/changes/10370-pickles/00-ACL.sql delete mode 100644 db/changes/10370-pickles/00-accountingType.sql delete mode 100644 db/changes/10370-pickles/00-payMethod.sql delete mode 100644 db/changes/10370-pickles/00-silexACL.sql delete mode 100644 db/changes/10370-pickles/00-ticket_getProblems.sql delete mode 100644 db/changes/10380-allsaints/00-defaultViewConfig.sql rename db/changes/{10410-noname => 10410-january}/00-smsConfig.sql (100%) rename db/changes/{10410-noname => 10410-january}/01-smsConfig_update.sql (100%) diff --git a/db/changes/10360-september/00-ACL.sql b/db/changes/10360-september/00-ACL.sql deleted file mode 100644 index 6a3fcf708..000000000 --- a/db/changes/10360-september/00-ACL.sql +++ /dev/null @@ -1,4 +0,0 @@ -DELETE FROM `salix`.`ACL` WHERE id = 48; -DELETE FROM `salix`.`ACL` WHERE id = 49; -DELETE FROM `salix`.`ACL` WHERE id = 50; -DELETE FROM `salix`.`ACL` WHERE id = 107; \ No newline at end of file diff --git a/db/changes/10360-september/00-sale_problems.sql b/db/changes/10360-september/00-sale_problems.sql deleted file mode 100644 index 2702b524c..000000000 --- a/db/changes/10360-september/00-sale_problems.sql +++ /dev/null @@ -1,197 +0,0 @@ -drop procedure `vn`.`sale_getProblems`; - -DELIMITER $$ -$$ -create - definer = root@`%` procedure `vn`.`sale_getProblems`(IN vIsTodayRelative tinyint(1)) -BEGIN -/** - * Calcula los problemas de cada venta - * para un conjunto de tickets. - * - * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular - * @return tmp.sale_problems - */ - DECLARE vWarehouse INT; - DECLARE vDate DATE; - DECLARE vAvailableCache INT; - DECLARE vDone INT DEFAULT 0; - DECLARE vComponentCount INT; - - DECLARE vCursor CURSOR FOR - SELECT DISTINCT tt.warehouseFk, IF(vIsTodayRelative, CURDATE(), date(tt.shipped)) - FROM tmp.sale_getProblems tt - WHERE DATE(tt.shipped) BETWEEN CURDATE() - AND TIMESTAMPADD(DAY, IF(vIsTodayRelative, 9.9, 1.9), CURDATE()); - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.sale_problems; - CREATE TEMPORARY TABLE tmp.sale_problems ( - ticketFk INT(11), - saleFk INT(11), - isFreezed INTEGER(1) DEFAULT 0, - risk DECIMAL(10,2) DEFAULT 0, - hasHighRisk TINYINT(1) DEFAULT 0, - hasTicketRequest INTEGER(1) DEFAULT 0, - isAvailable INTEGER(1) DEFAULT 1, - itemShortage VARCHAR(250), - isTaxDataChecked INTEGER(1) DEFAULT 1, - itemDelay VARCHAR(250), - hasComponentLack INTEGER(1), - PRIMARY KEY (ticketFk, saleFk) - ) ENGINE = MEMORY; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; - CREATE TEMPORARY TABLE tmp.ticket_list - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT tp.ticketFk, c.id clientFk - FROM tmp.sale_getProblems tp - JOIN vn.client c ON c.id = tp.clientFk; - - SELECT COUNT(*) INTO vComponentCount - FROM vn.component c - WHERE c.isRequired; - - INSERT INTO tmp.sale_problems(ticketFk, hasComponentLack, saleFk) - SELECT tl.ticketFk, (COUNT(DISTINCT s.id) * vComponentCount > COUNT(c.id)), s.id - FROM tmp.ticket_list tl - JOIN vn.sale s ON s.ticketFk = tl.ticketFk - LEFT JOIN vn.saleComponent sc ON sc.saleFk = s.id - LEFT JOIN vn.component c ON c.id = sc.componentFk AND c.isRequired - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - JOIN vn.deliveryMethod dm ON dm.id = am.deliveryMethodFk - WHERE dm.code IN('AGENCY','DELIVERY','PICKUP') - GROUP BY tl.ticketFk, s.id; - - INSERT INTO tmp.sale_problems(ticketFk, isFreezed) - SELECT DISTINCT tl.ticketFk, TRUE - FROM tmp.ticket_list tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isFreezed - ON DUPLICATE KEY UPDATE - isFreezed = c.isFreezed; - - DROP TEMPORARY TABLE IF EXISTS tmp.clientGetDebt; - CREATE TEMPORARY TABLE tmp.clientGetDebt - (PRIMARY KEY (clientFk)) - ENGINE = MEMORY - SELECT DISTINCT clientFk - FROM tmp.ticket_list; - - CALL clientGetDebt(CURDATE()); - - INSERT INTO tmp.sale_problems(ticketFk, risk, hasHighRisk) - SELECT DISTINCT tl.ticketFk, r.risk, ((r.risk - cc.riskTolerance) > c.credit + 10) - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.agencyMode a ON t.agencyModeFk = a.id - JOIN tmp.risk r ON r.clientFk = t.clientFk - JOIN vn.client c ON c.id = t.clientFk - JOIN vn.clientConfig cc - WHERE r.risk > c.credit + 10 - AND a.isRiskFree = FALSE - ON DUPLICATE KEY UPDATE - risk = r.risk, hasHighRisk = ((r.risk - cc.riskTolerance) > c.credit + 10); - - INSERT INTO tmp.sale_problems(ticketFk, hasTicketRequest) - SELECT DISTINCT tl.ticketFk, TRUE - FROM tmp.ticket_list tl - JOIN vn.ticketRequest tr ON tr.ticketFk = tl.ticketFk - WHERE tr.isOK IS NULL - ON DUPLICATE KEY UPDATE - hasTicketRequest = TRUE; - - OPEN vCursor; - - WHILE NOT vDone - DO - FETCH vCursor INTO vWarehouse, vDate; - - CALL cache.available_refresh(vAvailableCache, FALSE, vWarehouse, vDate); - - INSERT INTO tmp.sale_problems(ticketFk, isAvailable, saleFk) - SELECT tl.ticketFk, FALSE, s.id - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN cache.available av ON av.item_id = i.id - AND av.calc_id = vAvailableCache - WHERE date(t.shipped) = vDate - AND it.categoryFk != 6 - AND IFNULL(av.available, 0) < 0 - AND s.isPicked = FALSE - AND NOT i.generic - AND vWarehouse = t.warehouseFk - GROUP BY tl.ticketFk - ON DUPLICATE KEY UPDATE - isAvailable = FALSE, saleFk = VALUES(saleFk); - - INSERT INTO tmp.sale_problems(ticketFk, itemShortage, saleFk) - SELECT ticketFk, problem, saleFk - FROM ( - SELECT tl.ticketFk, CONCAT('F: ',GROUP_CONCAT(i.id, ' ', i.longName, ' ')) problem, s.id AS saleFk - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - LEFT JOIN cache.available av ON av.item_id = i.id AND av.calc_id = vAvailableCache - WHERE IFNULL(av.available, 0) < 0 - AND s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk LIMIT 1) sub - ON DUPLICATE KEY UPDATE - itemShortage = sub.problem, saleFk = sub.saleFk; - - INSERT INTO tmp.sale_problems(ticketFk, itemDelay, saleFk) - SELECT ticketFk, problem, saleFk - FROM ( - SELECT tl.ticketFk, GROUP_CONCAT('I: ',i.id, ' ', i.longName, ' ') problem, s.id AS saleFk - FROM tmp.ticket_list tl - JOIN vn.ticket t ON t.id = tl.ticketFk - JOIN vn.sale s ON s.ticketFk = t.id - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.itemType it on it.id = i.typeFk - LEFT JOIN vn.itemShelvingStock_byWarehouse issw ON issw.itemFk = i.id AND issw.warehouseFk = t.warehouseFk - WHERE s.quantity > IFNULL(issw.visible, 0) - AND s.quantity > 0 - AND s.isPicked = FALSE - AND s.reserved = FALSE - AND it.categoryFk != 6 - AND IF(vIsTodayRelative, TRUE, date(t.shipped) = vDate) - AND NOT i.generic - AND CURDATE() = vDate - AND t.warehouseFk = vWarehouse - GROUP BY tl.ticketFk LIMIT 1) sub - ON DUPLICATE KEY UPDATE - itemDelay = sub.problem, saleFk = sub.saleFk; - END WHILE; - - CLOSE vCursor; - - INSERT INTO tmp.sale_problems(ticketFk, isTaxDataChecked) - SELECT DISTINCT tl.ticketFk, FALSE - FROM tmp.ticket_list tl - JOIN vn.client c ON c.id = tl.clientFk - WHERE c.isTaxDataChecked = FALSE - ON DUPLICATE KEY UPDATE - isTaxDataChecked = FALSE; - - DROP TEMPORARY TABLE - tmp.clientGetDebt, - tmp.ticket_list; -END;;$$ -DELIMITER ; diff --git a/db/changes/10360-september/00-ticket_getProblems.sql b/db/changes/10360-september/00-ticket_getProblems.sql deleted file mode 100644 index dacba7e09..000000000 --- a/db/changes/10360-september/00-ticket_getProblems.sql +++ /dev/null @@ -1,48 +0,0 @@ -drop procedure `vn`.`ticket_getProblems`; - -DELIMITER $$ -$$ -create - definer = root@`%` procedure `vn`.`ticket_getProblems`(IN vIsTodayRelative tinyint(1)) -BEGIN -/** - * Calcula los problemas para un conjunto de tickets. - * Agrupados por ticket - * - * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular - * @return tmp.ticket_problems - */ - CALL sale_getProblems(vIsTodayRelative); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems - (INDEX (ticketFk)) - ENGINE = MEMORY - SELECT - ticketFk, - MAX(p.isFreezed) AS isFreezed, - MAX(p.risk) AS risk, - MAX(p.hasHighRisk) AS hasHighRisk, - MAX(p.hasTicketRequest) AS hasTicketRequest, - MIN(p.isAvailable) AS isAvailable, - MAX(p.itemShortage) AS itemShortage, - MIN(p.isTaxDataChecked) AS isTaxDataChecked, - MAX(p.hasComponentLack) AS hasComponentLack, - 0 AS totalProblems - FROM tmp.sale_problems p - GROUP BY ticketFk; - - UPDATE tmp.ticket_problems tp - SET tp.totalProblems = ( - (tp.isFreezed) + - IF(tp.risk, TRUE, FALSE) + - (tp.hasTicketRequest) + - (tp.isAvailable = 0) + - (tp.isTaxDataChecked = 0) + - (tp.hasComponentLack) - ); - - DROP TEMPORARY TABLE - tmp.sale_problems; -END;;$$ -DELIMITER ; diff --git a/db/changes/10360-september/01-travelThermograph.sql b/db/changes/10360-september/01-travelThermograph.sql deleted file mode 100644 index dec86d102..000000000 --- a/db/changes/10360-september/01-travelThermograph.sql +++ /dev/null @@ -1 +0,0 @@ -alter table `vn`.`travelThermograph` modify `temperature` enum('COOL', 'WARM') null; \ No newline at end of file diff --git a/db/changes/10370-pickles/00-ACL.sql b/db/changes/10370-pickles/00-ACL.sql deleted file mode 100644 index c5e10dec5..000000000 --- a/db/changes/10370-pickles/00-ACL.sql +++ /dev/null @@ -1 +0,0 @@ -UPDATE salix.ACL t SET t.principalId = 'employee' WHERE t.id = 269; diff --git a/db/changes/10370-pickles/00-accountingType.sql b/db/changes/10370-pickles/00-accountingType.sql deleted file mode 100644 index 1313e8223..000000000 --- a/db/changes/10370-pickles/00-accountingType.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE vn.accountingType ADD maxAmount INT DEFAULT NULL NULL; - -UPDATE vn.accountingType SET maxAmount = 1000 WHERE code = 'cash'; diff --git a/db/changes/10370-pickles/00-payMethod.sql b/db/changes/10370-pickles/00-payMethod.sql deleted file mode 100644 index ac6429b99..000000000 --- a/db/changes/10370-pickles/00-payMethod.sql +++ /dev/null @@ -1,4 +0,0 @@ -ALTER TABLE vn.payMethod CHANGE ibanRequired ibanRequiredForClients tinyint(3) DEFAULT 0 NULL; -ALTER TABLE vn.payMethod ADD ibanRequiredForSuppliers tinyint(3) DEFAULT 0 NULL; -ALTER TABLE vn.payMethod CHANGE ibanRequiredForSuppliers ibanRequiredForSuppliers tinyint(3) DEFAULT 0 NULL AFTER ibanRequiredForClients; -UPDATE vn.payMethod SET ibanRequiredForSuppliers = 1 WHERE code = 'wireTransfer'; \ No newline at end of file diff --git a/db/changes/10370-pickles/00-silexACL.sql b/db/changes/10370-pickles/00-silexACL.sql deleted file mode 100644 index 82623baf0..000000000 --- a/db/changes/10370-pickles/00-silexACL.sql +++ /dev/null @@ -1,2 +0,0 @@ -ALTER TABLE vn.silexACL MODIFY module VARCHAR(50) NOT NULL; -ALTER TABLE vn.silexACL MODIFY method VARCHAR(50) NOT NULL; \ No newline at end of file diff --git a/db/changes/10370-pickles/00-ticket_getProblems.sql b/db/changes/10370-pickles/00-ticket_getProblems.sql deleted file mode 100644 index 2ee057cd2..000000000 --- a/db/changes/10370-pickles/00-ticket_getProblems.sql +++ /dev/null @@ -1,48 +0,0 @@ -drop procedure `vn`.`ticket_getProblems`; - -DELIMITER $$ -$$ -create - definer = root@`%` procedure `vn`.`ticket_getProblems`(IN vIsTodayRelative tinyint(1)) -BEGIN -/** - * Calcula los problemas para un conjunto de tickets. - * Agrupados por ticket - * - * @table tmp.sale_getProblems(ticketFk, clientFk, warehouseFk, shipped) Identificadores de los tickets a calcular - * @return tmp.ticket_problems - */ - CALL sale_getProblems(vIsTodayRelative); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticket_problems; - CREATE TEMPORARY TABLE tmp.ticket_problems - (PRIMARY KEY (ticketFk)) - ENGINE = MEMORY - SELECT - ticketFk, - MAX(p.isFreezed) AS isFreezed, - MAX(p.risk) AS risk, - MAX(p.hasHighRisk) AS hasHighRisk, - MAX(p.hasTicketRequest) AS hasTicketRequest, - MIN(p.isAvailable) AS isAvailable, - MAX(p.itemShortage) AS itemShortage, - MIN(p.isTaxDataChecked) AS isTaxDataChecked, - MAX(p.hasComponentLack) AS hasComponentLack, - 0 AS totalProblems - FROM tmp.sale_problems p - GROUP BY ticketFk; - - UPDATE tmp.ticket_problems tp - SET tp.totalProblems = ( - (tp.isFreezed) + - IF(tp.risk, TRUE, FALSE) + - (tp.hasTicketRequest) + - (tp.isAvailable = 0) + - (tp.isTaxDataChecked = 0) + - (tp.hasComponentLack) - ); - - DROP TEMPORARY TABLE - tmp.sale_problems; -END;;$$ -DELIMITER ; \ No newline at end of file diff --git a/db/changes/10380-allsaints/00-defaultViewConfig.sql b/db/changes/10380-allsaints/00-defaultViewConfig.sql deleted file mode 100644 index e4b2f6c3d..000000000 --- a/db/changes/10380-allsaints/00-defaultViewConfig.sql +++ /dev/null @@ -1,14 +0,0 @@ -CREATE TABLE `salix`.`defaultViewConfig` -( - tableCode VARCHAR(25) not null, - columns JSON not null -) -comment 'The default configuration of columns for views'; - -INSERT INTO `salix`.`defaultViewConfig` (tableCode, columns) - VALUES - ('itemsIndex', '{"intrastat":false,"stemMultiplier":false,"landed":false}'), - ('latestBuys', '{"intrastat":false,"description":false,"density":false,"isActive":false,"freightValue":false,"packageValue":false,"isIgnored":false,"price2":false,"minPrice":true,"ektFk":false,"weight":false,"id":true,"packing":true,"grouping":true,"quantity":true,"size":false,"name":true,"code":true,"origin":true,"family":true,"entryFk":true,"buyingValue":true,"comissionValue":false,"price3":true,"packageFk":true,"packingOut":true}'), - ('ticketsMonitor', '{"id":false}'); - - \ No newline at end of file diff --git a/db/changes/10410-noname/00-smsConfig.sql b/db/changes/10410-january/00-smsConfig.sql similarity index 100% rename from db/changes/10410-noname/00-smsConfig.sql rename to db/changes/10410-january/00-smsConfig.sql diff --git a/db/changes/10410-noname/01-smsConfig_update.sql b/db/changes/10410-january/01-smsConfig_update.sql similarity index 100% rename from db/changes/10410-noname/01-smsConfig_update.sql rename to db/changes/10410-january/01-smsConfig_update.sql diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index f9f381bec..e11cf44d5 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -34,7 +34,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:20 +-- Dump completed on 2022-01-13 7:50:24 USE `account`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -120,7 +120,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:21 +-- Dump completed on 2022-01-13 7:50:25 USE `salix`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -144,7 +144,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','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(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','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(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'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(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','deleteSales','*','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','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','claimManager'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(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','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(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','*','*','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,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','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'),(165,'TicketDms','*','*','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','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(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','claimManager'),(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'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(219,'Account','acl','READ','ALLOW','ROLE','account'),(220,'Account','getCurrentUserData','READ','ALLOW','ROLE','account'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(246,'Account','changePassword','*','ALLOW','ROLE','account'),(247,'UserAccount','exists','*','ALLOW','ROLE','account'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','*','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(282,'UserAccount','*','WRITE','ALLOW','ROLE','it'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'); +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','trainee'),(13,'Employee','*','READ','ALLOW','ROLE','employee'),(14,'PayMethod','*','READ','ALLOW','ROLE','trainee'),(16,'FakeProduction','*','READ','ALLOW','ROLE','employee'),(17,'Warehouse','* ','READ','ALLOW','ROLE','trainee'),(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','trainee'),(30,'GreugeType','*','READ','ALLOW','ROLE','trainee'),(31,'Mandate','*','READ','ALLOW','ROLE','trainee'),(32,'MandateType','*','READ','ALLOW','ROLE','trainee'),(33,'Company','*','READ','ALLOW','ROLE','trainee'),(34,'Greuge','*','READ','ALLOW','ROLE','trainee'),(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'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','trainee'),(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','deleteSales','*','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','*','READ','ALLOW','ROLE','employee'),(94,'Agency','landsThatDay','*','ALLOW','ROLE','employee'),(96,'ClaimEnd','*','READ','ALLOW','ROLE','employee'),(97,'ClaimEnd','*','WRITE','ALLOW','ROLE','claimManager'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','claimManager'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','claimManager'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','trainee'),(111,'ClientLog','*','READ','ALLOW','ROLE','trainee'),(112,'Defaulter','*','READ','ALLOW','ROLE','employee'),(113,'ClientRisk','*','READ','ALLOW','ROLE','trainee'),(114,'Receipt','*','READ','ALLOW','ROLE','trainee'),(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','trainee'),(132,'CreditClassification','*','READ','ALLOW','ROLE','trainee'),(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','*','*','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,'Calendar','*','READ','ALLOW','ROLE','hr'),(156,'WorkerLabour','*','READ','ALLOW','ROLE','hr'),(157,'Calendar','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'),(165,'TicketDms','*','*','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','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','deliveryBoss'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','trainee'),(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','claimManager'),(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'),(208,'Sale','recalculatePrice','WRITE','ALLOW','ROLE','employee'),(209,'Ticket','recalculateComponents','WRITE','ALLOW','ROLE','employee'),(211,'TravelLog','*','READ','ALLOW','ROLE','buyer'),(212,'Thermograph','*','*','ALLOW','ROLE','buyer'),(213,'TravelThermograph','*','WRITE','ALLOW','ROLE','buyer'),(214,'Entry','*','*','ALLOW','ROLE','buyer'),(215,'TicketWeekly','*','WRITE','ALLOW','ROLE','buyer'),(216,'TravelThermograph','*','READ','ALLOW','ROLE','employee'),(218,'Intrastat','*','*','ALLOW','ROLE','buyer'),(219,'Account','acl','READ','ALLOW','ROLE','account'),(220,'Account','getCurrentUserData','READ','ALLOW','ROLE','account'),(221,'UserConfig','getUserConfig','READ','ALLOW','ROLE','account'),(222,'Client','*','READ','ALLOW','ROLE','trainee'),(226,'ClientObservation','*','READ','ALLOW','ROLE','trainee'),(227,'Address','*','READ','ALLOW','ROLE','trainee'),(228,'AddressObservation','*','READ','ALLOW','ROLE','trainee'),(230,'ClientCredit','*','READ','ALLOW','ROLE','trainee'),(231,'ClientContact','*','READ','ALLOW','ROLE','trainee'),(232,'ClientSample','*','READ','ALLOW','ROLE','trainee'),(233,'EntryLog','*','READ','ALLOW','ROLE','buyer'),(234,'WorkerLog','*','READ','ALLOW','ROLE','salesAssistant'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'),(238,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(239,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(240,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(241,'SupplierContact','*','WRITE','ALLOW','ROLE','administrative'),(242,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(244,'supplier','*','WRITE','ALLOW','ROLE','administrative'),(246,'Account','changePassword','*','ALLOW','ROLE','account'),(247,'UserAccount','exists','*','ALLOW','ROLE','account'),(248,'RoleMapping','*','READ','ALLOW','ROLE','account'),(249,'UserPassword','*','READ','ALLOW','ROLE','account'),(250,'Town','*','WRITE','ALLOW','ROLE','deliveryBoss'),(251,'Province','*','WRITE','ALLOW','ROLE','deliveryBoss'),(252,'Supplier','*','READ','ALLOW','ROLE','employee'),(253,'Supplier','*','WRITE','ALLOW','ROLE','administrative'),(254,'SupplierLog','*','READ','ALLOW','ROLE','employee'),(256,'Image','*','WRITE','ALLOW','ROLE','employee'),(257,'FixedPrice','*','*','ALLOW','ROLE','buyer'),(258,'PayDem','*','READ','ALLOW','ROLE','employee'),(259,'Client','createReceipt','*','ALLOW','ROLE','salesAssistant'),(260,'PrintServerQueue','*','WRITE','ALLOW','ROLE','employee'),(261,'SupplierAccount','*','*','ALLOW','ROLE','administrative'),(262,'Entry','*','*','ALLOW','ROLE','administrative'),(263,'InvoiceIn','*','*','ALLOW','ROLE','administrative'),(264,'StarredModule','*','*','ALLOW','ROLE','employee'),(265,'ItemBotanical','*','WRITE','ALLOW','ROLE','logisticBoss'),(266,'ZoneLog','*','READ','ALLOW','ROLE','employee'),(267,'Genus','*','WRITE','ALLOW','ROLE','logisticBoss'),(268,'Specie','*','WRITE','ALLOW','ROLE','logisticBoss'),(269,'InvoiceOut','createPdf','WRITE','ALLOW','ROLE','employee'),(270,'SupplierAddress','*','*','ALLOW','ROLE','employee'),(271,'SalesMonitor','*','*','ALLOW','ROLE','employee'),(272,'InvoiceInLog','*','*','ALLOW','ROLE','employee'),(273,'InvoiceInTax','*','*','ALLOW','ROLE','administrative'),(274,'InvoiceInLog','*','READ','ALLOW','ROLE','administrative'),(275,'InvoiceOut','createManualInvoice','WRITE','ALLOW','ROLE','invoicing'),(276,'InvoiceOut','globalInvoicing','WRITE','ALLOW','ROLE','invoicing'),(277,'Role','*','*','ALLOW','ROLE','it'),(278,'RoleInherit','*','WRITE','ALLOW','ROLE','grant'),(279,'MailAlias','*','*','ALLOW','ROLE','marketing'),(282,'UserAccount','*','WRITE','ALLOW','ROLE','it'),(283,'EntryObservation','*','*','ALLOW','ROLE','buyer'),(284,'LdapConfig','*','*','ALLOW','ROLE','sysadmin'),(285,'SambaConfig','*','*','ALLOW','ROLE','sysadmin'),(286,'ACL','*','*','ALLOW','ROLE','developer'),(287,'AccessToken','*','*','ALLOW','ROLE','developer'),(288,'MailAliasAccount','*','*','ALLOW','ROLE','marketing'),(289,'MailAliasAccount','*','*','ALLOW','ROLE','hr'),(290,'MailAlias','*','*','ALLOW','ROLE','hr'),(291,'MailForward','*','*','ALLOW','ROLE','marketing'),(292,'MailForward','*','*','ALLOW','ROLE','hr'),(293,'RoleInherit','*','*','ALLOW','ROLE','it'),(294,'RoleRole','*','*','ALLOW','ROLE','it'),(295,'AccountConfig','*','*','ALLOW','ROLE','sysadmin'),(296,'Collection','*','READ','ALLOW','ROLE','employee'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -186,7 +186,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:22 +-- Dump completed on 2022-01-13 7:50:26 USE `vn`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -410,7 +410,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,0,0,0,0,4,1),(2,'Libre',2,0,'FREE',NULL,2,1,0,0,0,1,0,4,1),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1,3,0),(4,'Impreso',4,0,'PRINTED',2,29,1,0,1,0,0,1,2,0),(5,'Preparación',6,1,'ON_PREPARATION',7,5,0,0,0,2,0,0,2,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1,0),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,0,0,4,1),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0,1,0),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0,1,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0,0,0),(11,'Facturado',0,3,'INVOICED',NULL,11,0,1,0,0,0,0,0,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4,1),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0,1,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0,0,0),(20,'Asignado',4,0,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0,2,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0,0,0,0,4,1),(23,'URGENTE',5,1,'LAST_CALL',NULL,23,1,0,1,0,0,0,4,1),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3,1),(25,'Embarcando',3,0,'BOARDING',5,25,1,0,0,0,0,0,3,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0,1,0,0,2,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,0,0,0,1,1,1,3,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,0,0,1,1,0,1,3,0),(30,'Embarcado',4,1,'BOARD',5,30,0,0,0,2,0,0,3,0),(31,'Polizon Impreso',4,1,'PRINTED STOWAWAY',2,29,1,0,1,0,0,1,3,0),(32,'Polizon OK',3,1,'OK STOWAWAY',3,31,1,0,0,1,1,1,3,0),(33,'Auto_Impreso',4,0,'PRINTED_AUTO',2,29,1,0,1,0,0,1,2,0),(34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',NULL,34,0,0,0,0,0,0,4,1),(35,'Semi-Encajado',9,2,'HALF_PACKED',NULL,10,0,1,0,0,0,0,1,0),(36,'Control Previa',3,1,'PREVIOUS_CONTROL',1,36,0,1,0,1,0,1,3,0); +INSERT INTO `state` VALUES (1,'Arreglar',2,0,'FIXING',NULL,1,0,0,0,0,0,0,4,1),(2,'Libre',2,0,'FREE',NULL,2,1,0,0,0,1,0,4,1),(3,'OK',3,0,'OK',3,28,1,0,0,0,1,1,3,0),(4,'Impreso',4,0,'PRINTED',2,29,1,0,1,0,0,1,2,0),(5,'Preparación',6,1,'ON_PREPARATION',7,5,0,0,0,2,0,0,2,0),(6,'En Revisión',7,1,'ON_CHECKING',NULL,6,0,1,0,3,0,0,1,0),(7,'Sin Acabar',1,0,'NOT_READY',NULL,7,0,0,0,0,0,0,4,1),(8,'Revisado',8,1,'CHECKED',NULL,8,0,1,0,3,0,0,1,0),(9,'Encajando',9,2,'PACKING',NULL,9,0,1,0,0,0,0,1,0),(10,'Encajado',10,2,'PACKED',NULL,10,0,1,0,0,0,0,0,0),(11,'Facturado',0,3,'INVOICED',NULL,11,0,1,0,0,0,0,0,0),(12,'Bloqueado',0,0,'BLOCKED',NULL,12,0,0,0,0,0,0,4,1),(13,'En Reparto',11,3,'ON_DELIVERY',NULL,13,0,1,0,0,0,0,0,0),(14,'Preparado',6,1,'PREPARED',NULL,14,0,1,0,2,0,0,1,0),(15,'Pte Recogida',12,3,'WAITING_FOR_PICKUP',NULL,15,0,1,0,0,0,0,0,0),(16,'Entregado',13,3,'DELIVERED',NULL,16,0,1,0,0,0,0,0,0),(20,'Asignado',4,0,'PICKER_DESIGNED',NULL,20,1,0,0,0,0,0,2,0),(21,'Retornado',4,1,'PRINTED_BACK',6,21,0,0,0,0,0,0,2,0),(22,'¿Fecha?',2,0,'WRONG_DATE',NULL,22,0,0,0,0,0,0,4,1),(23,'URGENTE',5,1,'LAST_CALL',NULL,23,1,0,1,0,0,0,4,1),(24,'Encadenado',4,0,'CHAINED',4,24,0,0,0,0,0,0,3,1),(25,'Embarcando',3,0,'BOARDING',5,25,1,0,0,0,0,0,3,0),(26,'Prep Previa',5,1,'PREVIOUS_PREPARATION',1,26,0,0,0,1,0,0,2,0),(27,'Prep Asistida',5,1,'ASSISTED_PREPARATION',7,27,0,0,0,0,0,0,2,0),(28,'Previa OK',3,1,'OK PREVIOUS',3,28,0,0,0,1,1,1,3,0),(29,'Previa Impreso',4,1,'PRINTED PREVIOUS',2,29,0,0,1,1,0,1,3,0),(30,'Embarcado',4,1,'BOARD',5,30,0,0,0,2,0,0,3,0),(31,'Polizon Impreso',4,1,'PRINTED STOWAWAY',2,29,1,0,1,0,0,1,3,0),(32,'Polizon OK',3,1,'OK STOWAWAY',3,31,1,0,0,1,1,1,3,0),(33,'Auto_Impreso',4,0,'PRINTED_AUTO',2,29,1,0,1,0,0,1,2,0),(34,'Pte Pago',3,0,'WAITING_FOR_PAYMENT',NULL,34,0,0,0,0,0,0,4,1),(35,'Semi-Encajado',9,2,'HALF_PACKED',NULL,10,0,1,0,0,0,0,1,0),(36,'Control Previa',3,1,'PREVIOUS_CONTROL',1,36,0,1,0,4,0,1,3,0); /*!40000 ALTER TABLE `state` ENABLE KEYS */; UNLOCK TABLES; @@ -452,7 +452,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:26 +-- Dump completed on 2022-01-13 7:50:30 USE `cache`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -488,7 +488,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:26 +-- Dump completed on 2022-01-13 7:50:31 USE `hedera`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -554,7 +554,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:28 +-- Dump completed on 2022-01-13 7:50:32 USE `postgresql`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -640,7 +640,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:29 +-- Dump completed on 2022-01-13 7:50:33 USE `sage`; -- MariaDB dump 10.19 Distrib 10.5.12-MariaDB, for debian-linux-gnu (x86_64) -- @@ -696,4 +696,4 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:27:29 +-- Dump completed on 2022-01-13 7:50:33 diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 1d862bdf3..5b463d420 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -5885,212 +5885,6 @@ BEGIN SET s.amountNewBorn = n.amount WHERE n.dated >= vDatedFrom; -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 `salesMonthlyCopy` */; -/*!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 `salesMonthlyCopy`() -BEGIN - DECLARE vPlusNewClient INT DEFAULT 100; - DECLARE vScoreNewClient INT DEFAULT 100; - DECLARE vRowCount INT DEFAULT 1; - DECLARE vMaxRow INT; - - -- COMERCIAL Y EQUIPO - DROP TEMPORARY TABLE IF EXISTS tmp.salesPersons; - CREATE TEMPORARY TABLE tmp.salesPersons - ENGINE = MEMORY - SELECT u.id workerFk, - u.name salesPerson, - d.name team, - u2.name bossFk - FROM vn.department d - JOIN vn.workerDepartment wd ON wd.departmentFk = d.id - JOIN account.user u ON u.id = wd.workerFk - JOIN vn.worker w ON w.id = u.id - JOIN account.user u2 ON u2.id = w.bossFk - WHERE d.name LIKE '%EQUIPO%'; - - -- VENTA, COMISIÓN - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - ENGINE = MEMORY - SELECT YEAR(s.dated) year, - MONTH(s.dated) month, - u.name, - SUM(s.amount) currentSale, - SUM(s.amount)*cc.rate commissionSale, - s.salesPersonFk workerFk, - cc.minimumSalesByQuarter/3 minimumSalesByMonth - FROM - bs.salesByclientSalesPerson s - JOIN vn.client c ON c.id = s.salesPersonFk - JOIN account.user u ON u.id = s.salesPersonFk - JOIN vn.commissionConfig cc - WHERE dated BETWEEN util.firstDayOfMonth(CURDATE()) AND LAST_DAY(CURDATE()) - GROUP BY year, month, workerFk; - - -- OBJETIVO EVALUABLE (GRUPO) Y OBJETIVO INCENTIVO (INDIVIDUAL) - DROP TEMPORARY TABLE IF EXISTS tmp.objectives; - CREATE TEMPORARY TABLE tmp.objectives - ENGINE = MEMORY - SELECT sg.rank, - sg.goal goalGroup, - sg2.goal goalIncentive, - sub.walletWeigth, - sub.walletWeigth*sg2.goal/100 AS incentiveObjective, - sub.walletWeigth*sg.goal/100 AS evaluableObjective, - sub.workerFk, - rb.bonus - FROM ( - SELECT - CASE - WHEN portfolioWeight >= sg1.walletWeightFrom - AND portfolioWeight <= sg1.walletWeightTo THEN 1 - WHEN portfolioWeight >= sg2.walletWeightFrom - AND portfolioWeight <= sg2.walletWeightTo THEN 2 - WHEN portfolioWeight >= sg3.walletWeightFrom - AND portfolioWeight <= sg3.walletWeightTo THEN 3 - WHEN portfolioWeight >= sg4.walletWeightFrom - AND portfolioWeight <= sg4.walletWeightTo THEN 4 - WHEN portfolioWeight >= sg5.walletWeightFrom - AND portfolioWeight <= sg5.walletWeightTo THEN 5 - END rank, - u.id workerFk, - IFNULL(v.portfolioWeight,0) AS walletWeigth - FROM bs.vendedores v - JOIN account.`user` u ON u.id = v.Id_Trabajador - JOIN vn.saleGoal sg1 ON sg1.`rank` = 1 AND sg1.`year` = YEAR(CURDATE()) AND sg1.`month` = MONTH(CURDATE()) - JOIN vn.saleGoal sg2 ON sg2.`rank` = 2 AND sg2.`year` = YEAR(CURDATE()) AND sg2.`month` = MONTH(CURDATE()) - JOIN vn.saleGoal sg3 ON sg3.`rank` = 3 AND sg3.`year` = YEAR(CURDATE()) AND sg3.`month` = MONTH(CURDATE()) - JOIN vn.saleGoal sg4 ON sg4.`rank` = 4 AND sg4.`year` = YEAR(CURDATE()) AND sg4.`month` = MONTH(CURDATE()) - JOIN vn.saleGoal sg5 ON sg5.`rank` = 5 AND sg5.`year` = YEAR(CURDATE()) AND sg5.`month` = MONTH(CURDATE()) - WHERE v.año = YEAR(CURDATE())-1 AND v.mes = MONTH(CURDATE()) - GROUP BY u.id - ) sub - JOIN vn.saleGoal sg ON sg.`rank` = sub.rank AND sg.goalType = 'grupo' AND sg.`year` = YEAR(CURDATE()) AND sg.`month` = MONTH(CURDATE()) - JOIN vn.saleGoal sg2 ON sg2.`rank` = sub.rank AND sg2.goalType = 'individual' AND sg2.`year` = YEAR(CURDATE()) AND sg2.`month` = MONTH(CURDATE()) - JOIN vn.rankBonus rb ON rb.`rank` = sub.`rank`; - - -- PUNTUACIÓN EQUIPO, PLUS OBJETIVO EQUIPO Y PLUS VARIABLE JEFE DE EQUIPO - DROP TEMPORARY TABLE IF EXISTS tmp.scoreTeam; - CREATE TEMPORARY TABLE tmp.scoreTeam - ENGINE = MEMORY - SELECT *, - IF(sub1.scoreTeam >= sub1.minScoreForPlusTeam, sub1.plusTeamValue, 0) plusTeam, - IF(sub1.scoreTeam >= sub1.minScoreForPlusBoss, countSalesPerson * sub1.plusBoss, 0) plusBossTeam - FROM ( - SELECT *, - (100/sub.countSalesPerson)*countGroupAchieved scoreTeam - FROM ( - SELECT COUNT(u.id) countSalesPerson, - u.id workerFk, - u.name salesPerson, - d.name team, - cc.minScoreForPlusTeam, - cc.minScoreForPlusBoss, - cc.plusTeam plusTeamValue, - cc.plusBoss, - s.minimumSalesByMonth, - s.currentSale, - SUM(IF(s.currentSale > r.evaluableObjective, 1, 0)) countGroupAchieved - FROM vn.department d - JOIN vn.workerDepartment wd ON wd.departmentFk = d.id - JOIN account.user u ON u.id = wd.workerFk - JOIN tmp.sale s ON s.workerFk = wd.workerFk - JOIN tmp.objectives r ON r.workerFk = wd.workerFk - JOIN vn.commissionConfig cc - WHERE d.name LIKE '%EQUIPO%' - GROUP BY d.name - ) sub - ) sub1; - - -- PLUS CLIENTES NUEVOS - DROP TEMPORARY TABLE IF EXISTS tmp.newClients; - CREATE TEMPORARY TABLE tmp.newClients ( - id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, - workerFk INTEGER(11), - name VARCHAR(30), - total DECIMAL(10,3), - plusNewClient INTEGER(11), - scoreNewClient INTEGER(11) - ); - - INSERT INTO tmp.newClients (workerFk, total, name, plusNewClient) - SELECT u.id workerFk, u.name, SUM(v.importe) total, vPlusNewClient - FROM bs.clientNewBorn cn - JOIN bs.ventas v ON DATE_ADD(cn.firstShipped, INTERVAL 1 YEAR) > v.fecha AND v.Id_Cliente = cn.clientFk - JOIN vn.client c ON c.id = v.Id_Cliente - JOIN account.user u ON u.id = c.salesPersonFk - JOIN vn.workerDepartment wd ON wd.workerFk = u.id - JOIN vn.department d On d.id = wd.departmentFk - WHERE v.fecha >= util.firstDayOfMonth(CURDATE()) - AND cn.firstShipped >= util.firstDayOfMonth(DATE_ADD(CURDATE(), INTERVAL -1 year)) - AND d.name LIKE 'EQUIPO%' - GROUP BY u.id - ORDER BY total DESC; - - SET vMaxRow = ROW_COUNT(); - - my_loop: LOOP - UPDATE tmp.newClients SET plusNewClient = vPlusNewClient WHERE id = vRowCount; - UPDATE tmp.newClients SET scoreNewClient = vScoreNewClient WHERE id = vRowCount; - - IF (vRowCount <= 20) THEN - SET vPlusNewClient = vPlusNewClient - 5; - ELSE - SET vPlusNewClient = 0; - END IF; - - SET vScoreNewClient = vScoreNewClient - 1; - SET vRowCount = vRowCount + 1; - - IF vRowCount > vMaxRow THEN - LEAVE my_loop; - END IF; - END LOOP my_loop; - - SELECT * - FROM ( - SELECT sp.salesPerson, - sp.team, - s.`year`, - s.`month`, - s.currentSale, - s.commissionSale, - IF(s.currentSale > s.minimumSalesByMonth AND s.currentSale > r.incentiveObjective, r.bonus, 0) plusIndividual, - IF(s.currentSale > s.minimumSalesByMonth, st.plusTeam, 0) plusTeam, - nc.plusNewClient, - IF(sp.bossFk = 'ricar', st.plusBossTeam, 0) plusBossTeam, - st.scoreTeam, - nc.scoreNewClient - FROM tmp.salesPersons sp - LEFT JOIN tmp.sale s ON s.workerFk = sp.workerFk - LEFT JOIN tmp.objectives r ON r.workerFk = sp.workerFk - LEFT JOIN tmp.scoreTeam st ON st.team = sp.team - LEFT JOIN tmp.newClients nc ON nc.workerFk = sp.workerFk - ) sub - ORDER BY salesPerson; - - DROP TEMPORARY TABLE - tmp.salesPersons, - tmp.sale, - tmp.objectives, - tmp.scoreTeam, - tmp.newClients; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -6114,22 +5908,19 @@ BEGIN DECLARE vRowCount INT DEFAULT 1; DECLARE vMaxRow INT; - IF(DAY(CURDATE()) = 5) THEN + IF(DAY(CURDATE()) = 5) THEN -- COMERCIAL Y EQUIPO DROP TEMPORARY TABLE IF EXISTS tmp.salesPersons; CREATE TEMPORARY TABLE tmp.salesPersons ENGINE = MEMORY SELECT u.id workerFk, u.name salesPersonName, - d.name teamName, - u2.name bossFk + d.name teamName FROM vn.department d JOIN vn.workerDepartment wd ON wd.departmentFk = d.id JOIN account.user u ON u.id = wd.workerFk - JOIN vn.worker w ON w.id = u.id - JOIN account.user u2 ON u2.id = w.bossFk WHERE d.name LIKE '%EQUIPO%'; - + -- VENTA, COMISIÓN DROP TEMPORARY TABLE IF EXISTS tmp.sale; CREATE TEMPORARY TABLE tmp.sale @@ -6148,7 +5939,7 @@ BEGIN JOIN vn.commissionConfig cc WHERE dated BETWEEN util.firstDayOfMonth(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND LAST_DAY(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) GROUP BY year, month, workerFk; - + -- OBJETIVO EVALUABLE (GRUPO) Y OBJETIVO INCENTIVO (INDIVIDUAL) DROP TEMPORARY TABLE IF EXISTS tmp.objectives; CREATE TEMPORARY TABLE tmp.objectives @@ -6190,19 +5981,19 @@ BEGIN JOIN vn.saleGoal sg ON sg.`rank` = sub.rank AND sg.goalType = 'grupo' AND sg.`year` = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND sg.`month` = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) JOIN vn.saleGoal sg2 ON sg2.`rank` = sub.rank AND sg2.goalType = 'individual' AND sg2.`year` = YEAR(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) AND sg2.`month` = MONTH(DATE_SUB(CURDATE(), INTERVAL 1 MONTH)) JOIN vn.rankBonus rb ON rb.`rank` = sub.`rank`; - + -- PUNTUACIÓN EQUIPO, PLUS OBJETIVO EQUIPO Y PLUS VARIABLE JEFE DE EQUIPO - DROP TEMPORARY TABLE IF EXISTS tmp.teamScore; - CREATE TEMPORARY TABLE tmp.teamScore + DROP TEMPORARY TABLE IF EXISTS tmp.scoreTeam; + CREATE TEMPORARY TABLE tmp.scoreTeam ENGINE = MEMORY SELECT *, IF(sub1.teamScore >= sub1.minScoreForPlusTeam, sub1.plusTeamValue, 0) teamPlus, - IF(sub1.teamScore >= sub1.minScoreForPlusBoss, IF(sub1.teamName = 'EQUIPO MIRIAM MAR', (sub1.countSalesPerson-2)*sub1.plusBoss, (sub1.countSalesPerson-1)*sub1.plusBoss), 0) teamBossPlus -- se resta 1 pq el jefe de equipo no cuenta + IF(sub1.teamScore >= sub1.minScoreForPlusBoss, countSalesPerson * sub1.plusBoss, 0) teamBossPlus FROM ( SELECT *, (100/sub.countSalesPerson)*countGroupAchieved teamScore FROM ( - SELECT COUNT(u.id) countSalesPerson, + SELECT COUNT(u.id) countSalesPerson, u.id workerFk, u.name salesPersonName, d.name teamName, @@ -6210,8 +6001,6 @@ BEGIN cc.minScoreForPlusBoss, cc.plusTeam plusTeamValue, cc.plusBoss, - s.minimumSalesByMonth, - s.currentSale, SUM(IF(s.currentSale > r.evaluableObjective, 1, 0)) countGroupAchieved FROM vn.department d JOIN vn.workerDepartment wd ON wd.departmentFk = d.id @@ -6223,7 +6012,7 @@ BEGIN GROUP BY d.name ) sub ) sub1; - + -- PLUS CLIENTES NUEVOS DROP TEMPORARY TABLE IF EXISTS tmp.newClients; CREATE TEMPORARY TABLE tmp.newClients ( @@ -6269,26 +6058,26 @@ BEGIN END IF; END LOOP my_loop; - INSERT INTO bs.salesMonthlySnapshot - SELECT * - FROM ( - SELECT sp.salesPersonName, - sp.teamName, - s.`year`, - s.`month`, - s.currentSale, - s.commissionSale, - IF(s.currentSale > s.minimumSalesByMonth AND s.currentSale > r.incentiveObjective, r.bonus, 0) individualPlus, - IF(s.currentSale > s.minimumSalesByMonth, st.teamPlus, 0) teamPlus, - st.teamScore, - nc.newClientPlus, - nc.newClientScore, - IF(sp.bossFk = 'ricar' OR sp.bossFk = 'miriam', IF(sp.salesPersonName = 'miriam' OR sp.salesPersonName = 'mmar', st.teamBossPlus/2, st.teamBossPlus), 0) teamBossPlus -- para que solo tengan teamBossPlus los jefes/ como hay 2 jefes de equipo, el plus se divide - FROM tmp.salesPersons sp - LEFT JOIN tmp.sale s ON s.workerFk = sp.workerFk - LEFT JOIN tmp.objectives r ON r.workerFk = sp.workerFk - LEFT JOIN tmp.teamScore st ON st.teamName = sp.teamName - LEFT JOIN tmp.newClients nc ON nc.workerFk = sp.workerFk + INSERT INTO bs.salesMonthlySnapshot + SELECT * + FROM ( + SELECT sp.salesPersonName, + sp.teamName, + s.`year`, + s.`month`, + s.currentSale, + s.commissionSale, + IF(s.currentSale > s.minimumSalesByMonth AND s.currentSale > r.incentiveObjective, r.bonus, 0) individualPlus, + np.teamPlus, + np.teamScore, + nc.newClientPlus, + nc.newClientScore, + np.teamBossPlus + FROM tmp.salesPersons sp + LEFT JOIN tmp.sale s ON s.workerFk = sp.workerFk + LEFT JOIN tmp.objectives r ON r.workerFk = sp.workerFk + LEFT JOIN tmp.scoreTeam np ON np.teamName = sp.teamName + LEFT JOIN tmp.newClients nc ON nc.workerFk = sp.workerFk ) sub ORDER BY salesPersonName; @@ -6296,9 +6085,10 @@ BEGIN tmp.salesPersons, tmp.sale, tmp.objectives, - tmp.teamScore, + tmp.scoreTeam, tmp.newClients; - END IF; + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -10145,7 +9935,7 @@ CREATE TABLE `supplyResponseLog` ( PRIMARY KEY (`id`), KEY `supplyResponseLog_FK` (`supplyResponseFk`), CONSTRAINT `supplyResponseLog_FK` FOREIGN KEY (`supplyResponseFk`) REFERENCES `supplyResponse` (`ID`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Esta tabla la utiliza la empresa LOGIFLORA. No kkear.'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -10973,9 +10763,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 ;; @@ -10987,10 +10777,10 @@ proc: BEGIN DECLARE vFreeId INT; DECLARE vSupplyResponseFk INT; DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; DECLARE cur1 CURSOR FOR SELECT id @@ -11041,21 +10831,13 @@ proc: BEGIN DROP TEMPORARY TABLE IF EXISTS tmp; CREATE TEMPORARY TABLE tmp (INDEX (`Item_ArticleCode`)) ENGINE = MEMORY - SELECT t.*, - IFNULL(idt.itemTypeFk, igo.itemTypeFk) itemTypeFk, - igo.expenseFk , - igo.intrastatFk , - igo.originFk + SELECT t.* FROM ( SELECT * FROM edi.supplyOffer ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, NumberOfUnits DESC) t - JOIN edi.item_groupToOffer igo ON igo.group_code = t.group_id - LEFT JOIN edi.item_defaultType idt ON idt.item_id = t.Item_ArticleCode GROUP BY t.srId ; - - -- select now(),'Antes de crear edi.offer'; DROP TEMPORARY TABLE IF EXISTS edi.offer; CREATE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), @@ -11470,9 +11252,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 ;; @@ -11484,10 +11266,10 @@ proc: BEGIN DECLARE vFreeId INT; DECLARE vSupplyResponseFk INT; DECLARE vLastInserted DATETIME; - DECLARE vIsAuctionDay BOOLEAN; - DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; DECLARE vStartingTime DATETIME; - DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; DECLARE cur1 CURSOR FOR SELECT id @@ -11538,21 +11320,12 @@ proc: BEGIN DROP TEMPORARY TABLE IF EXISTS tmp; CREATE TEMPORARY TABLE tmp (INDEX (`Item_ArticleCode`)) ENGINE = MEMORY - SELECT t.*, - IFNULL(idt.itemTypeFk, igo.itemTypeFk) itemTypeFk, - igo.expenseFk , - igo.intrastatFk , - igo.originFk + SELECT t.* FROM ( SELECT * FROM edi.supplyOffer ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, NumberOfUnits DESC) t - JOIN edi.item_groupToOffer igo ON igo.group_code = t.group_id - LEFT JOIN edi.item_defaultType idt ON idt.item_id = t.Item_ArticleCode - GROUP BY t.srId - ; - - -- select now(),'Antes de crear edi.offer'; + GROUP BY t.srId; DROP TEMPORARY TABLE IF EXISTS edi.offer; CREATE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), @@ -11613,8 +11386,6 @@ proc: BEGIN START TRANSACTION; - CALL util.debugAdd('edi.floramondo_offerRefresh_BETA',CONCAT('offerItems:' ,(SELECT COUNT(*) FROM edi.offer))); - -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos UPDATE IGNORE edi.offer o JOIN vn.item i @@ -11848,10 +11619,7 @@ proc: BEGIN UPDATE edi.warehouseFloramondo SET entryFk = vn.floramondo_getEntry(TIMESTAMPADD(DAY,travellingDays,vLanded), warehouseFk); - CALL util.debugAdd('edi.floramondo_offerRefresh_BETA',CONCAT('offerItems:' ,(SELECT COUNT(*) FROM edi.offer))); - - CALL util.debugAdd('edi.floramondo_offerRefresh_BETA',CONCAT('vLanded:' ,vLanded)); - + IF vLanded IS NOT NULL THEN -- actualiza la oferta existente UPDATE vn.buy b @@ -11862,7 +11630,6 @@ proc: BEGIN b.buyingValue = o.price WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask OR b.buyingValue <> o.price); - -- Se eliminan las ofertas ya incluidas en las entradas DELETE o FROM edi.offer o @@ -11919,6 +11686,7 @@ proc: BEGIN JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk JOIN vn.warehouse w ON w.id = wf.warehouseFk WHERE w.name = 'VNH' + AND b.quantity > 0 GROUP BY sr.vmpID) sub ON o.supplier = sub.name SET o.vnh = sub.total; @@ -11931,18 +11699,17 @@ proc: BEGIN JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk JOIN vn.warehouse w ON w.id = wf.warehouseFk WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 GROUP BY sr.vmpID) sub ON o.supplier = sub.name SET o.algemesi = sub.total; - CALL util.debugAdd('edi.floramondo_offerRefresh_BETA',CONCAT('offerItems:' ,(SELECT COUNT(*) FROM edi.offer))); - END IF; - /* + DROP TEMPORARY TABLE edi.offer, itemToInsert; - */ + DROP TABLE tmp.item; COMMIT; @@ -11961,7 +11728,496 @@ proc: BEGIN INSERT INTO edi.log(tableName, fieldName,fieldValue) VALUES('floramondo_offerRefresh','Tiempo de proceso',TIMEDIFF(NOW(),vStartingTime)); - SELECT * FROM util.debug WHERE variable = 'edi.floramondo_offerRefresh_BETA' ORDER BY id desc; + + +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 `floramondo_offerRefresh_beta2` */; +/*!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 `floramondo_offerRefresh_beta2`() +proc: BEGIN + + DECLARE vLanded DATETIME; + DECLARE done INT DEFAULT FALSE; + DECLARE vFreeId INT; + DECLARE vSupplyResponseFk INT; + DECLARE vLastInserted DATETIME; + DECLARE vIsAuctionDay BOOLEAN; + DECLARE vMaxNewItems INT DEFAULT 10000; + DECLARE vStartingTime DATETIME; + DECLARE vAalsmeerMarketPlaceID VARCHAR(13) DEFAULT '8713783439043'; + + DECLARE cur1 CURSOR FOR + SELECT id + FROM edi.item_free; + + DECLARE cur2 CURSOR FOR + SELECT srId + FROM itemToInsert; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + DECLARE EXIT HANDLER FOR SQLSTATE '45000' + BEGIN + ROLLBACK; + RESIGNAL; + END; + + SET vStartingTime = NOW(); + + TRUNCATE edi.offerList ; + + INSERT INTO edi.offerList(supplier, total) + SELECT v.name, COUNT(DISTINCT sr.ID) total + FROM edi.supplyResponse sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + WHERE sr.NumberOfUnits > 0 + AND sr.EmbalageCode != 999 + GROUP BY sr.vmpID; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(*) total + FROM edi.supplyOffer sr + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.`filter` = sub.total; + + -- Refresca las fotos de los items existentes, con prioridad baja (0.7 seg) + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url,priority) + SELECT i.id, sr.PictureReference , 100 + FROM edi.supplyResponse sr + JOIN vn.item i ON i.supplyResponseFk = sr.ID + WHERE i.image != edi.imageName(sr.PictureReference) + AND sr.NumberOfUnits > 0; + + -- Elimina de la lista de items libres aquellos que ya existen + DELETE itf.* + FROM edi.item_free itf + JOIN vn.item i ON i.id = itf.id; + + DROP TEMPORARY TABLE IF EXISTS tmp; + CREATE TEMPORARY TABLE tmp (INDEX (`Item_ArticleCode`)) ENGINE = MEMORY + SELECT t.* + FROM ( + SELECT * + FROM edi.supplyOffer + ORDER BY (MarketPlaceID = vAalsmeerMarketPlaceID) DESC, NumberOfUnits DESC) t + GROUP BY t.srId + ; + + DROP TEMPORARY TABLE IF EXISTS edi.offer; + CREATE TEMPORARY TABLE edi.offer (INDEX (`srID`), INDEX (`EmbalageCode`), + INDEX (`ef1`), INDEX (`ef2`), INDEX (`ef3`), INDEX (`ef4`),INDEX (`ef5`), INDEX (`ef6`), + INDEX (`s1Value`), INDEX (`s2Value`), INDEX (`s3Value`), INDEX (`s4Value`),INDEX (`s5Value`), INDEX (`s6Value`)) + ENGINE = MEMORY + SELECT so.*, + ev1.type_description s1Value, + ev2.type_description s2Value, + ev3.type_description s3Value, + ev4.type_description s4Value, + ev5.type_description s5Value, + ev6.type_description s6Value, + eif1.feature ef1, + eif2.feature ef2, + eif3.feature ef3, + eif4.feature ef4, + eif5.feature ef5, + eif6.feature ef6 + FROM tmp so + LEFT JOIN edi.item_feature eif1 ON eif1.item_id = so.Item_ArticleCode + AND eif1.presentation_order = 1 AND eif1.expiry_date IS NULL + LEFT JOIN edi.item_feature eif2 ON eif2.item_id = so.Item_ArticleCode + AND eif2.presentation_order = 2 AND eif2.expiry_date IS NULL + LEFT JOIN edi.item_feature eif3 ON eif3.item_id = so.Item_ArticleCode + AND eif3.presentation_order = 3 AND eif3.expiry_date IS NULL + LEFT JOIN edi.item_feature eif4 ON eif4.item_id = so.Item_ArticleCode + AND eif4.presentation_order = 4 AND eif4.expiry_date IS NULL + LEFT JOIN edi.item_feature eif5 ON eif5.item_id = so.Item_ArticleCode + AND eif5.presentation_order = 5 AND eif5.expiry_date IS NULL + LEFT JOIN edi.item_feature eif6 ON eif6.item_id = so.Item_ArticleCode + AND eif6.presentation_order = 6 AND eif6.expiry_date IS NULL + LEFT JOIN edi.`value` ev1 ON ev1.type_id = eif1.feature AND so.s1 = ev1.type_value + LEFT JOIN edi.`value` ev2 ON ev2.type_id = eif2.feature AND so.s2 = ev2.type_value + LEFT JOIN edi.`value` ev3 ON ev3.type_id = eif3.feature AND so.s3 = ev3.type_value + LEFT JOIN edi.`value` ev4 ON ev4.type_id = eif4.feature AND so.s4 = ev4.type_value + LEFT JOIN edi.`value` ev5 ON ev5.type_id = eif5.feature AND so.s5 = ev5.type_value + LEFT JOIN edi.`value` ev6 ON ev6.type_id = eif6.feature AND so.s6 = ev6.type_value + ORDER BY Price; + + DROP TEMPORARY TABLE tmp; + + DELETE o + FROM edi.offer o + LEFT JOIN vn.tag t1 ON t1.ediTypeFk = o.ef1 AND t1.overwrite = 'size' + LEFT JOIN vn.tag t2 ON t2.ediTypeFk = o.ef2 AND t2.overwrite = 'size' + LEFT JOIN vn.tag t3 ON t3.ediTypeFk = o.ef3 AND t3.overwrite = 'size' + LEFT JOIN vn.tag t4 ON t4.ediTypeFk = o.ef4 AND t4.overwrite = 'size' + LEFT JOIN vn.tag t5 ON t5.ediTypeFk = o.ef5 AND t5.overwrite = 'size' + LEFT JOIN vn.tag t6 ON t6.ediTypeFk = o.ef6 AND t6.overwrite = 'size' + JOIN vn.floramondoConfig fc ON TRUE + WHERE (t1.id IS NOT NULL AND CONVERT(s1Value, UNSIGNED) > fc.itemMaxSize) + OR(t2.id IS NOT NULL AND CONVERT(s2Value, UNSIGNED) > fc.itemMaxSize) + OR(t3.id IS NOT NULL AND CONVERT(s3Value, UNSIGNED) > fc.itemMaxSize) + OR(t4.id IS NOT NULL AND CONVERT(s4Value, UNSIGNED) > fc.itemMaxSize) + OR(t5.id IS NOT NULL AND CONVERT(s5Value, UNSIGNED) > fc.itemMaxSize) + OR(t6.id IS NOT NULL AND CONVERT(s6Value, UNSIGNED) > fc.itemMaxSize); + + START TRANSACTION; + + -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos + UPDATE IGNORE edi.offer o + JOIN vn.item i + ON i.name = o.product_name + AND i.subname <=> o.company_name + AND i.value5 <=> o.s1Value + AND i.value6 <=> o.s2Value + AND i.value7 <=> o.s3Value + AND i.value8 <=> o.s4Value + AND i.value9 <=> o.s5Value + AND i.value10 <=> o.s6Value + AND i.NumberOfItemsPerCask <=> o.NumberOfItemsPerCask + AND i.EmbalageCode <=> o.EmbalageCode + AND i.quality <=> o.Quality + JOIN vn.itemType it ON it.id = i.typeFk + LEFT JOIN vn.sale s ON s.itemFk = i.id + LEFT JOIN vn.ticket t ON t.id = s.ticketFk AND t.shipped > TIMESTAMPADD(WEEK, -1, CURDATE()) + LEFT JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + LEFT JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + LEFT JOIN edi.putOrder po ON po.supplyResponseID = i.supplyResponseFk AND po.OrderTradeLineDateTime > TIMESTAMPADD(WEEK, -1, CURDATE()) + SET i.supplyResponseFk = o.srID + WHERE ( sr.ID IS NULL + OR sr.NumberOfUnits = 0 + OR di.LatestOrderDateTime < NOW() + OR di.ID IS NULL) + AND it.isInventory + AND t.id IS NULL + AND po.id IS NULL; + -- select now(),'Antes de crear ITO'; + DROP TEMPORARY TABLE IF EXISTS itemToInsert; + CREATE TEMPORARY TABLE itemToInsert ENGINE = MEMORY + SELECT o.*, CAST(NULL AS DECIMAL(6,0)) as itemFk + FROM edi.offer o + LEFT JOIN vn.item i ON i.supplyResponseFk = o.srId + WHERE i.id IS NULL + LIMIT vMaxNewItems; + + -- Reciclado de nº de item + OPEN cur1; + OPEN cur2; + + read_loop: LOOP + + FETCH cur2 INTO vSupplyResponseFk; + FETCH cur1 INTO vFreeId; + + IF done THEN + LEAVE read_loop; + END IF; + + UPDATE itemToInsert + SET itemFk = vFreeId + WHERE srId = vSupplyResponseFk; + + END LOOP; + + CLOSE cur1; + CLOSE cur2; + + -- Insertamos todos los items en Articles de la oferta + INSERT INTO vn.item( id, + `name`, + longName, + subName, + expenceFk, + typeFk, + intrastatFk, + originFk, + supplyResponseFk, + numberOfItemsPerCask, + embalageCode, + quality, + isFloramondo) + SELECT iti.itemFk, + iti.product_name, + iti.product_name, + iti.company_name, + iti.expenseFk, + iti.itemTypeFk, + iti.intrastatFk, + iti.originFk, + iti.`srId`, + iti.NumberOfItemsPerCask, + iti.EmbalageCode, + iti.Quality, + TRUE + FROM itemToInsert iti; + + INSERT IGNORE INTO vn.itemImageQueue(itemFk, url) + SELECT i.id, PictureReference + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.srId + WHERE PictureReference IS NOT NULL; + + INSERT INTO edi.log(tableName, fieldName,fieldValue) + SELECT 'itemImageQueue','NumImagenesPtes', COUNT(*) + FROM vn.itemImageQueue + WHERE attempts = 0; + + -- Inserta si se añadiesen tags nuevos + INSERT IGNORE INTO vn.tag (name, ediTypeFk) + SELECT description, type_id FROM edi.type; + + -- Inserta los tags sólo en los articulos nuevos + + -- desabilita el trigger para recalcular los tags al final + SET @isTriggerDisabled = TRUE; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.product_name, 1 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Producto' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId`; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.Quality, 3 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Calidad' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId`; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , ii.company_name, 4 + FROM itemToInsert ii + JOIN vn.tag t ON t.`name` = 'Productor' + JOIN vn.item i ON i.supplyResponseFk = ii.`srId`; + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s1Value, 5 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef1 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ISNULL(s1Value); + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s2Value, 6 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef2 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ISNULL(s2Value); + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s3Value, 7 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef3 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ISNULL(s3Value); + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s4Value, 8 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef4 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ISNULL(s4Value); + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s5Value, 9 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef5 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ISNULL(s5Value); + + INSERT INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id , s6Value, 10 + FROM itemToInsert ii + JOIN vn.tag t ON t.ediTypeFk = ii.ef6 + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + WHERE NOT ISNULL(s6Value); + + INSERT IGNORE INTO vn.itemTag(itemFk, tagFk, value, priority) + SELECT i.id, t.id, IFNULL(ink.name, ik.color), 11 + FROM itemToInsert ii + JOIN vn.item i ON i.supplyResponseFk = ii.`srId` + JOIN vn.tag t ON t.`name` = 'Color' + LEFT JOIN edi.feature f ON f.item_id = ii.Item_ArticleCode + LEFT JOIN edi.`type` tp ON tp.type_id = f.feature_type_id AND tp.`description` = 'Hoofdkleur 1' + LEFT JOIN vn.ink ON ink.dutchCode = f.feature_value + LEFT JOIN vn.itemInk ik ON ik.longName = i.longName + WHERE ink.name IS NOT NULL + OR ik.color IS NOT NULL; + + UPDATE vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId` + JOIN vn.packaging p ON p.id LIKE ii.EmbalageCode AND hasCompressionVariations + JOIN vn.itemTag diameter ON diameter.itemFk = i.id + JOIN vn.tag tDiameter ON tDiameter.overwrite = 'diameter' AND tDiameter.id = diameter.tagFk + JOIN vn.itemTag size ON size.itemFk = i.id + JOIN vn.tag tSize ON tSize.overwrite = 'size' AND tSize.id = size.tagFk + SET i.`compression` = + (PI() * POW(diameter.`value`/ 2, 2) * size.`value`) + / + ((p.width * p.depth * p.height) / ii.NumberOfItemsPerCask); + + DROP TABLE IF EXISTS tmp.item; + CREATE TABLE tmp.item + (PRIMARY KEY (id)) + SELECT i.id FROM vn.item i + JOIN itemToInsert ii ON i.supplyResponseFk = ii.`srId`; + + CALL vn.item_refreshTags(); + + SET @isTriggerDisabled = FALSE; + + SELECT MIN(LatestDeliveryDateTime) INTO vLanded + FROM edi.supplyResponse sr + JOIN edi.deliveryInformation di ON di.supplyResponseID = sr.ID + JOIN edi.marketPlace mp ON mp.id = sr.MarketPlaceID + JOIN vn.floramondoConfig fc + WHERE mp.isLatestOrderDateTimeRelevant + AND di.LatestOrderDateTime > IF(fc.MaxLatestOrderHour > HOUR(NOW()), CURDATE(), TIMESTAMPADD(DAY,1,CURDATE())); + + UPDATE vn.floramondoConfig + SET nextLanded = vLanded + WHERE vLanded IS NOT NULL; + + -- Elimina la oferta obsoleta + UPDATE vn.buy b + JOIN vn.entry e ON e.id = b.entryFk + JOIN vn.travel tr ON tr.id = e.travelFk + JOIN vn.agencyMode am ON am.id = tr.agencyFk + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.supplyResponse sr ON i.supplyResponseFk = sr.ID + LEFT JOIN edi.deliveryInformation di ON di.ID = b.deliveryFk + SET b.quantity = 0 + WHERE (IFNULL(di.LatestOrderDateTime,NOW()) <= NOW() + OR i.supplyResponseFk IS NULL + OR sr.NumberOfUnits = 0) + AND am.name = 'LOGIFLORA' + AND e.isRaid; + + -- Localiza las entradas de cada almacen + UPDATE edi.warehouseFloramondo + SET entryFk = vn.floramondo_getEntry(TIMESTAMPADD(DAY,travellingDays,vLanded), warehouseFk); + + + IF vLanded IS NOT NULL THEN + -- actualiza la oferta existente + UPDATE vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = o.NumberOfUnits * o.NumberOfItemsPerCask, + b.buyingValue = o.price + WHERE (b.quantity <> o.NumberOfUnits * o.NumberOfItemsPerCask OR b.buyingValue <> o.price); + + -- Se eliminan las ofertas ya incluidas en las entradas + DELETE o + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN vn.buy b ON i.id = b.itemFk + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk; + + -- Se inserta el resto + SET vLastInserted := NOW(); + + -- Inserta la oferta + INSERT INTO vn.buy(entryFk, + itemFk, + quantity, + buyingValue, + stickers, + packing, + `grouping`, + groupingMode, + packageFk, + deliveryFk) + + SELECT wf.entryFk, + i.id, + o.NumberOfUnits * o.NumberOfItemsPerCask as quantity, + o.Price, + o.NumberOfUnits as etiquetas, + o.NumberOfItemsPerCask as packing, + GREATEST(1, IFNULL(o.MinimumQuantity,0)) * o.NumberOfItemsPerCask as `grouping`, + 2, -- Obliga al Packing + o.embalageCode, + o.diId + FROM edi.offer o + JOIN vn.item i ON i.supplyResponseFk = o.srId + JOIN edi.warehouseFloramondo wf + JOIN vn.packaging p ON p.id LIKE o.embalageCode; -- llevar esta linea i mirar de crear els packages a temps real + + DROP TEMPORARY TABLE IF EXISTS tmp.buyRecalc; + + CREATE TEMPORARY TABLE tmp.buyRecalc + SELECT b.id + FROM vn.buy b + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + WHERE b.created >= vLastInserted; + + CALL vn.buy_recalcPrices(); + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'VNH' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.vnh = sub.total; + + UPDATE edi.offerList o + JOIN (SELECT v.name, COUNT(DISTINCT b.itemFk) total + FROM vn.buy b + JOIN vn.item i ON i.id = b.itemFk + JOIN edi.supplyResponse sr ON sr.ID = i.supplyResponseFk + JOIN edi.VMPSettings v ON v.VMPID = sr.vmpID + JOIN edi.warehouseFloramondo wf ON wf.entryFk = b.entryFk + JOIN vn.warehouse w ON w.id = wf.warehouseFk + WHERE w.name = 'ALGEMESI' + AND b.quantity > 0 + GROUP BY sr.vmpID) sub ON o.supplier = sub.name + SET o.algemesi = sub.total; + + + END IF; + + DROP TEMPORARY TABLE + edi.offer, + itemToInsert; + + DROP TABLE tmp.item; + + COMMIT; + + -- Esto habria que pasarlo a procesos programados o trabajar con tags y dejar las familias + UPDATE vn.item i + SET typeFk = 121 + WHERE i.longName LIKE 'Rosa Garden %' + AND typeFk = 17; + + UPDATE vn.item i + SET typeFk = 156 + WHERE i.longName LIKE 'Rosa ec %' + AND typeFk = 17; + + INSERT INTO edi.log(tableName, fieldName,fieldValue) + VALUES('floramondo_offerRefresh','Tiempo de proceso',TIMEDIFF(NOW(),vStartingTime)); + + END ;; DELIMITER ; @@ -12468,17 +12724,17 @@ 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 `orderLog` */; +/*!50003 DROP PROCEDURE IF EXISTS `orderLog__` */; /*!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 `orderLog`(vItemFk INT) +CREATE DEFINER=`root`@`%` PROCEDURE `orderLog__`(vItemFk INT) BEGIN DECLARE vSupplyResponseFk INT; @@ -18492,6 +18748,36 @@ 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 `sip_getExtension` */; +/*!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 `sip_getExtension`(vUserId INT(10)) +BEGIN + + /* + * Devuelve la extensión pbx del usuario + * + * @param vUserId Id del usuario + * + */ + + SELECT extension + FROM sip s + WHERE s.user_id = vUserId; + +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 `sip_isValid` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -19487,13 +19773,13 @@ CREATE TABLE `TiposTransacciones` ( /*!40101 SET character_set_client = @saved_cs_client */; -- --- Table structure for table `XDiario_movConta_IVA` +-- Table structure for table `XDiario_movConta_IVA__` -- -DROP TABLE IF EXISTS `XDiario_movConta_IVA`; +DROP TABLE IF EXISTS `XDiario_movConta_IVA__`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; -CREATE TABLE `XDiario_movConta_IVA` ( +CREATE TABLE `XDiario_movConta_IVA__` ( `id` int(11) NOT NULL, `CodigoDivisa` varchar(3) COLLATE utf8_unicode_ci NOT NULL, `BaseIva1` double DEFAULT NULL, @@ -19920,7 +20206,8 @@ BEGIN * @vYear Año contable del que se quiere trasladar la información * @vCompanyFk Empresa de la que se quiere trasladar datos */ - DECLARE vDated DATE; + DECLARE vDatedFrom DATETIME; + DECLARE vDatedTo DATETIME; DECLARE vDuaTransactionFk INT; DECLARE vTaxImportFk INT; DECLARE vTaxImportReducedFk INT; @@ -19929,6 +20216,7 @@ BEGIN DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; DECLARE vInvoiceTypeInformativeCode VARCHAR(1); DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2) ; + DECLARE vBookEntries TEXT; SELECT SiglaNacion INTO vCountryCanariasCode FROM Naciones @@ -19961,7 +20249,8 @@ BEGIN SELECT codeSage INTO vInvoiceTypeInformativeCode FROM invoiceType WHERE code ='informative'; - SELECT CAST(CONCAT(vYear, '-01-01') AS DATE) INTO vDated; + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) + INTO vDatedFrom, vDatedTo; TRUNCATE movContaIVA; @@ -20164,7 +20453,7 @@ BEGIN )sub3 ON sub3.account = x.SUBCTA WHERE x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk - AND x.FECHA >= vDated; + AND x.FECHA BETWEEN vDatedFrom AND vDatedTo; -- Metálicos UPDATE movConta m @@ -20287,13 +20576,50 @@ BEGIN AND importeDivisa > 0 AND ImporteAsiento < 0; + -- Comprobación que los importes e ivas sean correctos, avisa vía CAU + SELECT GROUP_CONCAT(Asiento ORDER BY Asiento ASC SEPARATOR ' \n\r') INTO vBookEntries + FROM(SELECT sub.Asiento + FROM (SELECT mc.Asiento, SUM(mc.ImporteAsiento) amount + FROM movConta mc + WHERE mc.enlazadoSage = FALSE + GROUP BY mc.Asiento)sub + JOIN (SELECT x.ASIEN, SUM(IFNULL(x.EURODEBE,0) + IFNULL(x.EUROHABER,0)) amount + FROM vn.XDiario x + WHERE x.enlazadoSage = FALSE + GROUP BY ASIEN)sub2 ON sub2.ASIEN = sub.Asiento + WHERE sub.amount <> sub2.amount + UNION ALL + SELECT sub.Asiento + FROM (SELECT Asiento, SUM(BaseIva1 + BaseIva2 + BaseIva3 + BaseIva4) amountTaxableBase + FROM movConta + WHERE TipoFactura <> 'I' + AND enlazadoSage = FALSE + GROUP BY Asiento) sub + JOIN (SELECT ASIEN, SUM(BASEEURO) amountTaxableBase + FROM (SELECT ASIEN, SUM(BASEEURO) BASEEURO + FROM vn.XDiario + WHERE FACTURA + AND auxiliar <> '*' + AND enlazadoSage = FALSE + GROUP BY FACTURA, ASIEN)sub3 + GROUP BY ASIEN) sub2 ON sub2.ASIEN = sub.Asiento + WHERE sub.amountTaxableBase<>sub2.amountTaxableBase + AND sub.amountTaxableBase/2 <> sub2.amountTaxableBase) sub; + + IF vBookEntries IS NOT NULL THEN + CALL vn.mail_insert('cau@verdnatura.es, administracion@verdnatura.es', + 'noreply@verdnatura.es', + CONCAT('Asientos contables importados incorrectamente'), + CONCAT('

Existen asientos que difieren entre la info. de XDiario y la que se ha importado a Sage.

+ Asientos nº ', vBookEntries, '
')); + 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 `clientesProveedoresAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `clientesProveedoresAdd__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -20303,7 +20629,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `clientesProveedoresAdd`() +CREATE DEFINER=`root`@`%` PROCEDURE `clientesProveedoresAdd__`() BEGIN TRUNCATE TABLE clientesProveedores; INSERT INTO clientesProveedores @@ -20443,6 +20769,146 @@ BEGIN TRUNCATE TABLE clientesProveedores; + INSERT INTO clientesProveedores + (CodigoEmpresa, + ClienteOProveedor, + CodigoClienteProveedor, + RazonSocial, + Nombre, + Domicilio, + CodigoCuenta, + CifDni, + CifEuropeo, + CodigoPostal, + Municipio, + CodigoProvincia, + Provincia, + CodigoNacion, + SiglaNacion, + PersonaFisicaJuridica, + TipoDocumentoPersona, + CodigoIva, + Nacion, + Telefono, + Telefono2, + CodigoTransaccion, + CodigoRetencion, + Email1, + iban) + SELECT + IF (@@hostname = 'db', co.companyCode, co.companyCodeTest), + 'C', + c.id, + c.socialName, + c.socialName, + IFNULL(c.street, ''), + c.accountingAccount, + TRIM(IF(cu.code = LEFT(c.fi, 2), MID(c.fi, 3, LENGTH(c.fi)-1), c.fi)), + IF(n.NacionCEE,TRIM(IF(cu.code = LEFT(c.fi, 2), c.fi, CONCAT(cu.code,c.fi))) , ''), + IFNULL(c.postcode, ''), + IFNULL(c.city, ''), + IFNULL(pr.CodigoProvincia, ''), + IFNULL(p.name, ''), + IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8_general_ci, IF(@isCeutaMelilla := IF(pr.Provincia IN ('CEUTA', 'MELILLA'), TRUE, FALSE), vCountryCeutaMelillaFk, IF (@isCanarias, vCountryCanariasCode, n.CodigoNacion)), n.CodigoNacion), + IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8_general_ci, IF(@isCeutaMelilla, vCountryCeutaMelillaCode, IF (@isCanarias, vCountryCanariasCode, n.SiglaNacion)), n.SiglaNacion), + IF((c.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F'), + IF(cu.code IN('ES','EX'), + 1, + IF((cu.isUeeMember AND c.isVies), 2, 4)), + IFNULL(c.taxTypeSageFk,0), + IF(n.SiglaNacion = vCountryCanariasCode COLLATE utf8_general_ci, + IF(@isCeutaMelilla, 'CEUTA Y MELILLA', IF (@isCanarias, 'ISLAS CANARIAS', n.Nacion)), + n.Nacion), + IFNULL(c.phone, ''), + IFNULL(c.mobile, ''), + IFNULL(c.transactionTypeSageFk, 0), + '0', + IFNULL(SUBSTR(c.email, 1, LOCATE(',', CONCAT(c.email, ','))-1), ''), + IFNULL(c.iban, '') + FROM vn.`client` c + JOIN clientLastTwoMonths clm ON clm.clientFk = c.id + JOIN vn.company co ON co.id = clm.companyFk + LEFT JOIN vn.country cu ON cu.id = c.countryFk + LEFT JOIN Naciones n ON n.countryFk = cu.id + LEFT JOIN vn.province p ON p.id = c.provinceFk + LEFT JOIN Provincias pr ON pr.provinceFk = p.id + WHERE c.isRelevant + AND co.id = vCompanyFk + UNION ALL + SELECT IF (@@hostname = 'db', c.companyCode, companyCodeTest), + 'P', + s.id, + s.name, + s.name, + IFNULL(s.street, ''), + s.account, + TRIM(IF(co.code = LEFT(s.nif, 2), MID(s.nif, 3, LENGTH(s.nif) - 1), s.nif)), + IF(n.NacionCEE, TRIM(CONCAT(co.code, IF(co.code = LEFT(s.nif, 2), MID(s.nif, 3, LENGTH(s.nif) - 1), s.nif))), ''), + IFNULL(s.postCode,''), + IFNULL(s.city, ''), + IFNULL(pr.CodigoProvincia, ''), + IFNULL(p.name, ''), + n.CodigoNacion, + n.SiglaNacion COLLATE utf8_general_ci, + IF((s.nif REGEXP '^([[:blank:]]|[[:digit:]])'),'J','F'), + IF(co.country IN ('España', 'España exento'), 1,IF(co.isUeeMember = 1, 2, 4)), + IFNULL(s.taxTypeSageFk, 0), + n.Nacion, + IFNULL(con.Telefono, ''), + IFNULL(con.Movil, ''), + IFNULL(s.transactionTypeSageFk, 0), + IFNULL(s.withholdingSageFk, '0'), + IFNULL(SUBSTR(con.email, 1, (COALESCE(NULLIF(LOCATE(',', con.email), 0), 99) - 1)), ''), + IFNULL(iban, '') + FROM vn.supplier s + JOIN providerLastThreeMonths pl ON pl.supplierFk = s.id + LEFT JOIN vn.country co ON co.id = s.countryFk + LEFT JOIN Naciones n ON n.countryFk = co.id + LEFT JOIN vn.province p ON p.id = s.provinceFk + LEFT JOIN Provincias pr ON pr.provinceFk = p.id + LEFT JOIN vn2008.Relaciones r ON r.Id_Proveedor = s.id + LEFT JOIN vn.supplierAccount sa ON sa.supplierFk = s.id + LEFT JOIN vn2008.Contactos con ON con.Id_Contacto = r.Id_Contacto + JOIN vn.company c ON c.id = pl.companyFk + WHERE c.id = vCompanyFk AND + s.isActive AND + s.nif <> '' + GROUP BY pl.supplierFk, pl.companyFk; +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 `clientSupplier_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 `clientSupplier_add__`(vCompanyFk INT) +BEGIN +/** + * Prepara los datos de clientes y proveedores para exportarlos a Sage + * @vCompanyFk Empresa dela que se quiere trasladar datos + */ + DECLARE vCountryCeutaMelillaFk INT; + DECLARE vCountryCanariasCode, vCountryCeutaMelillaCode VARCHAR(2); + + SELECT SiglaNacion INTO vCountryCanariasCode + FROM Naciones + WHERE Nacion ='ISLAS CANARIAS'; + + SELECT CodigoNacion, SiglaNacion INTO vCountryCeutaMelillaFk, vCountryCeutaMelillaCode + FROM Naciones + WHERE Nacion ='CEUTA Y MELILLA'; + + TRUNCATE TABLE clientesProveedores; + INSERT INTO clientesProveedores (CodigoEmpresa, ClienteOProveedor, @@ -20774,7 +21240,8 @@ BEGIN DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vXDiarioFk INT; - DECLARE vDated DATE; + DECLARE vDatedFrom DATETIME; + DECLARE vDatedTo DATETIME; DECLARE vSerialDua VARCHAR(1) DEFAULT 'D'; DECLARE vAccountVNL VARCHAR(10); DECLARE vAccountTaxOutstanding VARCHAR(10); @@ -20789,13 +21256,15 @@ BEGIN LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id WHERE(it.taxTypeSageFk IS NOT NULL OR x.SERIE = vSerialDua COLLATE utf8_general_ci) AND x.enlazadoSage = FALSE - AND x.FECHA >= vDated + AND x.FECHA BETWEEN vDatedFrom AND vDatedTo AND x.empresa_id = vCompanyFk ) sub ON sub.ASIEN = x.ASIEN WHERE x.CLAVE IS NOT NULL; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - SELECT CAST(CONCAT(vYear, '-01-01') AS DATE) INTO vDated; + + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) + INTO vDatedFrom, vDatedTo; SELECT accountingAccount INTO vAccountVNL FROM vn.`client` @@ -20817,7 +21286,7 @@ BEGIN FROM vn.XDiario x WHERE x.enlazadoSage = FALSE AND x.SUBCTA = vAccountTaxOutstanding COLLATE utf8_general_ci - AND x.FECHA >= vDated + AND x.FECHA BETWEEN vDatedFrom AND vDatedTo )sub ON sub.ASIEN = x.ASIEN WHERE NOT x.CONTRA <=> vAccountVNL; @@ -20833,7 +21302,7 @@ BEGIN IF(c.code = 'EUR', '',c.`code`) currencyFk FROM vn.invoiceIn i JOIN vn.currency c ON c.id = i.currencyFk - WHERE i.bookEntried >= vDated + WHERE i.bookEntried BETWEEN vDatedFrom AND vDatedTo UNION ALL SELECT d.id, d.code, @@ -20946,7 +21415,7 @@ BEGIN WHERE SUBCTA LIKE '472%' AND x.enlazadoSage = FALSE AND x.empresa_id = vCompanyFk - AND x.FECHA >= vDated + AND x.FECHA BETWEEN vDatedFrom AND vDatedTo ) sub ON sub.ASIEN = x.ASIEN WHERE x.SUBCTA LIKE '477%' )sub2 ON sub2.ASIEN = x.ASIEN @@ -21257,7 +21726,8 @@ BEGIN DECLARE vDone BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; DECLARE vXDiarioFk INT; - DECLARE vDated DATE; + DECLARE vDatedFrom DATETIME; + DECLARE vDatedTo DATETIME; DECLARE vCursor CURSOR FOR SELECT i.id, @@ -21270,15 +21740,16 @@ BEGIN WHERE x.enlazadoSage = FALSE AND x.FACTURA AND x.empresa_id = vCompanyFk - AND x.FECHA >= vDated + AND x.FECHA BETWEEN vDatedFrom AND vDatedTo GROUP BY refFk ) sub ON sub.ASIEN = x.ASIEN GROUP BY refFk )sub2 ON sub2.refFk = i.ref; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - SELECT CAST(CONCAT(vYear, '-01-01') AS DATE) INTO vDated; + + SELECT CAST(CONCAT(vYear, '-01-01') AS DATETIME), util.dayEnd(CAST(CONCAT(vYear, '-12-31') AS DATE)) + INTO vDatedFrom, vDatedTo; OPEN vCursor; @@ -21301,7 +21772,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 `movContaAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `movContaAdd__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -21311,12 +21782,13 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `movContaAdd`() +CREATE DEFINER=`root`@`%` PROCEDURE `movContaAdd__`() BEGIN /* Copia en movConta los asientos de XDiario para que luego los importe el proceso automático que hay en SQL Server */ DECLARE vDated DATE; SELECT CONCAT(YEAR(CURDATE()), "-01-01") INTO vDated; +SELECT "2021-01-01" INTO vDated; TRUNCATE XDiario_movConta_IVA; DELETE FROM movConta WHERE enlazadoSage = FALSE AND Asiento <> 1 ; CALL clientesProveedoresAdd; @@ -21503,7 +21975,7 @@ BEGIN JOIN vn.company c ON c.id = x.empresa_id LEFT JOIN XDiario_movConta_IVA xmi ON xmi.id = x.id AND xmi.moveData > 0 LEFT JOIN (SELECT ASIEN, FECREGCON, FECHA_EX - FROM (SELECT ASIEN, FECREGCON, FECHA_EX + FROM (SELECT DISTINCT ASIEN, FECREGCON, FECHA_EX FROM vn2008.XDiario ORDER BY ASIEN, FECREGCON DESC, FECHA_EX DESC ) sub GROUP BY ASIEN @@ -21855,491 +22327,6 @@ 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 `movContaAdd__` */; -/*!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 `movContaAdd__`() -BEGIN - - /* Copia en movConta los asientos de XDiario para que luego los importe el proceso automático que hay en SQL Server - * - */ - - DECLARE vMaxAsiento INT; - - SELECT GREATEST(810000,IFNULL(MAX(Asiento),0)) INTO vMaxAsiento - FROM movConta; - - TRUNCATE XDiario_movConta_IVA; - DELETE FROM movConta WHERE enlazadoSage = FALSE ; - - CALL clientesProveedoresAdd; - CALL planCuentasPgcAdd; - CALL XDiario_movConta_IVA_InvoiceOutAdd_Manager; - CALL XDiario_movConta_IVA_InvoiceInAdd_Manager; - INSERT INTO movConta( - TipoEntrada, -- VARCHAR(2) - Ejercicio, -- Año - CodigoEmpresa, -- ENT(2) - Asiento, -- LONG(4), nº ASIENTO - CargoAbono, -- VARCHAR(1) "D" debe ó "H" haber - CodigoCuenta, -- VARCHAR(15) partida contable - Contrapartida, -- VARCHAR(15) partida contable - FechaAsiento, -- FECHA(8) - Comentario, -- VARCHAR(40) - ImporteAsiento, -- DOBLE(19) - NumeroPeriodo, -- ENT(2) "-1" Al informar este valor se calcula automát. A partir de la fecha de asiento - FechaGrabacion, -- FECHA(8) - CodigoDivisa, -- VARCHAR(3) - ImporteCambio, -- DOBLE(19) - ImporteDivisa, -- DOBLE(19) - FactorCambio, -- DOBLE(19) - IdProcesoIME, -- GUID(16) - TipoCarteraIME, -- ENT(2) "0" para que no genere cartera - TipoAnaliticaIME, -- ENT(2) - StatusTraspasadoIME, -- BYTE "0" para dejar como no importado aún - TipoImportacionIME, -- BYTE "0" Alta "1" Baja - Metalico347, -- ENT(2) - /* ESTOS CAMPOS SOLO SE INFORMAN EN EL CASO DE SER FACTURA */ - BaseIva1, -- DOBLE(19) - PorBaseCorrectora1, -- DOBLE(19) - PorIva1, -- DOBLE(19) - CuotaIva1, -- DOBLE(19) - PorRecargoEquivalencia1,-- DOBLE(19) - RecargoEquivalencia1, -- DOBLE(19) - CodigoTransaccion1, -- BYTE "0" Nacional "1" Intracomunitario "2" Extracomunitario - BaseIva2, - PorBaseCorrectora2, - PorIva2, - CuotaIva2, - PorRecargoEquivalencia2, - RecargoEquivalencia2, - CodigoTransaccion2, - BaseIva3, - PorBaseCorrectora3, - PorIva3, - CuotaIva3, - PorRecargoEquivalencia3, - RecargoEquivalencia3, - CodigoTransaccion3, - BaseIva4, - PorBaseCorrectora4, - PorIva4, - CuotaIva4, - PorRecargoEquivalencia4, - RecargoEquivalencia4, - CodigoTransaccion4, - Año, -- ENT(2) - Serie, -- VARCHAR(10) - Factura, -- LONG(4) - SuFacturaNo, -- VARCHAR(40) - FechaFactura, -- FECHA(8) - ImporteFactura, -- DOBLE(19) - TipoFactura, -- VARCHAR(1) "E" / "R" / "I" - CodigoCuentaFactura, -- VARCHAR(15) cuenta del cliente/proveedor - CifDni, -- VARCHAR(13) - Nombre, -- VARCHAR(35) - CodigoRetencion, -- ENT(2) - BaseRetencion, -- DOBLE(19) - PorRetencion, -- DOBLE(19) - ImporteRetencion, -- DOBLE(19) - SiglaNacion, -- VARCHAR(2) "ES" por defecto - EjercicioFactura, -- ENT(2) - FechaOperacion, -- FECHA(8) - Exclusion347, -- ENT(2) - MantenerAsiento, -- BYTE "-1" mantener "0" Sage asigna nuevo - ClaveOperacionFactura_, -- VARCHAR(1) P(4721000011,4721000021)-I(4721000015-4720000005-4720000006)-D (Rectificativas) - TipoRectificativa, -- ENT(2) - FechaFacturaOriginal, -- FECHA(8) - BaseImponibleOriginal, -- DOBLE(19) - CuotaIvaOriginal, -- DOBLE(19) - ClaseAbonoRectificativas,-- ENT(2) - RecargoEquivalenciaOriginal, -- DOBLE(19) */ - LibreA1, - CodigoIva1, -- ENT(6) - CodigoIva2, -- ENT(6) - CodigoIva3, -- ENT(6) - CodigoIva4, -- ENT(6) - Intracomunitaria -- INT(2) - ) - SELECT 'EN' as TipoEntrada, - YEAR(x.FECHA) AS Ejercicio, - IF (@@hostname = 'db', c.companyCode, companyCodeTest) AS CodigoEmpresa, -- ENT(2) c.companyCode AS CodigoEmpresa, - x.ASIEN AS Asiento, -- LONG(4), nº ASIENTO - IF(x.EURODEBE,"D","H") AS CargoAbono, -- VARCHAR(1) "D" debe ó "H" haber - x.SUBCTA AS CodigoCuenta, -- VARCHAR(15) partida contable - x.CONTRA AS Contrapartida, -- VARCHAR(15) partida contable - x.FECHA AS FechaAsiento, -- FECHA(8) - SUBSTRING(x.CONCEPTO, 1, 40) AS Comentario, -- VARCHAR(40) - IF(x.EURODEBE,x.EURODEBE,x.EUROHABER) AS ImporteAsiento, -- DOBLE(19) - MONTH(x.FECHA) AS NumeroPeriodo, -- ENT(2) "-1" Al informar este valor se calcula automát. A partir de la fecha de asiento - IF( sub2.FECREGCON IS NULL, sub2.FECHA_EX, sub2.FECREGCON) FechaGrabacion, -- FECHA(8) - 'EUR' AS CodigoDivisa, -- VARCHAR(3) - x.CAMBIO AS ImporteCambio, -- DOBLE(19) - IFNULL(x.EURODEBE,x.EUROHABER) AS ImporteDivisa, -- DOBLE(19) - IF(x.CAMBIO,1,0) AS FactorCambio, -- DOBLE(19) - NULL AS IdProcesoIME, -- GUID(16) - 0 AS TipoCarteraIME, -- ENT(2) "0" para que no genere cartera - 0 AS TipoAnaliticaIME, -- ENT(2) - 0 AS StatusTraspasadoIME, -- BYTE "0" para dejar como no importado aún - 0 AS TipoImportacionIME, -- BYTE "0" Alta "1" Baja - x.METAL as Metalico347, - /* ESTOS CAMPOS SOLO SE INFORMAN EN EL CASO DE SER FACTURA */ - xmi.BaseIva1, -- DOBLE(19) - xmi.PorBaseCorrectora1, -- DOBLE(19) - xmi.PorIva1, -- DOBLE(19) - xmi.CuotaIva1, -- DOBLE(19) - xmi.PorRecargoEquivalencia1,-- DOBLE(19) - xmi.RecargoEquivalencia1, -- DOBLE(19) - xmi.CodigoTransaccion1, -- BYTE "0" Nacional "1" Intracomunitario "2" Extracomunitario - xmi.BaseIva2, - xmi.PorBaseCorrectora2, - xmi.PorIva2, - xmi.CuotaIva2, - xmi.PorRecargoEquivalencia2, - xmi.RecargoEquivalencia2, - xmi.CodigoTransaccion2, - xmi.BaseIva3, - xmi.PorBaseCorrectora3, - xmi.PorIva3, - xmi.CuotaIva3, - xmi.PorRecargoEquivalencia3, - xmi.RecargoEquivalencia3, - xmi.CodigoTransaccion3, - xmi.BaseIva4, - xmi.PorBaseCorrectora4, - xmi.PorIva4, - xmi.CuotaIva4, - xmi.PorRecargoEquivalencia4, - xmi.RecargoEquivalencia4, - xmi.CodigoTransaccion4, - xmi.Año, -- ENT(2) - xmi.Serie, -- VARCHAR(10) - xmi.Factura, -- LONG(4) - xmi.SuFacturaNo, -- VARCHAR(40) - xmi.FechaFactura, -- FECHA(8) - xmi.ImporteFactura, -- DOBLE(19) - xmi.TipoFactura, -- VARCHAR(1) "E" / "R" - xmi.CodigoCuentaFactura, -- VARCHAR(15) cuenta del cliente/proveedor - xmi.CifDni, -- VARCHAR(13) - xmi.Nombre, -- VARCHAR(35) - xmi.CodigoRetencion, -- ENT(2) - xmi.BaseRetencion, -- DOBLE(19) - xmi.PorRetencion, -- DOBLE(19) - xmi.ImporteRetencion, -- DOBLE(19) - xmi.SiglaNacion, -- VARCHAR(2) "ES" por defecto - xmi.EjercicioFactura, -- ENT(2) - xmi.FechaOperacion, -- FECHA(8) - xmi.Exclusion347, -- ENT(2) - 1, -- xmi.MantenerAsiento BYTE "-1" mantener "0" Sage asigna nuevo - xmi.ClaveOperacionFactura, -- VARCHAR(1) - xmi.TipoRectificativa, -- ENT(2) - xmi.FechaFacturaOriginal, -- FECHA(8) - xmi.BaseImponibleOriginal, -- DOBLE(19) - xmi.CuotaIvaOriginal, -- DOBLE(19) - xmi.ClaseAbonoRectificativas,-- ENT(2) - xmi.RecargoEquivalenciaOriginal,-- DOBLE(19) */ - xmi.LibreA1, - xmi.CodigoIva1, -- ENT(6) - xmi.CodigoIva2, -- ENT(6) - xmi.CodigoIva3, -- ENT(6) - xmi.CodigoIva4, -- ENT(6) - xmi.Intracomunitaria -- TINYINT(1) - FROM vn2008.XDiario x - JOIN vn.company c ON c.id = x.empresa_id - LEFT JOIN XDiario_movConta_IVA xmi ON xmi.id = x.id - LEFT JOIN (SELECT ASIEN, FECREGCON, FECHA_EX - FROM (SELECT ASIEN, FECREGCON, FECHA_EX - FROM vn2008.XDiario - ORDER BY ASIEN, FECREGCON DESC, FECHA_EX DESC - ) sub GROUP BY ASIEN - )sub2 ON sub2.ASIEN = x.ASIEN - WHERE x.enlazadoSage = 0 - AND c.companyCode; - - - --- Prepara Metálicos - - UPDATE sage.movConta m - JOIN (SELECT Asiento, SUBSTR(c.socialName,1,35) Nombre, c.fi, n.SiglaNacion - FROM sage.movConta m - JOIN vn.client c ON c.id = m.CodigoCuenta-4300000000 - LEFT JOIN Naciones n ON n.countryFk = c.countryFk - WHERE Metalico347 = TRUE AND - CargoAbono = "H" - ) AS sub ON m.Asiento = sub.Asiento - SET - m.Metalico347 = TRUE, - m.Contrapartida = "", - m.TipoFactura = "I", - m.CifDni = sub.fi , - m.Nombre = sub.Nombre, - m.SiglaNacion = sub.SiglaNacion - WHERE m.enlazadoSage = FALSE; - --- Elimina cuentas de cliente/proveedor que no se utilizarán en la importación - DELETE cp - FROM clientesProveedores cp - JOIN (SELECT cp.codigoCuenta - FROM clientesProveedores cp - LEFT JOIN movConta mc ON mc.codigoCuenta = cp.codigoCuenta AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL - GROUP BY cp.codigoCuenta - ) sub ON sub.codigoCuenta = cp.codigoCuenta ; - --- Elimina cuentas contables que no se utilizarán en la importación - DELETE pc - FROM planCuentasPGC pc - JOIN ( SELECT pc.codigoCuenta - FROM planCuentasPGC pc - LEFT JOIN movConta mc ON mc.codigoCuenta = pc.codigoCuenta AND mc.enlazadoSage = FALSE - WHERE mc.codigoCuenta IS NULL - GROUP BY pc.codigoCuenta - ) sub ON sub.codigoCuenta = pc.codigoCuenta ; - - - - -/*UPDATE sage.movConta m - JOIN (SELECT DISTINCT(Asiento) - FROM sage.movConta - WHERE Metalico347 = TRUE - ) AS sub ON m.Asiento = sub.Asiento -SET - m.Metalico347 = TRUE, - m.Contrapartida = "", - m.TipoFactura = "I";*/ - - - -/*-- Actualiza las facturas DUA para excluirlas del 347 y marcarlas como intracomunitarias -/*UPDATE sage.movConta mc - SET - mc.Intracomunitaria = 1, - mc.Exclusion347 = 1 -WHERE - mc.CodigoCuenta = '4700000999'; */ - - --- MARCAR EN CASO DE SER INTRACOMUNITARIA -/* -UPDATE sage.movConta mc - SET - mc.Intracomunitaria = 1 -WHERE - mc.CodigoTransaccion1 IN (20,29); -*/ - - - -- LAS FACTURAS RTECTIFICATIVAS QUE TIENEN CUENTA DE IVA 477.2 SALE CON T.T. 1, TODAS ESTAS FACTURAS DEBEN DE TENER T.T. 15 - - /*UPDATE sage.movConta mc - JOIN - (SELECT - Asiento - FROM - sage.movConta - WHERE - CodigoCuenta = 4770000002) sub ON sub.Asiento = mc.Asiento -SET - CodigoTransaccion1 = CASE - WHEN CodigoTransaccion1 = 1 THEN 15 - ELSE CodigoTransaccion1 - END, - CodigoTransaccion2 = CASE - WHEN CodigoTransaccion2 = 1 THEN 15 - ELSE CodigoTransaccion2 - END, - CodigoTransaccion3 = CASE - WHEN CodigoTransaccion3 = 1 THEN 15 - ELSE CodigoTransaccion3 - END, - CodigoTransaccion4 = CASE - WHEN CodigoTransaccion4 = 1 THEN 15 - ELSE CodigoTransaccion4 - END -WHERE - serie = 'R'; - -*/ - -/* -Nombre Tipo Longitud Descripción campo / Valor por defecto -MovPosicion Guid contador 16 Automático, no informar -Ejercicio Entero 2 -1 -- Al informar este valor se calcula automát. A partir de la fecha de asiento -CodigoEmpresa Entero 2 Empresa de Sage 200c donde va destinado el asiento -Asiento Entero Largo 4 Número de asiento -CargoAbono Texto 1 "D" - Debe / "H" - Haber -CodigoCuenta Texto 15 Cuenta contable del movimiento -Contrapartida Texto 15 Es informativo, no es necesario informarlo -FechaAsiento Fecha 8 Fecha del asiento -TipoDocumento Texto 6 -DocumentoConta Texto 9 -Comentario Texto 40 Comentario del asiento -ImporteAsiento Doble 19 Importe del movimiento -CodigoDiario Entero 2 -CodigoCanal Texto 10 Centro coste analítico (no necesario informar) -CodigoActividad Texto 1 -FechaVencimiento Fecha 8 Si se tienen que generar efectos, será la fecha de vto. Del efecto. No informar -NumeroPeriodo Entero 2 -1 -- Al informar este valor se calcula automát. A partir de la fecha de asiento -CodigoUsuario Entero 2 -FechaGrabacion Fecha 8 -TipoEntrada Texto 2 -CodigoDepartamento Texto 10 Centro coste analítico (no necesario informar) -CodigoSeccion Texto 10 Centro coste analítico (no necesario informar) -CodigoDivisa Texto 3 -ImporteCambio Doble 19 -ImporteDivisa Doble 19 -FactorCambio Doble 19 -CodigoProyecto Texto 10 Centro coste analítico (no necesario informar) -LibreN1 Entero Largo 4 Campo libre numérico -LibreN2 Entero Largo 4 Campo libre numérico -LibreA1 Texto 15 Campo libre alfanumérico -LibreA2 Texto 15 Campo libre alfanumérico -IdDelegacion Texto 10 Centro coste analítico (no necesario informar) -OrdenMovimientos Contador 4 Número de orden de cada movimiento dentro de un mismo asiento, autonumerar para cada asiento -MovCartera Guid 16 -IdProcesoIME Guid 16 guid igual para todos los registros que correspondan a una misma importación. -TipoCarteraIME Entero 2 0 - Para que no genere cartera -TipoAnaliticaIME Entero 2 -StatusTraspasadoIME Byte 1 0 - Para que quede marcado el movimiento como no importado todavía. -TipoImportacionIME Byte 1 0 - Alta -BaseIva1 Doble 19 Base para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorBaseCorrectora1 Doble 19 Base correctora (en caso de que la haya) para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorIva1 Doble 19 Porcentaje IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CuotaIva1 Doble 19 Cuota IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorRecargoEquivalencia1 Doble 19 Si hay recargo - Porcentaje de recargo para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -RecargoEquivalencia1 Doble 19 Si hay recargo - Importe de Recargo para el IVA 1 (idéntico para cada posible IVA hasta el 4) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CodigoTransaccion1 Byte 1 Ver con dpto. de contabilidad - Depende de la naturaleza del asiento (Nacional, Intracoumunitario, etc…) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -BaseIva2 Doble 19 0 -PorBaseCorrectora2 Doble 19 0 -PorIva2 Doble 19 0 -CuotaIva2 Doble 19 0 -PorRecargoEquivalencia2 Doble 19 0 -RecargoEquivalencia2 Doble 19 0 -CodigoTransaccion2 Byte 1 0 -BaseIva3 Doble 19 0 -PorBaseCorrectora3 Doble 19 0 -PorIva3 Doble 19 0 -CuotaIva3 Doble 19 0 -PorRecargoEquivalencia3 Doble 19 0 -RecargoEquivalencia3 Doble 19 0 -CodigoTransaccion3 Byte 1 0 -BaseIva4 Doble 19 0 -PorBaseCorrectora4 Doble 19 0 -PorIva4 Doble 19 0 -CuotaIva4 Doble 19 0 -PorRecargoEquivalencia4 Doble 19 0 -RecargoEquivalencia4 Doble 19 0 -CodigoTransaccion4 Byte 1 0 -Año Entero 2 Ejercicio de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Serie Texto 10 Serie de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Factura Entero Largo 4 Número de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -SuFacturaNo Texto 40 Número de la factura del proveedor para factura recibidas, en el caso de que el asiento sea de una factura. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -FechaFactura Fecha 8 Fecha de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -ImporteFactura Doble 19 Importe de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -TipoFactura Texto 1 "E" - Factura emitida / "R" - Factura Recibida - en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CodigoCuentaFactura Texto 15 Cuenta contable del cliente / proveedor en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CifDni Texto 13 CIF del cliente / proveedor en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Nombre Texto 35 Nombre del cliente / proveedor en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CodigoRetencion Entero 2 Código de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -BaseRetencion Doble 19 Base de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -PorRetencion Doble 19 Porcentaje de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -ImporteRetencion Doble 19 Importe de retención de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -AbonoIva Entero 2 0 -CodigoActividadF Texto 1 ('') -Intracomunitaria Entero 2 0 -CodigoTerritorio Entero 2 0 -SiglaNacion Texto 2 Sigla de la nación de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -RetencionInformativa Entero 2 0 -EjercicioFacturaOriginal Entero 2 0 -SerieFacturaOriginal Texto 10 ('') -NumeroFacturaOriginal Entero Largo 4 0 -EjercicioFactura Entero 2 Ejercicio de la factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -CobroPagoRetencion Texto 1 ('') -FechaOperacion Fecha 8 Normalmente Fecha Factura en el caso de que sea un asiento de facturas. (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -Exclusion347 Entero 2 0 -MovIdentificadorIME Guid contador 16 (newid()) -Previsiones Texto 1 ('') -MantenerAsiento Byte 1 -1 si se quiere mantener el número de asiento que se informa en la importación o "0" si se quiere que se asigne automáticamente el asiento en Sage 200c -OrdenMovIME Entero 2 0 -Metalico347 Entero 2 0 -ClaveOperacionFactura_ Texto 1 Ver con dpto. de contabilidad - Depende de la naturaleza del asiento (Nacional, Intracoumunitario, etc…) (Solamente se informa en el movimiento de la factura - cuenta cliente / proveedor) -SerieAgrupacion_ Texto 10 ('') -NumeroFacturaInicial_ Entero Largo 4 0 -NumeroFacturaFinal_ Entero Largo 4 0 -IdAsientoExterno Texto 50 ('') -IdDiarioExterno Texto 10 ('') -IdFacturaExterno Texto 50 ('') -IdMovimiento Texto 40 ('') -IdCuadre Entero 2 ((0)) -FechaCuadre Fecha 8 (getdate()) -TipoCuadre Texto 4 ('') -AgrupacionCuadre Entero Largo 4 ((0)) -StatusSaldo Entero 2 ((0)) -StatusConciliacion Entero 2 ((0)) -CodigoConciliacion Entero Largo 4 ((0)) -FechaConciliacion Fecha 8 -TipoConciliacion Entero 2 ((0)) -IndicadorContaBanco Texto 1 ('') -Descripcion3 Texto 40 ('') -Descripcion4 Texto 40 ('') -Descripcion5 Texto 40 ('') -Descripcion6 Texto 40 ('') -Descripcion7 Texto 40 ('') -Descripcion8 Texto 50 ('') -Descripcion9 Texto 50 ('') -Descripcion2 Texto 250 ('') -Descripcion1 Texto 250 ('') -Punteo1 Entero 2 ((0)) -Punteo9 Entero 2 ((0)) -Punteo8 Entero 2 ((0)) -Punteo7 Entero 2 ((0)) -Punteo6 Entero 2 ((0)) -Punteo5 Entero 2 ((0)) -Punteo4 Entero 2 ((0)) -Punteo3 Entero 2 ((0)) -Punteo2 Entero 2 ((0)) -CodigoIva1 Entero 2 ((0)) -CodigoIva2 Entero 2 ((0)) -CodigoIva3 Entero 2 ((0)) -CodigoIva4 Entero 2 ((0)) -CriterioIva Byte 1 ((0)) -FechaMaxVencimiento Fecha 8 -TipoCriterioCaja Byte 1 ((0)) -MovFacturaOrigenIME Texto 50 ('') -IdFacturaExternoFinal Texto 50 ('') -IdFacturaExternoInicial Texto 50 ('') -IdFacturaExternoOriginal Texto 50 ('') -NumFacturasExternoAgrupacion Entero Largo 4 ((0)) -CodigoMedioCobro Texto 1 ('') -MedioCobro Texto 31 ('') -IvaDeducible1 Entero 2 ((-1)) -IvaDeducible2 Entero 2 ((-1)) -IvaDeducible3 Entero 2 ((-1)) -IvaDeducible4 Entero 2 ((-1)) -TipoRectificativa Entero 2 ((0)) -FechaFacturaOriginal Fecha 8 -BaseImponibleOriginal Doble 19 ((0)) -CuotaIvaOriginal Doble 19 ((0)) -ClaseAbonoRectificativas Entero 2 ((0)) -RecargoEquivalenciaOriginal Doble 19 ((0)) -ObjetoFactura Texto 500 ('') -*/ -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 `pgc_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -22394,7 +22381,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 `planCuentasPgcAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `planCuentasPgcAdd__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -22404,7 +22391,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `planCuentasPgcAdd`() +CREATE DEFINER=`root`@`%` PROCEDURE `planCuentasPgcAdd__`() BEGIN TRUNCATE TABLE planCuentasPGC; @@ -22459,7 +22446,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 `XDiario_movConta_IVA_InvoiceInAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `XDiario_movConta_IVA_InvoiceInAdd_Manager__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -22469,554 +22456,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_movConta_IVA_InvoiceInAdd`(IN vInvoiceInFk INT, IN vXDiarioId INT) -BEGIN - - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vBase DOUBLE; - DECLARE vVat DOUBLE; - DECLARE vRate DOUBLE; - DECLARE vTransactionCode INT; - DECLARE vCounter INT DEFAULT 0; - DECLARE vTransactionCodeOld INT; - DECLARE vTaxCode INT; - DECLARE vTaxCodeOld INT; - DECLARE vOperationCode VARCHAR(1); - DECLARE vIsIntracommunity BOOL DEFAULT FALSE; - DECLARE vDuaExcluded INT; - - DECLARE rs CURSOR FOR -- IVA - SELECT it.taxableBase BASEEURO, - CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)) vat, - t.PorcentajeIva rate, - it.transactionTypeSageFk transactionCode, - it.taxTypeSageFk taxCode, - t.isIntracommunity, - tt.ClaveOperacionDefecto operationCode, - id.id - FROM vn.invoiceIn i - JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id - JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk - JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk - LEFT JOIN tmp.invoiceDua id ON id.id = vXDiarioId - WHERE i.id = vInvoiceInFk - AND i.id> 70000; -- los DUAS no son vInvoiceInFk, pero se pasan en el mismo parametro comparten id en tablas distintas de InvoiceIN (100000) dua(20000) - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DELETE FROM XDiario_movConta_IVA - WHERE id = vXDiarioId; - - INSERT INTO XDiario_movConta_IVA(id, LibreA1) - VALUES (vXDiarioId, vInvoiceInFk); - - OPEN rs; - FETCH rs INTO vBase, - vVat, - vRate, - vTransactionCode, - vTaxCode, - vIsIntracommunity, - vOperationCode, - vDuaExcluded; - - SET vTransactionCodeOld=vTransactionCode; - SET vTaxCodeOld=vTaxCode; - - WHILE NOT vDone DO - IF vOperationCode IS NOT NULL THEN - UPDATE XDiario_movConta_IVA - SET ClaveOperacionFactura = vOperationCode - WHERE id = vXDiarioId; - END IF; - - IF vTransactionCode IS NULL THEN - SET vTransactionCode = vTransactionCodeOld; - END IF; - - IF vTaxCodeOld IS NULL THEN - SET vTaxCode = vTaxCodeOld; - END IF; - - SET vCounter = vCounter + 1; - CASE vCounter - WHEN 1 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva1 = vBase, - PorIva1 = vRate, - CuotaIva1 = vVat, - CodigoTransaccion1 = vTransactionCode, - CodigoIva1 = vTaxCode - WHERE id = vXDiarioId; - WHEN 2 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva2 = vBase, - PorIva2 = vRate, - CuotaIva2 = vVat, - CodigoTransaccion2 = vTransactionCode, - CodigoIva2 = vTaxCode - WHERE id = vXDiarioId; - WHEN 3 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva3 = vBase, - PorIva3 = vRate, - CuotaIva3 = vVat, - CodigoTransaccion3 = vTransactionCode, - CodigoIva3 = vTaxCode - WHERE id = vXDiarioId; - WHEN 4 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva4 = vBase, - PorIva4 = vRate, - CuotaIva4 = vVat, - CodigoTransaccion4 = vTransactionCode, - CodigoIva4 = vTaxCode - WHERE id = vXDiarioId; - ELSE - SELECT vXDiarioId INTO vXDiarioId; - END CASE; - - IF vIsIntracommunity THEN - UPDATE XDiario_movConta_IVA - SET Intracomunitaria = TRUE - WHERE id = vXDiarioId; - END IF; - - SET vTransactionCodeOld=vTransactionCode; - SET vTaxCodeOld=vTaxCode; - - FETCH rs INTO vBase, - vVat, - vRate, - vTransactionCode, - vTaxCode, - vIsIntracommunity, - vOperationCode, - vDuaExcluded; - END WHILE; - CLOSE rs; - - UPDATE XDiario_movConta_IVA xmi - JOIN tmp.invoiceInList ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - LEFT JOIN tmp.invoiceDua id ON id.id = xmi.id - JOIN vn.supplier s ON s.id = ii.supplierFk - JOIN Naciones n ON n.countryFk = s.countryFk - SET xmi.CodigoDivisa = ii.currencyFk, - xmi.Año = YEAR(ii.issued), - xmi.Serie = ii.serial, - xmi.Factura = ii.serialNumber, -- x.FACTURA, DUAS¿? - xmi.FechaFactura = ii.issued, - xmi.ImporteFactura = IFNULL(xmi.BaseIva1, 0) + IFNULL(xmi.CuotaIva1, 0) + - IFNULL(xmi.BaseIva2, 0) + IFNULL(xmi.CuotaIva2, 0) + - IFNULL(xmi.BaseIva3, 0) + IFNULL(xmi.CuotaIva3, 0) + - IFNULL(xmi.BaseIva4, 0) + IFNULL(xmi.CuotaIva4, 0), - xmi.TipoFactura = IF(id.id,IF( ii.serial = 'D', 'R','I'), 'R'), -- MARCAR I para informativa - xmi.CodigoCuentaFactura = x.SUBCTA, - xmi.CifDni = IF(LEFT(TRIM(s.nif),2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif),3) ,s.nif), - xmi.Nombre = s.name, - xmi.SiglaNacion = n.SiglaNacion, - xmi.EjercicioFactura = YEAR(ii.issued), - xmi.FechaOperacion = ii.issued, - xmi.MantenerAsiento = TRUE, - xmi.SuFacturaNo = ii.supplierRef, - xmi.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)), - xmi.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)), - xmi.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)), - xmi.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)), - xmi.FechaFacturaOriginal = x.FECHA_EX - WHERE xmi.id = vXDiarioId; - - -- RETENCIONES - - UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - JOIN vn.supplier s ON s.id = supplierFk - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk - JOIN (SELECT SUM(BASEEURO) taxableBase, SUM(EURODEBE) taxBase - FROM vn.XDiario - WHERE BASEEURO <> 0 AND ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioId) - )sub - SET xmi.CodigoRetencion = t.CodigoRetencion, - xmi.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', 'R', xmi.ClaveOperacionFactura), - xmi.BaseRetencion = IF (t.CodigoRetencion = 2, sub.taxableBase + sub.taxBase, sub.taxableBase), - xmi.PorRetencion = t.PorcentajeRetencion, - xmi.ImporteRetencion = iit.taxableBase * - 1 - WHERE xmi.id = vXDiarioId AND iit.expenceFk = 4751000000; - -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 `XDiario_movConta_IVA_InvoiceInAddTest` */; -/*!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 `XDiario_movConta_IVA_InvoiceInAddTest`( - IN vInvoiceInFk INT, IN vXDiarioId INT) -BEGIN -/* - DECLARE done BOOL DEFAULT FALSE; - DECLARE vBase DOUBLE; - DECLARE vVat DOUBLE; - DECLARE vRate DOUBLE; - DECLARE vTransactionCode INT; - DECLARE vCounter INT DEFAULT 0; - - -- IVA - DECLARE rs CURSOR FOR - SELECT - x.BASEEURO, - x.EURODEBE vat, - IFNULL(tc2.rate,tc1.rate), - IFNULL(tc2.transactionCode,tc1.transactionCode) - FROM vn.invoiceInTax iit - JOIN vn.taxCode tc1 ON tc1.id = iit.taxCodeFk - JOIN vn2008.XDiario x ON x.ASIEN = (SELECT ASIEN FROM vn2008.XDiario WHERE id = vXDiarioId) - LEFT JOIN vn.invoiceInEntry iie ON iie.invoiceInFk = iit.invoiceInFk - LEFT JOIN vn.invoiceInIntrastat iii ON iii.invoiceInFk = iie.invoiceInAwbFk - LEFT JOIN vn.intrastat i ON i.id = iii.intrastatFk - LEFT JOIN vn.taxCode tc2 ON tc2.id = i.taxCodeFk - WHERE iit.invoiceInFk = vInvoiceInFk - AND iit.taxableBase <> 0 AND x.BASEEURO AND x.IVA = IFNULL(tc2.rate,tc1.rate) - AND x.CLAVE = vInvoiceInFk - GROUP BY x.id; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - - DELETE FROM XDiario_movConta_IVA - WHERE id = vXDiarioId; - - INSERT INTO XDiario_movConta_IVA(id, LibreA1) - VALUES (vXDiarioId, vInvoiceInFk); - - OPEN rs; - - FETCH rs INTO vBase, - vVat, - vRate, - vTransactionCode; - - WHILE NOT done DO - - SET vCounter = vCounter + 1; - - CASE vCounter - - WHEN 1 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva1 = vBase, - PorIva1 = vVat, - CuotaIva1 = vRate, - CodigoTransaccion1 = vTransactionCode - WHERE id = vXDiarioId; - - WHEN 2 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva2 = vBase, - PorIva2 = vVat, - CuotaIva2 = vRate, - CodigoTransaccion2 = vTransactionCode - WHERE id = vXDiarioId; - - - WHEN 3 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva3 = vBase, - PorIva3 = vVat, - CuotaIva3 = vRate, - CodigoTransaccion3 = vTransactionCode - WHERE id = vXDiarioId; - - WHEN 4 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva4 = vBase, - PorIva4 = vVat, - CuotaIva4 = vRate, - CodigoTransaccion4 = vTransactionCode - WHERE id = vXDiarioId; - - END CASE; - - FETCH rs INTO vBase, - vVat, - vRate, - vTransactionCode; - END WHILE; - - CLOSE rs; - - -- OTROS CAMPOS RELATIVOS A LAS FACTURAS - UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - LEFT JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - LEFT JOIN vn.taxCode tc ON iit.taxCodeFk = tc.id - JOIN vn.invoiceInSerial iis ON iis.code = ii.serial - JOIN vn.taxArea ta ON ta.code = iis.taxAreaFk - JOIN vn.supplier s ON s.id = ii.supplierFk - SET xmi.Año = YEAR(ii.issued), - xmi.Serie = ii.serial, - xmi.Factura = supplierRef, - xmi.FechaFactura = ii.issued, - xmi.ImporteFactura = BaseIva1 + CuotaIva1 + BaseIva2 + CuotaIva2 + BaseIva3 + CuotaIva3 + BaseIva4 + CuotaIva4, - xmi.TipoFactura = 'R', - xmi.CodigoCuentaFactura = x.SUBCTA, - xmi.CifDni = s.nif, - xmi.Nombre = s.name, - xmi.SiglaNacion = 'ES', - xmi.EjercicioFactura = YEAR(ii.issued), - xmi.FechaOperacion = ii.issued, - xmi.MantenerAsiento = TRUE, - xmi.ClaveOperacionFactura = ta.ClaveOperacionFactura, - xmi.SuFacturaNo = ii.supplierRef - - WHERE xmi.id = vXDiarioId; - - -- RETENCIONES - UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - JOIN vn.supplier s ON s.id = supplierFk - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN vn.taxCode tc ON tc.id = iit.taxCodeFk - SET xmi.CodigoRetencion = - CASE - WHEN s.account LIKE '_____4____' THEN 2 - WHEN s.account LIKE '_____3____' AND ii.cplusTrascendency472Fk = 1 THEN 18 - WHEN s.account LIKE '_____3____'AND ii.cplusTrascendency472Fk = 1 THEN 19 - END, - xmi.BaseRetencion = iit.taxableBase, - xmi.PorRetencion = tc.rate, - xmi.ImporteRetencion = iit.taxableBase * (tc.rate / 100) - WHERE xmi.id = vXDiarioId AND iit.taxableBase < 0 AND s.account LIKE '_____4____'; -*/ - -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 `XDiario_movConta_IVA_InvoiceInAdd_` */; -/*!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 `XDiario_movConta_IVA_InvoiceInAdd_`(IN vInvoiceInFk INT, IN vXDiarioId INT) -BEGIN - - DECLARE vDone BOOL DEFAULT FALSE; - DECLARE vBase DOUBLE; - DECLARE vVat DOUBLE; - DECLARE vRate DOUBLE; - DECLARE vTransactionCode INT; - DECLARE vCounter INT DEFAULT 0; - DECLARE vTransactionCodeOld INT; - DECLARE vTaxCode INT; - DECLARE vTaxCodeOld INT; - DECLARE vOperationCode VARCHAR(1); - DECLARE vIsIntracommunity BOOL DEFAULT FALSE; - DECLARE vDuaExcluded INT; - - DECLARE rs CURSOR FOR -- IVA - SELECT it.taxableBase BASEEURO, - ( it.taxableBase/100) * t.PorcentajeIva vat, - t.PorcentajeIva rate, - i. transactionTypeSageFk transactionCode, - it.taxTypeSageFk taxCode, - t.isIntracommunity, - tt.ClaveOperacionDefecto operationCode, - id.id - FROM vn.invoiceIn i - JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id - JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk - JOIN TiposTransacciones tt ON tt.CodigoTransaccion = i.transactionTypeSageFk - LEFT JOIN tmp.invoiceDua id ON id.id = vXDiarioId - WHERE i.id = vInvoiceInFk; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DELETE FROM XDiario_movConta_IVA - WHERE id = vXDiarioId; - - OPEN rs; - FETCH rs INTO vBase, - vVat, - vRate, - vTransactionCode, - vTaxCode, - vIsIntracommunity, - vOperationCode, - vDuaExcluded; - - SET vTransactionCodeOld=vTransactionCode; - SET vTaxCodeOld=vTaxCode; - - IF vDuaExcluded IS NULL THEN - - WHILE NOT vDone DO - IF vOperationCode IS NOT NULL THEN - UPDATE XDiario_movConta_IVA - SET ClaveOperacionFactura = vOperationCode - WHERE id = vXDiarioId; - END IF; - - IF vTransactionCode IS NULL THEN - SET vTransactionCode = vTransactionCodeOld; - END IF; - - IF vTaxCodeOld IS NULL THEN - SET vTaxCode = vTaxCodeOld; - END IF; - - SET vCounter = vCounter + 1; - - CASE vCounter - WHEN 1 THEN - INSERT INTO XDiario_movConta_IVA(id, LibreA1, BaseIva1 , PorIva1 , CuotaIva1, CodigoTransaccion1, CodigoIva1) - VALUES (vXDiarioId, vInvoiceInFk,vBase, vRate, vVat, vTransactionCode, vTaxCode); - WHEN 2 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva2 = vBase, - PorIva2 = vRate, - CuotaIva2 = vVat, - CodigoTransaccion2 = vTransactionCode, - CodigoIva2 = vTaxCode - WHERE id = vXDiarioId; - WHEN 3 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva3 = vBase, - PorIva3 = vRate, - CuotaIva3 = vVat, - CodigoTransaccion3 = vTransactionCode, - CodigoIva3 = vTaxCode - WHERE id = vXDiarioId; - WHEN 4 THEN - UPDATE XDiario_movConta_IVA - SET BaseIva4 = vBase, - PorIva4 = vRate, - CuotaIva4 = vVat, - CodigoTransaccion4 = vTransactionCode, - CodigoIva4 = vTaxCode - WHERE id = vXDiarioId; - ELSE - SELECT vXDiarioId; - END CASE; - - IF vIsIntracommunity THEN - UPDATE XDiario_movConta_IVA - SET Intracomunitaria = TRUE - WHERE id = vXDiarioId; - END IF; - - SET vTransactionCodeOld=vTransactionCode; - SET vTaxCodeOld=vTaxCode; - - FETCH rs INTO vBase, - vVat, - vRate, - vTransactionCode, - vTaxCode, - vIsIntracommunity, - vOperationCode, - vDuaExcluded; - END WHILE; - ELSE - INSERT INTO XDiario_movConta_IVA(id, LibreA1) - VALUES (vXDiarioId, vInvoiceInFk); - END IF; - CLOSE rs; - - UPDATE XDiario_movConta_IVA xmi - JOIN tmp.invoiceInList ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - LEFT JOIN tmp.invoiceDua id ON id.id = xmi.id - JOIN vn.supplier s ON s.id = ii.supplierFk - JOIN Naciones n ON n.countryFk = s.countryFk - SET xmi.CodigoDivisa = ii.currencyFk, - xmi.Año = YEAR(ii.issued), - xmi.Serie = ii.serial, - xmi.Factura = ii.serialNumber, -- x.FACTURA, DUAS¿? - xmi.FechaFactura = ii.issued, - xmi.ImporteFactura = BaseIva1 + CuotaIva1 + BaseIva2 + CuotaIva2 + BaseIva3 + CuotaIva3 + BaseIva4 + CuotaIva4, - xmi.TipoFactura = IF(id.id,IF( ii.serial = 'D', 'R','I'), 'R'), -- MARCAR I para informativa - xmi.CodigoCuentaFactura = x.SUBCTA, - xmi.CifDni = IF(LEFT(TRIM(s.nif),2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif),3) ,s.nif), - xmi.Nombre = s.name, - xmi.SiglaNacion = n.SiglaNacion, - xmi.EjercicioFactura = YEAR(ii.issued), - xmi.FechaOperacion = ii.issued, - xmi.MantenerAsiento = TRUE, - xmi.SuFacturaNo = ii.supplierRef, - xmi.IvaDeducible1 = ii.isVatDeductible, - xmi.IvaDeducible2 = ii.isVatDeductible, - xmi.IvaDeducible3 = ii.isVatDeductible, - xmi.IvaDeducible4 = ii.isVatDeductible, - xmi.FechaFacturaOriginal = x.FECHA_EX - WHERE xmi.id = vXDiarioId; - - -- RETENCIONES - /* UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - JOIN vn.supplier s ON s.id = supplierFk - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk - SET xmi.CodigoRetencion = t.CodigoRetencion, - xmi.BaseRetencion = iit.taxableBase, - xmi.PorRetencion = t.PorcentajeRetencion, - xmi.ImporteRetencion = iit.taxableBase * (t.PorcentajeRetencion / 100) - WHERE xmi.id = vXDiarioId AND iit.taxableBase < 0 ;*/ - - UPDATE XDiario_movConta_IVA xmi - JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk - JOIN vn2008.XDiario x ON x.id = xmi.id - JOIN vn.supplier s ON s.id = supplierFk - JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id - JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk - JOIN (SELECT SUM(BASEEURO) taxableBase, SUM(EURODEBE) taxBase - FROM vn.XDiario - WHERE BASEEURO <> 0 AND ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioId) - )sub - SET xmi.CodigoRetencion = t.CodigoRetencion, - xmi.BaseRetencion = IF (t.CodigoRetencion = 2, sub.taxableBase + sub.taxBase, sub.taxableBase), - xmi.PorRetencion = t.PorcentajeRetencion, - xmi.ImporteRetencion = iit.taxableBase * - 1 - WHERE xmi.id = vXDiarioId AND iit.expenceFk= 4751000000 ; - -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 `XDiario_movConta_IVA_InvoiceInAdd_Manager` */; -/*!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 `XDiario_movConta_IVA_InvoiceInAdd_Manager`() +CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_movConta_IVA_InvoiceInAdd_Manager__`() BEGIN DECLARE done BOOL DEFAULT FALSE; DECLARE vInvoiceFk INT; @@ -23040,6 +22480,7 @@ BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; SELECT CONCAT(YEAR(CURDATE()), "-01-01") INTO vDated; + SELECT "2021-01-01" INTO vDated; DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua; CREATE TEMPORARY TABLE tmp.invoiceDua SELECT id @@ -23259,7 +22700,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 `XDiario_movConta_IVA_InvoiceInAdd_Manager__` */; +/*!50003 DROP PROCEDURE IF EXISTS `XDiario_movConta_IVA_InvoiceInAdd__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -23269,245 +22710,182 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_movConta_IVA_InvoiceInAdd_Manager__`() +CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_movConta_IVA_InvoiceInAdd__`(IN vInvoiceInFk INT, IN vXDiarioId INT) BEGIN - DECLARE done BOOL DEFAULT FALSE; - DECLARE vInvoiceFk INT; - DECLARE vXDiarioFk INT; - DECLARE vDated DATE; - DECLARE rs CURSOR FOR - SELECT IFNULL(ii.id,x.FACTURA) invoiceInFk, x.id XDiarioFk - FROM vn2008.XDiario x - JOIN(SELECT DISTINCT (x.ASIEN) - FROM vn2008.XDiario x - LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id - LEFT JOIN vn.invoiceInTax it ON it.invoiceInFk = ii.id - WHERE it.taxTypeSageFk IS NOT NULL AND - x.enlazadoSage = FALSE AND - x.FECHA >= vDated - ) sub ON sub.ASIEN =x.ASIEN -- Elimina las Facturas con IVA 0 (-) no se trasladan a sage - LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id - WHERE x.enlazadoSage = FALSE AND - x.FECHA >= vDated AND - ((SUBCTA<>"4700000999" AND ii.id IS NOT NULL) - OR (SUBCTA LIKE '472%' AND CONTRA ='4330002067' AND ii.id IS NULL)) ; + + DECLARE vDone BOOL DEFAULT FALSE; + DECLARE vBase DOUBLE; + DECLARE vVat DOUBLE; + DECLARE vRate DOUBLE; + DECLARE vTransactionCode INT; + DECLARE vCounter INT DEFAULT 0; + DECLARE vTransactionCodeOld INT; + DECLARE vTaxCode INT; + DECLARE vTaxCodeOld INT; + DECLARE vOperationCode VARCHAR(1); + DECLARE vIsIntracommunity BOOL DEFAULT FALSE; + DECLARE vDuaExcluded INT; - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + DECLARE rs CURSOR FOR -- IVA + SELECT it.taxableBase BASEEURO, + CAST((( it.taxableBase / 100) * t.PorcentajeIva) AS DECIMAL (10,2)) vat, + t.PorcentajeIva rate, + it.transactionTypeSageFk transactionCode, + it.taxTypeSageFk taxCode, + t.isIntracommunity, + tt.ClaveOperacionDefecto operationCode, + id.id + FROM vn.invoiceIn i + JOIN vn.invoiceInTax it ON it.InvoiceInFk = i.id + JOIN TiposIva t ON t.CodigoIva = it.taxTypeSageFk + JOIN TiposTransacciones tt ON tt.CodigoTransaccion = it.transactionTypeSageFk + LEFT JOIN tmp.invoiceDua id ON id.id = vXDiarioId + WHERE i.id = vInvoiceInFk + AND i.id> 70000; -- los DUAS no son vInvoiceInFk, pero se pasan en el mismo parametro comparten id en tablas distintas de InvoiceIN (100000) dua(20000) + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DELETE FROM XDiario_movConta_IVA + WHERE id = vXDiarioId; - SELECT CONCAT(YEAR(CURDATE()), "-01-01") INTO vDated; - DROP TEMPORARY TABLE IF EXISTS tmp.invoiceDua; - CREATE TEMPORARY TABLE tmp.invoiceDua - SELECT id - FROM vn2008.XDiario x - WHERE ASIEN IN (SELECT ASIEN - FROM vn.invoiceIn ii - JOIN vn2008.XDiario x ON x.CLAVE = ii.id - WHERE x.enlazadoSage = FALSE AND - x.SUBCTA = '4700000999' AND - x.FECHA >= vDated - ) AND - NOT CONTRA <=> "4330002067"; - - DROP TEMPORARY TABLE IF EXISTS tmp.invoiceInList; - CREATE TEMPORARY TABLE tmp.invoiceInList - SELECT i.id id, - i.supplierRef supplierRef, - i.serial serial, - i.supplierFk supplierFk, - i.issued issued, - i.isVatDeductible isVatDeductible, - i.serialNumber serialNumber, - IF(c.code = "EUR", '',c.code) currencyFk - FROM vn.invoiceIn i - JOIN vn.currency c ON c.id = i.currencyFk - WHERE i.bookEntried >= vDated - UNION ALL - SELECT d.id , - d.code , - 'D' , - d.companyFk , - d.issued , - FALSE, - d.id, - '' -- EUROS - FROM vn.dua d - WHERE d.issued IS NOT NULL AND - code IS NOT NULL; + INSERT INTO XDiario_movConta_IVA(id, LibreA1) + VALUES (vXDiarioId, vInvoiceInFk); OPEN rs; - FETCH rs INTO vInvoiceFk, vXDiarioFk; - WHILE NOT done DO - CALL XDiario_movConta_IVA_InvoiceInAdd(vInvoiceFk, vXDiarioFk); - FETCH rs INTO vInvoiceFk, vXDiarioFk; - END WHILE; + FETCH rs INTO vBase, + vVat, + vRate, + vTransactionCode, + vTaxCode, + vIsIntracommunity, + vOperationCode, + vDuaExcluded; + + SET vTransactionCodeOld=vTransactionCode; + SET vTaxCodeOld=vTaxCode; + + WHILE NOT vDone DO + IF vOperationCode IS NOT NULL THEN + UPDATE XDiario_movConta_IVA + SET ClaveOperacionFactura = vOperationCode + WHERE id = vXDiarioId; + END IF; + + IF vTransactionCode IS NULL THEN + SET vTransactionCode = vTransactionCodeOld; + END IF; + + IF vTaxCodeOld IS NULL THEN + SET vTaxCode = vTaxCodeOld; + END IF; + + SET vCounter = vCounter + 1; + CASE vCounter + WHEN 1 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva1 = vBase, + PorIva1 = vRate, + CuotaIva1 = vVat, + CodigoTransaccion1 = vTransactionCode, + CodigoIva1 = vTaxCode + WHERE id = vXDiarioId; + WHEN 2 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva2 = vBase, + PorIva2 = vRate, + CuotaIva2 = vVat, + CodigoTransaccion2 = vTransactionCode, + CodigoIva2 = vTaxCode + WHERE id = vXDiarioId; + WHEN 3 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva3 = vBase, + PorIva3 = vRate, + CuotaIva3 = vVat, + CodigoTransaccion3 = vTransactionCode, + CodigoIva3 = vTaxCode + WHERE id = vXDiarioId; + WHEN 4 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva4 = vBase, + PorIva4 = vRate, + CuotaIva4 = vVat, + CodigoTransaccion4 = vTransactionCode, + CodigoIva4 = vTaxCode + WHERE id = vXDiarioId; + ELSE + SELECT vXDiarioId INTO vXDiarioId; + END CASE; + + IF vIsIntracommunity THEN + UPDATE XDiario_movConta_IVA + SET Intracomunitaria = TRUE + WHERE id = vXDiarioId; + END IF; + + SET vTransactionCodeOld=vTransactionCode; + SET vTaxCodeOld=vTaxCode; + + FETCH rs INTO vBase, + vVat, + vRate, + vTransactionCode, + vTaxCode, + vIsIntracommunity, + vOperationCode, + vDuaExcluded; + END WHILE; CLOSE rs; - - DROP TEMPORARY TABLE tmp.invoiceDua; - DROP TEMPORARY TABLE tmp.invoiceInList; - - -- ASIENTOS CON IVA SOPORTADO 472. y 477. hay que informar 2 líneas la info de facturas una como tipo de factura emitida y otra como recibida - DROP TEMPORARY TABLE IF EXISTS tmp.XDiario_movConta_IVA; - CREATE TEMPORARY TABLE tmp.XDiario_movConta_IVA - SELECT - sub3.id, - mc.CodigoDivisa, - mc.BaseIva1, - mc.PorBaseCorrectora1, - mc.PorIva1, - mc.CuotaIva1, - mc.PorRecargoEquivalencia1, - mc.RecargoEquivalencia1, - mc.CodigoTransaccion1, - mc.CodigoIva1, - mc.BaseIva2, - mc.PorBaseCorrectora2, - mc.PorIva2, - mc.CuotaIva2, - mc.PorRecargoEquivalencia2, - mc.RecargoEquivalencia2, - mc.CodigoTransaccion2, - mc.CodigoIva2, - mc.BaseIva3, - mc.PorBaseCorrectora3, - mc.PorIva3, - mc.CuotaIva3, - mc.PorRecargoEquivalencia3, - mc.RecargoEquivalencia3, - mc.CodigoTransaccion3, - mc.CodigoIva3, - mc.BaseIva4, - mc.PorBaseCorrectora4, - mc.PorIva4, - mc.CuotaIva4, - mc.PorRecargoEquivalencia4, - mc.RecargoEquivalencia4, - mc.CodigoTransaccion4, - mc.CodigoIva4, - mc.Año, - mc.Serie, - mc.Factura, - mc.SuFacturaNo, - mc.FechaFactura, - mc.ImporteFactura, - 'E', - mc.CodigoCuentaFactura, - mc.CifDni, - mc.Nombre, - mc.CodigoRetencion, - mc.BaseRetencion, - mc.PorRetencion, - mc.ImporteRetencion, - mc.SiglaNacion, - mc.EjercicioFactura, - x.FECHA, - mc.Exclusion347, - mc.MantenerAsiento, - mc.Metalico347, - mc.ClaveOperacionFactura, - mc.TipoRectificativa, - mc.FechaFacturaOriginal, - mc.CuotaIvaOriginal, - mc.BaseImponibleOriginal, - mc.ClaseAbonoRectificativas, - mc.RecargoEquivalenciaOriginal, - mc.LibreA1, - mc.IvaDeducible1, - mc.IvaDeducible2, - mc.IvaDeducible3, - mc.IvaDeducible4, - mc.FechaGrabacion, - mc.Intracomunitaria, - mc.moveData - FROM sage.XDiario_movConta_IVA mc - JOIN vn.XDiario x ON x.id = mc.id - JOIN (SELECT x.ASIEN, x.id - FROM vn.XDiario x - JOIN(SELECT DISTINCT(x.ASIEN) ASIEN - FROM (SELECT DISTINCT(ASIEN) - FROM vn.XDiario x - WHERE SUBCTA LIKE '472%' AND - x.enlazadoSage = FALSE AND - x.FECHA >= vDated - ) sub JOIN vn.XDiario x ON x.ASIEN = sub.ASIEN - WHERE x.SUBCTA LIKE '477%' - )sub2 ON sub2.ASIEN = x.ASIEN - WHERE x.CONTRA IS NOT NULL AND x.SUBCTA LIKE '477%' - GROUP BY x.ASIEN - )sub3 ON sub3.ASIEN = x.ASIEN; - - INSERT INTO sage.XDiario_movConta_IVA - (`id`, - `CodigoDivisa`, - `BaseIva1`, - `PorBaseCorrectora1`, - `PorIva1`, - `CuotaIva1`, - `PorRecargoEquivalencia1`, - `RecargoEquivalencia1`, - `CodigoTransaccion1`, - `CodigoIva1`, - `BaseIva2`, - `PorBaseCorrectora2`, - `PorIva2`, - `CuotaIva2`, - `PorRecargoEquivalencia2`, - `RecargoEquivalencia2`, - `CodigoTransaccion2`, - `CodigoIva2`, - `BaseIva3`, - `PorBaseCorrectora3`, - `PorIva3`, - `CuotaIva3`, - `PorRecargoEquivalencia3`, - `RecargoEquivalencia3`, - `CodigoTransaccion3`, - `CodigoIva3`, - `BaseIva4`, - `PorBaseCorrectora4`, - `PorIva4`, - `CuotaIva4`, - `PorRecargoEquivalencia4`, - `RecargoEquivalencia4`, - `CodigoTransaccion4`, - `CodigoIva4`, - `Año`, - `Serie`, - `Factura`, - `SuFacturaNo`, - `FechaFactura`, - `ImporteFactura`, - `TipoFactura`, - `CodigoCuentaFactura`, - `CifDni`, - `Nombre`, - `CodigoRetencion`, - `BaseRetencion`, - `PorRetencion`, - `ImporteRetencion`, - `SiglaNacion`, - `EjercicioFactura`, - `FechaOperacion`, - `Exclusion347`, - `MantenerAsiento`, - `Metalico347`, - `ClaveOperacionFactura`, - `TipoRectificativa`, - `FechaFacturaOriginal`, - `CuotaIvaOriginal`, - `BaseImponibleOriginal`, - `ClaseAbonoRectificativas`, - `RecargoEquivalenciaOriginal`, - `LibreA1`, - `IvaDeducible1`, - `IvaDeducible2`, - `IvaDeducible3`, - `IvaDeducible4`, - `FechaGrabacion`, - `Intracomunitaria`, - `moveData`) - SELECT * - FROM tmp.XDiario_movConta_IVA; - DROP TEMPORARY TABLE tmp.XDiario_movConta_IVA; + + UPDATE XDiario_movConta_IVA xmi + JOIN tmp.invoiceInList ii ON ii.id = vInvoiceInFk + JOIN vn2008.XDiario x ON x.id = xmi.id + LEFT JOIN tmp.invoiceDua id ON id.id = xmi.id + JOIN vn.supplier s ON s.id = ii.supplierFk + JOIN Naciones n ON n.countryFk = s.countryFk + SET xmi.CodigoDivisa = ii.currencyFk, + xmi.Año = YEAR(ii.issued), + xmi.Serie = ii.serial, + xmi.Factura = ii.serialNumber, -- x.FACTURA, DUAS¿? + xmi.FechaFactura = ii.issued, + xmi.ImporteFactura = IFNULL(xmi.BaseIva1, 0) + IFNULL(xmi.CuotaIva1, 0) + + IFNULL(xmi.BaseIva2, 0) + IFNULL(xmi.CuotaIva2, 0) + + IFNULL(xmi.BaseIva3, 0) + IFNULL(xmi.CuotaIva3, 0) + + IFNULL(xmi.BaseIva4, 0) + IFNULL(xmi.CuotaIva4, 0), + xmi.TipoFactura = IF(id.id,IF( ii.serial = 'D', 'R','I'), 'R'), -- MARCAR I para informativa + xmi.CodigoCuentaFactura = x.SUBCTA, + xmi.CifDni = IF(LEFT(TRIM(s.nif),2) = n.SiglaNacion, SUBSTRING(TRIM(s.nif),3) ,s.nif), + xmi.Nombre = s.name, + xmi.SiglaNacion = n.SiglaNacion, + xmi.EjercicioFactura = YEAR(ii.issued), + xmi.FechaOperacion = ii.issued, + xmi.MantenerAsiento = TRUE, + xmi.SuFacturaNo = ii.supplierRef, + xmi.IvaDeducible1 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva1, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.IvaDeducible2 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva2, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.IvaDeducible3 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva3, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.IvaDeducible4 = IF(id.id, FALSE, IF(IFNULL(xmi.BaseIva4, FALSE) = FALSE, FALSE, ii.isVatDeductible)), + xmi.FechaFacturaOriginal = x.FECHA_EX + WHERE xmi.id = vXDiarioId; + + -- RETENCIONES + + UPDATE XDiario_movConta_IVA xmi + JOIN vn.invoiceIn ii ON ii.id = vInvoiceInFk + JOIN vn2008.XDiario x ON x.id = xmi.id + JOIN vn.supplier s ON s.id = supplierFk + JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id + JOIN TiposRetencion t ON t.CodigoRetencion = ii.withholdingSageFk + JOIN (SELECT SUM(BASEEURO) taxableBase, SUM(EURODEBE) taxBase + FROM vn.XDiario + WHERE BASEEURO <> 0 AND ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioId) + )sub + SET xmi.CodigoRetencion = t.CodigoRetencion, + xmi.ClaveOperacionFactura = IF( t.Retencion = 'ARRENDAMIENTO Y SUBARRENDAMIENTO', 'R', xmi.ClaveOperacionFactura), + xmi.BaseRetencion = IF (t.CodigoRetencion = 2, sub.taxableBase + sub.taxBase, sub.taxableBase), + xmi.PorRetencion = t.PorcentajeRetencion, + xmi.ImporteRetencion = iit.taxableBase * - 1 + WHERE xmi.id = vXDiarioId AND iit.expenceFk = 4751000000; END ;; DELIMITER ; @@ -23515,7 +22893,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 `XDiario_movConta_IVA_InvoiceOutAdd` */; +/*!50003 DROP PROCEDURE IF EXISTS `XDiario_movConta_IVA_InvoiceOutAdd_Manager__` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -23525,7 +22903,59 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_movConta_IVA_InvoiceOutAdd`(IN vInvoiceOutFk INT, IN vXDiarioId INT) +CREATE DEFINER=`root`@`%` PROCEDURE `XDiario_movConta_IVA_InvoiceOutAdd_Manager__`() +BEGIN + + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vXDiarioFk INT; + DECLARE vDated DATE; + + DECLARE rs CURSOR FOR + SELECT io.id invoiceOutFk, x.XDiarioFk + FROM vn.invoiceOut io + JOIN (SELECT MIN(id) XDiarioFk, refFk + FROM vn2008.XDiario x + JOIN (SELECT x.ASIEN, CONCAT(x.SERIE,x.FACTURA) AS refFk + FROM vn2008.XDiario x + JOIN vn.company c ON c.id = x.empresa_id + WHERE enlazadoSage = FALSE AND + x.FACTURA AND + c.companyCode AND + x.FECHA >= vDated + GROUP BY refFk + ) a ON a.ASIEN = x.ASIEN + GROUP BY refFk + ) x ON x.refFk = io.ref; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + SELECT CONCAT(YEAR(CURDATE()), "-01-01") INTO vDated; +SELECT "2021-01-01" INTO vDated; + OPEN rs; + FETCH rs INTO vInvoiceFk, vXDiarioFk; + WHILE NOT done DO + CALL XDiario_movConta_IVA_InvoiceOutAdd(vInvoiceFk, vXDiarioFk); + FETCH rs INTO vInvoiceFk, vXDiarioFk; + END WHILE; + CLOSE rs; + +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 `XDiario_movConta_IVA_InvoiceOutAdd__` */; +/*!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 `XDiario_movConta_IVA_InvoiceOutAdd__`(IN vInvoiceOutFk INT, IN vXDiarioId INT) BEGIN DECLARE vDone BOOL DEFAULT FALSE; @@ -23738,57 +23168,6 @@ 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 `XDiario_movConta_IVA_InvoiceOutAdd_Manager` */; -/*!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 `XDiario_movConta_IVA_InvoiceOutAdd_Manager`() -BEGIN - - DECLARE done BOOL DEFAULT FALSE; - DECLARE vInvoiceFk INT; - DECLARE vXDiarioFk INT; - DECLARE vDated DATE; - - DECLARE rs CURSOR FOR - SELECT io.id invoiceOutFk, x.XDiarioFk - FROM vn.invoiceOut io - JOIN (SELECT MIN(id) XDiarioFk, refFk - FROM vn2008.XDiario x - JOIN (SELECT x.ASIEN, CONCAT(x.SERIE,x.FACTURA) AS refFk - FROM vn2008.XDiario x - JOIN vn.company c ON c.id = x.empresa_id - WHERE enlazadoSage = FALSE AND - x.FACTURA AND - c.companyCode AND - x.FECHA >= vDated - GROUP BY refFk - ) a ON a.ASIEN = x.ASIEN - GROUP BY refFk - ) x ON x.refFk = io.ref; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; - SELECT CONCAT(YEAR(CURDATE()), "-01-01") INTO vDated; - OPEN rs; - FETCH rs INTO vInvoiceFk, vXDiarioFk; - WHILE NOT done DO - CALL XDiario_movConta_IVA_InvoiceOutAdd(vInvoiceFk, vXDiarioFk); - FETCH rs INTO vInvoiceFk, vXDiarioFk; - END WHILE; - CLOSE rs; - -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: `salix` @@ -25715,6 +25094,33 @@ 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 `lastDayOfYear` */; +/*!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`@`%` FUNCTION `lastDayOfYear`(vDate DATE) RETURNS date + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns the date formatted to the first day of year. + * + * @param vDate The date to format + * @return The formatted date + */ + RETURN DATE_FORMAT(vDate, '%Y-12-31'); +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 `midnight` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -26856,6 +26262,32 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Table structure for table `addressFilter` +-- + +DROP TABLE IF EXISTS `addressFilter`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `addressFilter` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, + `provinceFk` smallint(5) unsigned DEFAULT NULL, + `countryFk` mediumint(8) unsigned DEFAULT NULL, + `isLogifloraAllowed` tinyint(1) DEFAULT '0', + `isVNHSupplier` tinyint(1) DEFAULT '0' COMMENT 'corresponde al campo edi.VMPSettings.isVNHSupplier', + `isEarlyBird` tinyint(1) DEFAULT '0' COMMENT 'corresponde al campo edi.marketPlace.isEarlybird', + `warehouseFk` smallint(5) unsigned DEFAULT NULL, + PRIMARY KEY (`id`), + KEY `addressFilter_FK` (`provinceFk`), + KEY `addressFilter_FK_1` (`countryFk`), + KEY `addressFilter_FK_2` (`warehouseFk`), + CONSTRAINT `addressFilter_FK` FOREIGN KEY (`provinceFk`) REFERENCES `province` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `addressFilter_FK_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `addressFilter_FK_2` FOREIGN KEY (`warehouseFk`) REFERENCES `warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Establece los criterios para habilitar las compras directas a Floraholland'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `addressForPackaging` -- @@ -33373,33 +32805,32 @@ DELIMITER ;; BEFORE INSERT ON `invoiceOut` FOR EACH ROW -- Edit trigger body code below this line. Do not edit lines above this one BEGIN - DECLARE vRef CHAR(9) DEFAULT '0000001'; - DECLARE vMaxId INT; - - SELECT IFNULL(MAX(id),0) INTO vMaxId - FROM invoiceOut - WHERE serial LIKE NEW.serial - AND ((Year(NEW.issued) = Year(issued) - AND companyFk = NEW.companyFk)); - - IF vMaxId THEN - - SELECT RIGHT(MAX(ref), LENGTH(ref)-1) + 1 - INTO vRef - FROM invoiceOut - WHERE serial LIKE NEW.serial - AND ((Year(NEW.issued) = Year(issued) - AND length(ref) > 6 - AND companyFk = NEW.companyFk) /*OR (NEW.serial LIKE 'B' AND length(ref) > 7)*/ ); - ELSE - SELECT CONCAT(sage200Company,RIGHT(YEAR(CURDATE()),1),'00001') INTO vRef - FROM company - WHERE id = NEW.companyFk; -/*Primer digito la empresa, segundo el año, despues la numeracion correlativa con 5 digitos*/ - END IF; - - SELECT CONCAT(NEW.serial, LPAD(vRef,7,'0')) INTO vRef; - SET NEW.ref = vRef; + DECLARE vRef CHAR(10) ; + + IF YEAR(NEW.issued) <= 2021 THEN + + SELECT CONCAT(NEW.serial, + IFNULL(RIGHT(MAX(i.ref), LENGTH(i.ref)-1) , + RPAD(CONCAT(c.sage200Company, RIGHT(YEAR(CURDATE()), 2)), 7,'0')) + 1) INTO vRef + FROM invoiceOut i + LEFT JOIN company c ON c.id = i.companyFk + WHERE i.serial = NEW.serial + AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.dayEnd(util.lastDayOfYear(NEW.issued)) + AND c.id = NEW.companyFk; + ELSE + + SELECT CONCAT(NEW.serial, + IFNULL(RIGHT(MAX(i.ref), LENGTH(i.ref)-1) , + RPAD(CONCAT(c.sage200Company, RIGHT(YEAR(CURDATE()), 2)), 8,'0')) + 1) INTO vRef + FROM invoiceOut i + LEFT JOIN company c ON c.id = i.companyFk + WHERE i.serial = NEW.serial + AND i.issued BETWEEN util.firstDayOfYear(NEW.issued) AND util.dayEnd(util.lastDayOfYear(NEW.issued)) + AND c.id = NEW.companyFk; + END IF; + + SET NEW.ref = vRef; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33739,6 +33170,12 @@ BEGIN END IF; + IF NEW.itemPackingTypeFk = '' THEN + + SET NEW.itemPackingTypeFk = NULL; + + END IF; + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -33754,28 +33191,14 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `vn`.`item_afterUpdate` - AFTER UPDATE ON `item` FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER `vn`.`item_afterUpdate` + AFTER UPDATE ON `item` + FOR EACH ROW BEGIN - DECLARE vStandardFlowerBox INT; - IF !(NEW.image <=> OLD.image) THEN CALL hedera.image_unref('catalog', OLD.image); CALL hedera.image_ref('catalog', NEW.image); END IF; - IF NEW.density = 0 THEN - CALL util.throw('error densidad = 0'); - END IF; - - IF !(NEW.packingOut <=> OLD.packingOut) THEN - SELECT standardFlowerBox * 1000 INTO vStandardFlowerBox - FROM volumeConfig; - - UPDATE itemCost ic - JOIN warehouse w ON w.id = ic.warehouseFk - SET cm3Delivery = IFNULL(vStandardFlowerBox / NEW.packingOut, cm3) - WHERE itemFk = NEW.id AND w.hasProduction; - END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -34919,7 +34342,7 @@ CREATE TABLE `itemTag` ( `intValue` int(11) DEFAULT NULL, `priority` int(2) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), - UNIQUE KEY `itemFk` (`itemFk`,`tagFk`,`value`) USING BTREE, + UNIQUE KEY `itemTagItemUq` (`itemFk`,`tagFk`), KEY `tagFk` (`tagFk`,`value`), KEY `priorityItem` (`priority`,`itemFk`), KEY `value` (`value`), @@ -35178,6 +34601,12 @@ DELIMITER ;; -- Edit trigger body code below this line. Do not edit lines above this one BEGIN + IF NEW.itemPackingTypeFk = '' THEN + + SET NEW.itemPackingTypeFk = NULL; + + END IF; + IF NEW.itemPackingTypeFk != OLD.itemPackingTypeFk THEN UPDATE vn.item @@ -36226,7 +35655,7 @@ CREATE TABLE `packingSite__` ( PRIMARY KEY (`code`), KEY `packingSite_FK` (`hostFk`), KEY `packingSite_FK_1` (`printerFk`), - CONSTRAINT `packingSite_FK` FOREIGN KEY (`hostFk`) REFERENCES `vn2008`.`config_host` (`config_host_id`), + CONSTRAINT `packingSite_FK` FOREIGN KEY (`hostFk`) REFERENCES `vn2008`.`config_host__` (`config_host_id`), CONSTRAINT `packingSite_FK_1` FOREIGN KEY (`printerFk`) REFERENCES `printer` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -37068,6 +36497,7 @@ CREATE TABLE `producer` ( `id` mediumint(3) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, `isVisible` tinyint(1) NOT NULL DEFAULT '1', + `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -38985,6 +38415,28 @@ CREATE TABLE `sector` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `sectorProductivity` +-- + +DROP TABLE IF EXISTS `sectorProductivity`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `sectorProductivity` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) DEFAULT NULL, + `firstName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `lastName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `sector` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL, + `ticketCount` int(11) DEFAULT NULL, + `saleCount` int(11) DEFAULT NULL, + `volume` decimal(10,6) DEFAULT NULL, + `hourWorked` decimal(10,2) DEFAULT NULL, + `dated` date 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 `sharingCart` -- @@ -40502,26 +39954,31 @@ CREATE TABLE `ticketCollection` ( /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER ticketCollection_AFTER_DELETE +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`localhost`*/ /*!50003 TRIGGER ticketCollection_afterDelete AFTER DELETE ON ticketCollection FOR EACH ROW BEGIN - DECLARE vTicketsInCollection INT; + DECLARE vSalesRemaining INT; - SELECT count(*) INTO vTicketsInCollection - FROM vn.ticketCollection tc + SELECT count(*) INTO vSalesRemaining + FROM vn.ticketCollection tc + JOIN sale s ON s.ticketFk = tc.ticketFk WHERE collectionFk = OLD.collectionFk AND tc.id != OLD.id; - IF vTicketsInCollection = 0 THEN + IF NOT vSalesRemaining THEN DELETE FROM vn.collection WHERE id = OLD.collectionFk; + ELSE + + UPDATE vn.collection + SET saleTotalCount = vSalesRemaining + WHERE id = OLD.collectionFk; + END IF; - - -- CALL vn.ticketStateUpdate(OLD.ticketFk, 'OK'); - + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -50654,20 +50111,32 @@ proc: BEGIN END IF; CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); + CALL vn.buyUltimate (vWarehouseFk, vShipped); INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), + a.item_id, + IFNULL(a.available, 0), bu.buyFk, vZoneFk - 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 i.available > 0; + FROM `cache`.available a + JOIN vn.address a ON a.id = @addressFk + JOIN vn.province p ON p.id = a.provinceFk + JOIN vn.item i ON i.id = a.item_id + JOIN vn.addressFilter af + LEFT JOIN edi.supplyOffer so ON so.srId = i.supplyResponseFk + LEFT JOIN edi.VMPSettings v ON v.VMPID = so.vmpID + LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = a.item_id + WHERE a.calc_id = vAvailableCalc + AND a.available > 0 + AND i.supplyResponseFk + AND (IFNULL(af.isEarlyBird,so.isEarlyBird) = so.isEarlyBird OR ISNULL(so.isEarlyBird)) + AND (IFNULL(af.isVNHSupplier,so.isVNHSupplier ) = so.isVNHSupplier OR ISNULL(so.isVNHSupplier)) + AND af.warehouseFk = vWarehouseFk + AND (ISNULL(af.provinceFk) OR af.provinceFk = a.provinceFk) + AND (ISNULL(af.countryFk) OR af.countryFk = p.countryFk) + AND (ISNULL(af.isLogifloraAllowed) OR af.isLogifloraAllowed = a.isLogifloraAllowed) + ; DROP TEMPORARY TABLE tmp.buyUltimate; @@ -50729,9 +50198,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 ;; @@ -50778,7 +50247,7 @@ proc: BEGIN DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; DECLARE vIsCatalonianBuyer BOOL; DECLARE visAnyVolumeAllowed BOOL; - + SELECT (COUNT(*) > 0) INTO vIsZonePremium FROM vn.zoneFilter zf WHERE zf.zoneFk = vZoneFk; @@ -50790,7 +50259,7 @@ proc: BEGIN FROM address WHERE id = vAddressFk; - SELECT (c.country = 'FRANCIA' AND vWarehouseFk IN (vVNHWarehouseFk, vFloramondoWarehouseFk)) + SELECT (c.country IN ('Francia','Suiza') AND vWarehouseFk IN (vVNHWarehouseFk, vFloramondoWarehouseFk)) INTO vIsFrenchVNHBuyer FROM vn.country c JOIN vn.province p ON p.countryFk = c.id @@ -50806,14 +50275,14 @@ proc: BEGIN SELECT travellingDays INTO vMaxLogifloraDays FROM edi.warehouseFloramondo WHERE warehouseFk = vWarehouseFk; - + -- Se eliminan los productos de tamaños no convencionales, salvo agencias que lo permitan SELECT a.isAnyVolumeAllowed INTO visAnyVolumeAllowed FROM vn.agency a JOIN vn.agencyMode am ON am.agencyFk = a.id JOIN vn.`zone`z ON z.agencyModeFk = am.id WHERE z.id = vZoneFk; - + IF NOT vIsAnyVolumeAllowed THEN DELETE tl.* @@ -50823,7 +50292,7 @@ proc: BEGIN WHERE it.isUnconventionalSize; END IF; - + -- Esto sirve para que los franceses compren sólo por las cuentas de VNH DELETE tl.* FROM tmp.ticketLot tl @@ -50861,7 +50330,7 @@ proc: BEGIN AND vWarehouseFk = tl.warehouseFk); END IF; - + -- Eliminem productes de la oferta que no deuen vore els francesos IF vIsFrenchVNHBuyer THEN @@ -50904,7 +50373,7 @@ proc: BEGIN JOIN item i ON i.id = tl.itemFk JOIN vn.zone z ON z.id = vZoneFk WHERE i.size > z.itemMaxSize; - + SET @rate2 := 0; SET @rate3 := 0; SET @minPrice := 0; @@ -50963,7 +50432,7 @@ proc: BEGIN tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue FROM tmp.ticketComponentCalculate tcc JOIN buy b ON b.id = tcc.buyFk; - + -- Promo Francia IF vIsFrenchVNHBuyer THEN @@ -50984,7 +50453,7 @@ proc: BEGIN FROM tmp.ticketComponent tc JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk GROUP BY tc.itemFk, warehouseFk; - + -- RECOBRO INSERT INTO tmp.ticketComponent(warehouseFk, itemFk, componentFk, cost) SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, @@ -51006,7 +50475,7 @@ proc: BEGIN JOIN workerMana wm ON c.salesPersonFk = wm.workerFk WHERE wm.isPricesModifierActivated HAVING manaAuto <> 0; - + -- Precios especiales INSERT INTO tmp.ticketComponent SELECT tcb.warehouseFk, @@ -51068,7 +50537,7 @@ proc: BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY SELECT * FROM tmp.ticketComponent; - + -- Precio especial INSERT INTO tmp.ticketComponent SELECT tcc.warehouseFk, @@ -51204,31 +50673,16 @@ proc: BEGIN * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) */ DECLARE vClientFk INT; - -- DECLARE vMinimumDensityWeight INT DEFAULT 167; - -- DECLARE vBoxVolume BIGINT; - -- 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; - -- DECLARE vFrenchOffer INT DEFAULT 42; DECLARE vIsFrenchVNHBuyer BOOLEAN DEFAULT FALSE; DECLARE vVNHWarehouseFk INT DEFAULT 7; - -- DECLARE vFloramondoWarehouseFk INT DEFAULT 40; DECLARE vIsLogifloraAllowed BOOLEAN DEFAULT 0; - -- DECLARE vMaxLogifloraDays INT; - -- DECLARE vRangeLogifloraDays INT DEFAULT 3; DECLARE vVisibleCache INT; - -- DECLARE vRappelComponent INT DEFAULT 44; DECLARE vIsZonePremium BOOL; DECLARE vFrenchDiscount DECIMAL(3,2) DEFAULT 0.12; - -- DECLARE vIsCatalonianBuyer BOOL; DECLARE visAnyVolumeAllowed BOOL; + SELECT * FROM tmp.ticketLot; + SELECT (COUNT(*) > 0) INTO vIsZonePremium FROM vn.zoneFilter zf WHERE zf.zoneFk = vZoneFk; @@ -51246,15 +50700,8 @@ proc: BEGIN JOIN vn.province p ON p.countryFk = c.id JOIN vn.address a ON a.provinceFk = p.id WHERE a.id = vAddressFk; - /* - SELECT (p.name = 'Barcelona' AND vWarehouseFk = vVNHWarehouseFk) - INTO vIsCatalonianBuyer - FROM vn.province p - JOIN vn.address a ON a.provinceFk = p.id - WHERE a.id = vAddressFk; -- PAK 18/10/21 - */ - - + + /* -- Se eliminan los productos de tamaños no convencionales, salvo agencias que lo permitan SELECT a.isAnyVolumeAllowed INTO visAnyVolumeAllowed FROM vn.agency a @@ -51289,7 +50736,6 @@ proc: BEGIN DELETE tl FROM tmp.ticketLot tl JOIN item i ON i.id = tl.itemFk - -- LEFT JOIN cache.last_buy lb ON lb.item_id = i.id AND lb.warehouse_id = vWarehouseFk LEFT JOIN vn.buy b ON b.id = tl.buyFk LEFT JOIN vn.entry e ON e.id = b.entryFk LEFT JOIN vn.supplier s ON s.id = e.supplierFk @@ -51351,7 +50797,7 @@ proc: BEGIN JOIN item i ON i.id = tl.itemFk JOIN vn.zone z ON z.id = vZoneFk WHERE i.size > z.itemMaxSize; - + */ SET @rate2 := 0; SET @rate3 := 0; SET @minPrice := 0; @@ -51617,6 +51063,8 @@ proc: BEGIN SELECT * FROM tmp.ticketComponentRate ORDER BY price ) t GROUP BY itemFk, warehouseFk, `grouping`; + + SELECT * FROM tmp.ticketComponentPrice; DROP TEMPORARY TABLE tmp.ticketComponentCalculate, @@ -53601,11 +53049,11 @@ BEGIN INSERT INTO tmp.sale(ticketFk, saleFk, itemFk, isStowaway) SELECT s.ticketFk, s.id, s.itemFk, FALSE FROM vn.ticketCollection tc - JOIN vn.collection c ON c.id = tc.collectionFk + -- JOIN vn.collection c ON c.id = tc.collectionFk JOIN vn.sale s ON s.ticketFk = tc.ticketFk - JOIN vn.item i ON i.id = s.itemFk + -- JOIN vn.item i ON i.id = s.itemFk WHERE tc.collectionFk = vParamFk - AND (i.itemPackingTypeFk = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) + -- AND (IFNULL(i.itemPackingTypeFk,c.itemPackingTypeFk) = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) UNION ALL SELECT s.ticketFk, s.id, s.itemFk, FALSE FROM vn.sale s @@ -55243,8 +54691,7 @@ proc:BEGIN AND s.isPreparable AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) - OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) - OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)); + OR pb.N > 0 AND ISNULL(pb.collectionH)); SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; -- AutoPRINT @@ -55267,8 +54714,7 @@ proc:BEGIN AND s.isOK AND (pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) - OR pb.F > 0 AND vItemPackingTypeFk = 'F' AND ISNULL(pb.collectionF) - OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + OR pb.N > 0 AND ISNULL(pb.collectionH)) AND t.created < TIMESTAMPADD(MINUTE, - tc.pickingDelay , NOW()) ORDER BY HH, mm, @@ -55290,8 +54736,7 @@ proc:BEGIN JOIN vn.ticketStateToday tst ON tst.ticket = pb.ticketFk JOIN vn.state s ON s.id = tst.state WHERE ( pb.H > 0 AND vItemPackingTypeFk = 'H' AND ISNULL(pb.collectionH) - OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV) - OR pb.P > 0 AND vItemPackingTypeFk = 'P' AND ISNULL(pb.collectionP)) + OR pb.V > 0 AND vItemPackingTypeFk = 'V' AND ISNULL(pb.collectionV)) AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) AND LENGTH(pb.problem) = 0 AND s.isPreparable @@ -59939,6 +59384,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 `entry_clone` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = 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 `entry_clone`(vSelf INT) +BEGIN + + /* Clona una entrada + * + * @param vSelf Identificador de vn.entry + */ + + DECLARE vEntryFk INT; + + INSERT INTO vn.entry(supplierFk, dated, isInventory, notes, isRaid, commission, travelFk, currencyFk, + companyFk, loadPriority ) + SELECT supplierFk, dated, isInventory, notes, isRaid, commission, travelFk, currencyFk, + companyFk, loadPriority + FROM vn.entry e + WHERE e.id = vSelf; + + SET vEntryFk = LAST_INSERT_ID(); + + INSERT INTO vn.buy(entryFk, itemFk, quantity, buyingValue, freightValue, isIgnored, stickers, packing, `grouping`, groupingMode, containerFk, comissionValue, packageValue, packageFk, price1, price2, price3, minPrice, producer, workerFk, weight, itemOriginalFk ) + SELECT vEntryFk, itemFk, quantity, buyingValue, freightValue, isIgnored, stickers, packing, `grouping`, groupingMode, containerFk, comissionValue, packageValue, packageFk, price1, price2, price3, minPrice, producer, workerFk, weight, itemOriginalFk + FROM vn.buy b + WHERE b.entryFk = vSelf; + + SELECT vEntryFk; + +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 `entry_fixMisfit` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -64777,6 +64264,10 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `itemCard`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT, IN isBarcode BOOL) BEGIN + + /* + * @deprecated: Utilizar item_getInfo + */ DECLARE vCacheVisibleFk INT; DECLARE vCacheAvailableFk INT; @@ -68944,6 +68435,88 @@ BEGIN ORDER BY shipped, alertLevel DESC, isTicket, `order` DESC, isPicked DESC, `in` DESC, `out` DESC ) AS itemDiary; +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 `item_getInfo` */; +/*!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 `item_getInfo`(IN `vBarcode` VARCHAR(22), IN `vWarehouseFk` INT) +BEGIN + + /* + * Devuelve información relativa al item correspondiente del vBarcode pasado + * + * @param vBarcode código relativo al ítem + * @param vWarehouseFk código del almacén + */ + + DECLARE vCacheVisibleFk INT; + DECLARE vCacheAvailableFk INT; + DECLARE vVisibleItemShelving INT; + DECLARE vItemFk INT; + + SELECT vn.barcodeToItem(vBarcode) INTO vItemFk; + + CALL cache.visible_refresh(vCacheVisibleFk, FALSE,vWarehouseFk); + CALL cache.available_refresh(vCacheAvailableFk, FALSE,vWarehouseFk, CURDATE()); + + SELECT SUM(visible) INTO vVisibleItemShelving + FROM vn.itemShelvingStock + WHERE itemFk = vItemFk AND warehouseFk = vWarehouseFk; + + CALL vn.buyUltimate(vWarehouseFk, CURDATE()); + + SELECT i.id, + i.longName, + i.tag5, + i.value5, + i.tag6, + i.value6, + i.tag7, + i.value7, + i.image, + i.size, + i.stems, + i.category, + i.minimum as min, + p.name as producer, + o.code as origin, + v.visible - IFNULL(vVisibleItemShelving,0) as unlocated, + a.available, + vVisibleItemShelving, + v.visible, + c.`grouping`, + c.packing, + CONCAT('https://verdnatura.es/vn-image-data/catalog/200x200/', i.image) as urlImage200, + CONCAT('https://verdnatura.es/vn-image-data/catalog/1600x900/', i.image) as urlImage, + i.itemPackingTypeFk, + i.comment as reference + FROM vn.item i + LEFT JOIN vn.producer p ON p.id = i.producerFk + LEFT JOIN vn.origin o ON o.id = i.originFk + LEFT JOIN cache.visible v ON v.calc_id = vCacheVisibleFk AND v.item_id = i.id + LEFT JOIN cache.available a ON a.calc_id = vCacheAvailableFk AND a.item_id = i.id + LEFT JOIN ( + SELECT b.itemFk, b2.`grouping`, b2.packing + FROM tmp.buyUltimate b + JOIN vn.buy b2 ON b2.id = b.buyFk + WHERE b.warehouseFk = vWarehouseFk + ) c ON i.id = c.itemFk + WHERE i.id = vItemFk; + + DROP TEMPORARY TABLE tmp.buyUltimate; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -69505,6 +69078,13 @@ BEGIN SET i.stems = it.`value` WHERE i.id = vItemFk; + -- Al insertar el tag categoria se modifica también en la tabla item + UPDATE item i + JOIN tag t ON t.overwrite = 'category' + JOIN itemTag it ON it.itemFk = i.id AND it.tagFk = t.id + SET i.category = it.`value` + WHERE i.id = vItemFk; + -- Comprueba si existe un genérico y lo asigna CALL vn.item_setGeneric(vItemFk); @@ -70132,9 +69712,9 @@ BEGIN JOIN warehouse wOut ON wOut.id = tr.warehouseOutFk WHERE vDated >= tr.shipped AND vDated < tr.landed AND NOT isRaid - -- AND wIn.valuatedInventory + AND wIn.valuatedInventory AND t.isInventory - -- AND e.isConfirmed + AND e.isConfirmed ON DUPLICATE KEY UPDATE inv.cantidad = inv.cantidad + (b.quantity); CALL vn.buyUltimate(NULL,vDateDayEnd); @@ -72887,6 +72467,226 @@ proc: BEGIN CREATE TEMPORARY TABLE tmp.ticket SELECT * FROM tmp.productionTicket; + CALL vn.prepareClientList(); + + DROP TEMPORARY TABLE IF EXISTS tmp.sale_getProblems; + CREATE TEMPORARY TABLE tmp.sale_getProblems + (INDEX (ticketFk)) ENGINE = MEMORY + SELECT tt.ticketFk, tt.clientFk, t.warehouseFk, t.shipped + FROM tmp.productionTicket tt + JOIN vn.ticket t ON t.id = tt.ticketFk; + + CALL vn.ticket_getProblems(vIsTodayRelative); + + DROP TEMPORARY TABLE IF EXISTS tmp.productionBuffer; + CREATE TEMPORARY TABLE tmp.productionBuffer + (PRIMARY KEY(ticketFk)) + ENGINE = MEMORY + SELECT tt.ticketFk + , tt.clientFk + , t.warehouseFk + , t.nickname + , t.packages + , IF(HOUR(t.shipped), HOUR(t.shipped), IFNULL(HOUR(zc.hour),HOUR(z.hour))) as HH + , IFNULL(HOUR(zc.hour),HOUR(z.hour)) as Departure + , IF(MINUTE(t.shipped), MINUTE(t.shipped), IFNULL(MINUTE(zc.hour), MINUTE(z.hour))) as mm + , t.routeFk + , IF(am.deliveryMethodFk = 2,z.`id`,0) as zona + , t.nickname addressNickname + , a.postalCode + , a.city + , p.name province + , CONCAT(z.`name`,' ',IFNULL(RIGHT(t.routeFk,3),'')) agency + , am.id agencyModeFk + , 0 AS `lines` + , CAST( 0 AS DECIMAL(5,2)) AS m3 + , CAST( 0 AS DECIMAL(5,2)) AS preparationRate + , "" as problem + , IFNULL(tls.state,2) AS state + , w.code workerCode + , DATE(t.shipped) shipped + , wk.code AS salesPersonCode + , p.id provinceFk + , tls.productionOrder + , ifnull(tls.alertLevel,0) alertLevel + , t.isBoxed as palletized + , IF(rm.isPickingAllowed ,rm.bufferFk, NULL) ubicacion + , tlu.lastUpdated + , ifnull(st.graphCategory,0) graphCategory + , pk.code as parking + , 0 AS H + , 0 AS V + , 0 AS N + , st.isOk + , ag.isOwn + FROM tmp.productionTicket tt + JOIN vn.ticket t on tt.ticketFk = t.id + LEFT JOIN vn.ticketStateToday tst ON tst.ticket = t.id + LEFT JOIN vn.state st ON st.id = tst.state + LEFT JOIN vn.client c ON c.id = t.clientFk + LEFT JOIN vn.worker wk ON wk.id = c.salesPersonFk + JOIN vn.address a on a.id = t.addressFk + LEFT JOIN vn.province p on p.id = a.provinceFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.agency ag ON ag.id = am.agencyFk + LEFT JOIN vn.ticketState tls on tls.ticket = tt.ticketFk + LEFT JOIN vn.ticketLastUpdated tlu ON tlu.ticketFk = tt.ticketFk + LEFT JOIN vn.worker w on w.id = tls.worker + LEFT JOIN vn.routesMonitor rm ON rm.routeFk = t.routeFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN vn.zoneClosure zc ON zc.zoneFk = t.zoneFk AND date(t.shipped) = zc.dated + LEFT JOIN vn.ticketParking tp ON tp.ticketFk = t.id + LEFT JOIN vn.parking pk ON pk.id = tp.parkingFk + WHERE t.warehouseFk = vWarehouseFk + AND am.deliveryMethodFk IN (1,2,3); + + ALTER TABLE tmp.productionBuffer + CHANGE COLUMN `problem` `problem` VARCHAR(255), + ADD COLUMN `collectionH` INT, + ADD COLUMN `collectionV` INT; + + -- Líneas y volumen por ticket + UPDATE tmp.productionBuffer pb + JOIN ( + SELECT tt.ticketFk, + COUNT(*) as `lines`, + sum(sv.volume) as m3, + IFNULL(sum(IF(sv.isPicked,sv.volume,0)) / sum(sv.volume),0) as rate + FROM tmp.productionTicket tt + JOIN vn.saleVolume sv on sv.ticketFk = tt.ticketFk + GROUP BY tt.ticketFk + ) m on m.ticketFk = pb.ticketFk + SET pb.`lines` = m.`lines`, + pb.m3 = m.m3, + pb.preparationRate = m.rate; + + DELETE FROM tmp.productionBuffer + WHERE `lines`= 0; + + -- Lineas por linea de encajado + UPDATE tmp.productionBuffer pb + JOIN ( SELECT ticketFk, + sum(sub.H) H, + sum(sub.V) V, + sum(sub.N) N + FROM ( + SELECT t.ticketFk, + sum(i.itemPackingTypeFk = 'H') H, + sum(i.itemPackingTypeFk = 'V') V, + sum(ISNULL(i.itemPackingTypeFk)) N + FROM tmp.productionTicket t + JOIN vn.sale s ON s.ticketFk = t.ticketFk + JOIN vn.item i ON i.id = s.itemFk + GROUP BY t.ticketFk, i.itemPackingTypeFk) sub + GROUP BY ticketFk + ) sub2 ON sub2.ticketFk = pb.ticketFk + SET pb.H = sub2.H, + pb.V = sub2.V, + pb.N = sub2.N; + + -- Colecciones segun tipo de encajado + UPDATE tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk + JOIN vn.collection c ON c.id = tc.collectionFk + SET pb.collectionH = c.id + WHERE c.itemPackingTypeFk = 'H' OR ISNULL(c.itemPackingTypeFk); + + UPDATE tmp.productionBuffer pb + JOIN vn.ticketCollection tc ON pb.ticketFk = tc.ticketFk + JOIN vn.collection c ON c.id = tc.collectionFk + SET pb.collectionV = c.id + WHERE c.itemPackingTypeFk = 'V' OR ISNULL(c.itemPackingTypeFk); + + -- Cajas + ALTER TABLE tmp.productionBuffer + ADD Cajas DOUBLE DEFAULT NULL; + + -- Problemas por ticket + UPDATE tmp.productionBuffer pb + JOIN tmp.ticket_problems tp ON tp.ticketFk = pb.ticketFk + SET pb.problem = TRIM(CAST(CONCAT( IFNULL(tp.itemShortage,''), + IFNULL(tp.itemDelay,''), + IF(tp.isFreezed,' CONGELADO',''), + IF(tp.hasHighRisk,' RIESGO',''), + IF(tp.hasTicketRequest, ' COD 100',''), + IF(tp.isTaxDataChecked, '',' FICHA INCOMPLETA'), + IF(tp.hasComponentLack,' COMPONENTES', ''), + IF(tp.isTooLittle,' PEQUEÑO', '') + ) as char(255))); + + -- Refresca la caché para el cierre dinámico de agencias + -- CALL cache.departure_timing(vWarehouseFk); +/* + -- Tickets de recogida + REPLACE tmp.productionBuffer( + shipped + , ticketFk + , agency + , clientFk + , addressNickname + , state + , workerCode + , alertLevel + , warehouseFk + ) + SELECT DATE(t.shipped) + , t.id + , am.name + , t.clientFk + , a.nickname + , s.id as state + , w.code + , ifnull(tls.alertLevel,0) alert_level + , vWarehouseFk + FROM vn.ticket t + JOIN vn.address a on a.id = t.addressFk + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + LEFT JOIN vn2008.warehouse_pickup wp ON wp.agency_id = am.id + LEFT JOIN vn.ticketState tls on tls.ticket = t.id + LEFT JOIN vn.state s ON s.id = tls.state + LEFT JOIN vn.worker w on w.id = tls.worker + WHERE t.shipped between TIMESTAMPADD(WEEK,-1,CURDATE()) AND util.dayend(TIMESTAMPADD(DAY,-1,CURDATE())) + AND wp.warehouse_id = vWarehouseFk; +*/ + DROP TEMPORARY TABLE tmp.productionTicket; + DROP TEMPORARY TABLE tmp.ticket; + DROP TEMPORARY TABLE IF EXISTS tmp.risk; + +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 `productionControl__` */; +/*!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 `productionControl__`(vWarehouseFk INT, vScopeDays INT) +proc: BEGIN + + DECLARE vEndingDate DATETIME DEFAULT TIMESTAMPADD(DAY,vScopeDays,util.dayEnd(CURDATE())); + + DECLARE vIsTodayRelative BOOLEAN; + + CALL util.debugAdd('vn.productionControl',CONCAT('warehouse: ',vWarehouseFk,' scopeDays:',vScopeDays)); + + SELECT isTodayRelative INTO vIsTodayRelative + FROM vn.worker + WHERE userFk = vn.getUser(); + + CALL vn.prepareTicketList(TIMESTAMPADD(DAY,-1,CURDATE()), vEndingDate); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT * FROM tmp.productionTicket; + CALL vn.prepareClientList(); /* DROP TEMPORARY TABLE IF EXISTS tmp.ticketGetProblems; @@ -73171,7 +72971,9 @@ BEGIN JOIN vn.item i ON i.id = isa.itemFk JOIN vn.sector s ON s.id = isa.sectorFk AND s.warehouseFk = isa.warehouseFk - AND i.itemPackingTypeFk = IFNULL(s.itemPackingTypeFk , i.itemPackingTypeFk) + AND (i.itemPackingTypeFk = s.itemPackingTypeFk + -- OR ISNULL(i.itemPackingTypeFk) + OR ISNULL(s.itemPackingTypeFk)) JOIN vn.ticket t ON t.id = isa.ticketFk JOIN vn.client c ON c.id = t.clientFk JOIN tmp.productionBuffer pb ON pb.ticketFk = t.id @@ -73787,66 +73589,68 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `reportLabelCollection_get`(vCollectionFk INT) BEGIN - +/** + * Obtiene los datos necesarios de una colección + * + * @param vCollectionFk La colección de la que sacar los datos + **/ DECLARE vItemPackingTypeFk VARCHAR(1); -- Si los sacadores NO son de V, pinta los colores SELECT c.itemPackingTypeFk INTO vItemPackingTypeFk - FROM vn.collection c - WHERE c.id = vCollectionFk; + FROM vn.collection c + WHERE c.id = vCollectionFk; - IF !(vItemPackingTypeFk <=> 'V') THEN + IF !(vItemPackingTypeFk <=> 'V') THEN - SELECT * FROM ( - SELECT CONCAT(tc.collectionFk,' ',LEFT(cc.code,4)) `level`, - tc.ticketFk, + SELECT * FROM ( + SELECT CONCAT(tc.collectionFk,' ',LEFT(cc.code,4)) `level`, + tc.ticketFk, LEFT(IF(t.routeFk IS null, am.name, zo.name ),12) agencyDescription, am.name, - t.clientFk, + t.clientFk, count(*) notes, w.code workerCode, tt.labelCount, IF(HOUR(t.shipped),TIME(t.shipped),TIME(zo.HOUR)) AS horaagencia, - t.shipped, - count(*) AS lineas, - t.nickName, - CONCAT(CAST(sv.litros / 1000 AS DECIMAL(5,2)), 'm3') m3 - FROM vn.ticket t + t.shipped, + count(*) lineas, + t.nickName, + CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5,2)) , "m³") m3 + FROM vn.ticket t JOIN vn.ticketCollection tc ON tc.ticketFk = t.id - JOIN vn.collection c ON c.id = tc.collectionFk - JOIN vn.collectionColors cc - ON cc.shelve = tc.`level` - AND cc.wagon = tc.wagon - AND cc.trainFk = c.trainFk + JOIN vn.collection c ON c.id = tc.collectionFk + JOIN vn.collectionColors cc + ON cc.shelve = tc.`level` + AND cc.wagon = tc.wagon + AND cc.trainFk = c.trainFk JOIN vn.sale s ON s.ticketFk = t.id LEFT JOIN vn.saleVolume sv ON sv.saleFk = s.id - JOIN vn.worker w ON w.id = c.workerFk + JOIN vn.worker w ON w.id = c.workerFk JOIN vn.agencyMode am ON am.id = t.agencyModeFk LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id LEFT JOIN vn.address a ON a.id = t.addressFk LEFT JOIN vn.route r ON r.id = t.routeFk - LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk - LEFT JOIN vn.agencyMode agm on r.agencyModeFk =agm.id - LEFT JOIN vn.zone zo ON t.zoneFk = zo.id + LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk + LEFT JOIN vn.agencyMode agm ON r.agencyModeFk =agm.id + LEFT JOIN vn.zone zo ON t.zoneFk = zo.id WHERE tc.collectionFk = vCollectionFk - GROUP BY t.id) sub + GROUP BY t.id) sub ORDER BY `level`; - - ELSE - - SELECT CONCAT(tc.collectionFk,' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-',tc.level) `level`, + ELSE + SELECT CONCAT(tc.collectionFk,' ', SUBSTRING('ABCDEFGH',tc.wagon, 1), '-',tc.level) `level`, tc.ticketFk, LEFT(IF(t.routeFk IS null, am.name, zo.name ),12) agencyDescription, am.name, t.clientFk, - CAST(IF(ic.code = 'plant', CONCAT(MAX(i.size),' cm'),count(*)) AS CHAR) notes, + CAST(IF(ic.code = 'plant', CONCAT(MAX(i.size),' cm'),count(*)) AS CHAR) notes, w.code workerCode, tt.labelCount, - IF(HOUR(t.shipped),TIME(t.shipped),TIME(zo.HOUR)) as horaagencia, + IF(HOUR(t.shipped),TIME(t.shipped),TIME(zo.HOUR)) horaagencia, t.shipped, - count(*) AS lineas, + count(*) lineas, t.nickName, - CONCAT(CAST(sv.litros / 1000 AS DECIMAL(5,2)), 'm3') m3 + CONCAT(CAST(SUM(sv.volume) AS DECIMAL(5,2)) , "m³") m3 FROM vn.ticket t JOIN vn.ticketCollection tc ON tc.ticketFk = t.id JOIN vn.collection c ON c.id = tc.collectionFk @@ -73859,15 +73663,13 @@ BEGIN JOIN vn.agencyMode am on am.id = t.agencyModeFk LEFT JOIN vn.ticketTrolley tt ON tt.ticket = t.id LEFT JOIN vn.address a ON a.id = t.addressFk - LEFT JOIN vn.route r on r.id = t.routeFk + LEFT JOIN vn.route r ON r.id = t.routeFk LEFT JOIN vn.zoneEstimatedDelivery ze ON ze.zoneFk = t.zoneFk - LEFT JOIN vn.agencyMode agm on r.agencyModeFk =agm.id + LEFT JOIN vn.agencyMode agm ON r.agencyModeFk =agm.id LEFT JOIN vn.zone zo ON t.zoneFk = zo.id WHERE tc.collectionFk = vCollectionFk GROUP BY t.id; - END IF; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -75852,6 +75654,7 @@ BEGIN MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) as isPreviousPrepared, MAX(IF(st.semaphore <=> 2, TRUE, FALSE)) as isPrepared, MAX(IF(st.semaphore <=> 3, TRUE, FALSE)) as isControlled, + MAX(IF(st.semaphore <=> 4, TRUE, FALSE)) as isPreControlled, ic.color, ip.productor, s.discount, @@ -75877,7 +75680,7 @@ BEGIN str.originalQuantity as startQuantity, -- eliminar cuando tengamos la nueva apk IFNULL(c.workerFk,getUser()) as workerFk, IFNULL(SUM(iss.quantity),0) as pickedQuantity, - i.packingShelve -- PAk 21/12/21 + i.packingShelve FROM vn.sale s JOIN tmp.ticket t ON t.id = s.ticketFk JOIN vn.ticket tt ON tt.id = t.id @@ -75895,7 +75698,7 @@ BEGIN LEFT JOIN vn.saleGroupDetail sgd ON sgd.saleFk = s.id LEFT JOIN vn.saleGroup sg ON sg.id = sgd.saleGroupFk LEFT JOIN vn.parking p ON p.id = sg.parkingFk - WHERE (i.itemPackingTypeFk = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) + -- WHERE (i.itemPackingTypeFk = c.itemPackingTypeFk OR ISNULL(c.itemPackingTypeFk)) GROUP BY s.id; DROP TEMPORARY TABLE tmp.ticket; @@ -76584,7 +76387,7 @@ proc: BEGIN LEAVE l; END IF; - SELECT t.refFk IS NULL AND (IFNULL(ts.alertLevel, 0) = 0 OR s.price = 0), + SELECT t.refFk IS NULL, s.ticketFk, s.itemFk , t.zoneFk, @@ -76801,7 +76604,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 `sectorProductivity` */; +/*!50003 DROP PROCEDURE IF EXISTS `sectorProductivity_add` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -76811,7 +76614,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `sectorProductivity`() +CREATE DEFINER=`root`@`%` PROCEDURE `sectorProductivity_add`() BEGIN DECLARE vDatedFrom DATETIME; @@ -76821,13 +76624,14 @@ BEGIN CALL timeControl_calculateAll(vDatedFrom, vDatedTo); - SELECT sub.*, SUM(wp.volume) volume, IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) AS hourWorked + INSERT INTO sectorProductivity(workerFk, firstName, lastName, sector, ticketCount, saleCount, volume, hourWorked, dated) + SELECT sub.*, SUM(wp.volume) volume, IFNULL(CAST(tc.timeWorkDecimal AS DECIMAL (10,2)) , 0) AS hourWorked, DATE(vDatedFrom) dated FROM( SELECT w.id workerFk, w.firstName, - w.lastName, - se.description, - COUNT(DISTINCT t.id) ticketCount, + w.lastName, + se.description sector, + COUNT(DISTINCT t.id) ticketCount, COUNT(st.saleFk) saleCount FROM vn.saleTracking st JOIN vn.worker w ON w.id = st.workerFk @@ -76839,9 +76643,9 @@ BEGIN AND se.code IN ('ALGEMESI ARTIFI','COMPLEMENTOS') GROUP BY w.id ) sub + LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = sub.workerFk LEFT JOIN bs.workerProductivity wp ON wp.workerFk = sub.workerFk - LEFT JOIN tmp.timeControlCalculate tc ON tc.userFk = sub.workerFk - WHERE wp.dated > vDatedFrom + WHERE wp.dated = vDatedFrom GROUP BY sub.workerFk; END ;; @@ -80970,6 +80774,9 @@ DELIMITER ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateToday_setOnchecking`(vParamFk INT) BEGIN + /* + * @deprecated:utilizar ticketStateToday_setState + */ DECLARE vAlertLevel INT; @@ -81004,6 +80811,11 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateToday_setOnPreviousChecking`(vParamFk INT) BEGIN + /* + * @deprecated:utilizar ticketStateToday_setState + */ + + /* * Cambia el estado del ticket al estado de "control previa" * @@ -81024,6 +80836,46 @@ BEGIN 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 `ticketStateToday_setState` */; +/*!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 `ticketStateToday_setState`(vTicketFk INT, vStateCode VARCHAR(45)) +BEGIN + + /* Modifica el estado de un ticket de hoy + * + * @param vTicketFk el id del ticket + * @param vStateCode estado a modificar del ticket + * + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM state s + JOIN ticketStateToday tst ON tst.state = s.id + WHERE tst.ticket = vTicketFk + LIMIT 1; + + IF vAlertLevel < 2 THEN + + CALL vn.ticket_setState(vTicketFk, vStateCode); + + END IF; + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -81038,11 +80890,15 @@ DELIMITER ; /*!50003 SET character_set_results = utf8mb4 */ ; /*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION' */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `ticketStateUpdate`(vTicketFk INT, vStateCode VARCHAR(45)) BEGIN + /* + * @deprecated:utilizar ticket_setState + */ + DECLARE vAlertLevel INT; SELECT s.alertLevel INTO vAlertLevel @@ -81259,7 +81115,6 @@ BEGIN UPDATE vn.saleTracking st JOIN vn.state s ON s.code = 'OK PREVIOUS' - JOIN vncontrol.accion a ON a.accion_id = st.actionFk JOIN vn.state s2 ON s2.id = st.stateFk SET st.stateFk = s.id WHERE workerFk = vn.getUser() @@ -81279,8 +81134,8 @@ BEGIN SELECT s.ticketFk, s.itemFk, i.longName, - i.itemPackingTypeFk, - i.subName, + IFNULL(i.itemPackingTypeFk,' ') itemPackingTypeFk, + IFNULL(i.subName ,' ') subName, s.quantity originalQuantity , s.quantity, w.code workerCode, @@ -84210,6 +84065,47 @@ 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 `ticket_setState` */; +/*!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 `ticket_setState`(vTicketFk INT, vStateCode VARCHAR(45)) +BEGIN + + /* Modifica el estado de un ticket + * + * @param vTicketFk el id del ticket + * @param vStateCode estado a modificar del ticket + * + */ + + DECLARE vAlertLevel INT; + + SELECT s.alertLevel INTO vAlertLevel + FROM vn.state s + JOIN vn.ticketState ts ON ts.stateFk = s.id + WHERE ts.ticketFk = vTicketFk; + + IF !(vStateCode = 'ON_CHECKING' AND vAlertLevel > 1) THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT id, vTicketFk, account.myUser_getId() + FROM vn.state + WHERE `code` = vStateCode collate utf8_unicode_ci; + + 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 `ticket_splitItemPackingType` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -84316,6 +84212,7 @@ proc:BEGIN SELECT itemPackingTypeFk INTO vItemPackingTypeFk FROM tmp.saleGroup sg + WHERE NOT ISNULL(sg.itemPackingTypeFk) ORDER BY sg.totalLitros LIMIT 1; @@ -84330,215 +84227,6 @@ proc:BEGIN DROP TEMPORARY TABLE tmp.sale; DROP TEMPORARY TABLE tmp.saleGroup; -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 `ticket_splitItemPackingType_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 `ticket_splitItemPackingType_beta`(vTicketFk INT) -proc:BEGIN - - /* - * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado - * - * @param vTicketFk Identificador de vn.ticket - * @return table tmp.ticketIPT(ticketFk, itemPackingTypeFk) - */ - - - DECLARE vItemPackingTypeFk VARCHAR(1); - - DECLARE vNewTicketFk INT; - - DECLARE vPackingTypesToSplit INT; - - DECLARE vDone INT DEFAULT FALSE; - - DECLARE cur1 CURSOR FOR - SELECT itemPackingTypeFk - FROM tmp.saleGroup - WHERE itemPackingTypeFk IS NOT NULL; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - DROP TEMPORARY TABLE IF EXISTS tmp.sale; - CREATE TEMPORARY TABLE tmp.sale - (PRIMARY KEY (id)) - SELECT s.id, i.itemPackingTypeFk , sv.litros - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - JOIN vn.saleVolume sv ON sv.saleFk = s.id - WHERE s.ticketFk = vTicketFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.saleGroup; - CREATE TEMPORARY TABLE tmp.saleGroup - SELECT itemPackingTypeFk , sum(litros) AS totalLitros - FROM tmp.sale - GROUP BY itemPackingTypeFk; - - SELECT COUNT(*) INTO vPackingTypesToSplit - FROM tmp.saleGroup - WHERE itemPackingTypeFk IS NOT NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - (ticketFk INT, - itemPackingTypeFk VARCHAR(1)); - - CASE vPackingTypesToSplit - - WHEN 0 THEN - - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, 'H'); - - WHEN 1 THEN - - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - SELECT vTicketFk, itemPackingTypeFk - FROM tmp.saleGroup - WHERE itemPackingTypeFk IS NOT NULL; - ELSE - - OPEN cur1; - - FETCH cur1 INTO vItemPackingTypeFk; - - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vTicketFk, vItemPackingTypeFk); - - read_loop: LOOP - - FETCH cur1 INTO vItemPackingTypeFk; - - IF vDone THEN - LEAVE read_loop; - END IF; - - CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - INSERT INTO tmp.ticketIPT(ticketFk, itemPackingTypeFk) - VALUES(vNewTicketFk, vItemPackingTypeFk); - - END LOOP; - - CLOSE cur1; - - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = ts.itemPackingTypeFk - SET s.ticketFk = t.ticketFk; - - SELECT itemPackingTypeFk INTO vItemPackingTypeFk - FROM tmp.saleGroup sg - ORDER BY sg.totalLitros - LIMIT 1; - - UPDATE vn.sale s - JOIN tmp.sale ts ON ts.id = s.id - JOIN tmp.ticketIPT t ON t.itemPackingTypeFk = vItemPackingTypeFk - SET s.ticketFk = t.ticketFk - WHERE ISNULL(ts.itemPackingTypeFk); - - END CASE; - - DROP TEMPORARY TABLE tmp.sale; - DROP TEMPORARY TABLE tmp.saleGroup; - -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 `ticket_splitItemPackingType__` */; -/*!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 `ticket_splitItemPackingType__`(vTicketFk INT) -BEGIN - - /* - * Clona y reparte las ventas de un ticket en funcion del tipo de empaquetado - * - */ - - DECLARE vNewItemPackingTypeFk VARCHAR(1); - DECLARE vNewTicketFk INT; - DECLARE vCollectionFk INT; - DECLARE vSplittedLines INT; - DECLARE vPickedLines INT; - -- DECLARE vIsPickUp BOOL; - - SELECT collectionFk INTO vCollectionFk - FROM vn.ticketCollection tc - WHERE tc.ticketFk = vTicketFk - LIMIT 1; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketIPT; - CREATE TEMPORARY TABLE tmp.ticketIPT - SELECT DISTINCT s.ticketFk, i.itemPackingTypeFk - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - WHERE s.ticketFk = vTicketFk; - /* - SELECT count(*) INTO vIsPickUp - FROM vn.ticket t - JOIN vn.agencyMode am ON am.id = t.agencyModeFk - WHERE t.id = vTicketFk - AND am.name = 'REC_ALGEMESI'; - - WHILE NOT vIsPickUp AND (SELECT count(*) FROM tmp.ticketIPT WHERE ticketFk = vTicketFk ) > 1 DO - */ - WHILE (SELECT count(*) FROM tmp.ticketIPT WHERE ticketFk = vTicketFk ) > 1 DO - - SELECT MIN(itemPackingTypeFk) INTO vNewItemPackingTypeFk - FROM tmp.ticketIPT - WHERE ticketFk = vTicketFk; - - CALL vn.ticket_Clone(vTicketFk, vNewTicketFk); - - UPDATE tmp.ticketIPT - SET ticketFk = vNewTicketFk - WHERE itemPackingTypeFk = vNewItemPackingTypeFk; - - SELECT count(*), sum(isPicked != 0) INTO vSplittedLines, vPickedLines - FROM vn.sale s - JOIN vn.item i ON i.id = s.itemFk - WHERE s.ticketFk = vTicketFk - AND i.itemPackingTypeFk = vNewItemPackingTypeFk; - - UPDATE vn.sale s - JOIN vn.item i ON i.id = s.itemFk - SET s.ticketFk = vNewTicketFk - WHERE s.ticketFk = vTicketFk - AND i.itemPackingTypeFk = vNewItemPackingTypeFk; - - UPDATE vn.collection - SET saleTotalCount = saleTotalCount - vSplittedLines, - salePickedCount = salePickedCount - vPickedLines - WHERE id = vCollectionFk; - - END WHILE; - - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -96716,4 +96404,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2022-01-03 7:26:08 +-- Dump completed on 2022-01-13 7:46:58 From 83d2dd2d808aee9113153b2a07e7be8adf21d6de Mon Sep 17 00:00:00 2001 From: alexm Date: Mon, 17 Jan 2022 13:17:06 +0100 Subject: [PATCH 5/5] refacto(ticket_volume): tests and front js --- .../ticket/back/methods/ticket/getVolume.js | 8 ++-- .../methods/ticket/specs/getVolume.spec.js | 13 +++-- modules/ticket/front/volume/index.js | 19 ++++---- modules/ticket/front/volume/index.spec.js | 47 +++++++------------ 4 files changed, 40 insertions(+), 47 deletions(-) diff --git a/modules/ticket/back/methods/ticket/getVolume.js b/modules/ticket/back/methods/ticket/getVolume.js index 57493a5e3..6029020ba 100644 --- a/modules/ticket/back/methods/ticket/getVolume.js +++ b/modules/ticket/back/methods/ticket/getVolume.js @@ -11,11 +11,11 @@ module.exports = Self => { }], returns: [{ arg: 'saleVolume', - type: ['Object'] + type: ['object'] }, { arg: 'packingTypeVolume', - type: ['Object'] + type: ['object'] }], http: { path: `/:id/getVolume`, @@ -43,7 +43,7 @@ module.exports = Self => { ON i.code = s.itemPackingTypeFk WHERE s.ticketFk = ? GROUP BY s.itemPackingTypeFk`, [ticketFk], myOptions); - - return [saleVolume, packingTypeVolume] + + return [saleVolume, packingTypeVolume]; }; }; diff --git a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js index af171c8eb..cba3948db 100644 --- a/modules/ticket/back/methods/ticket/specs/getVolume.spec.js +++ b/modules/ticket/back/methods/ticket/specs/getVolume.spec.js @@ -8,12 +8,15 @@ describe('ticket getVolume()', () => { const options = {transaction: tx}; const ticketId = 1; - const result = await models.Ticket.getVolume(ticketId, options); - const saleVolume = result[0]; - const packingTypeVolume = result[1]; + const expectedSaleVolume = 1.09; + const expectedPackingTypeVolume = 0.028; - expect(saleVolume).toBeDefined; - expect(packingTypeVolume).toBeDefined; + const result = await models.Ticket.getVolume(ticketId, options); + const [saleVolume] = result[0]; + const [packingTypeVolume] = result[1]; + + expect(saleVolume.volume).toEqual(expectedSaleVolume); + expect(packingTypeVolume.volume).toEqual(expectedPackingTypeVolume); await tx.rollback(); } catch (e) { diff --git a/modules/ticket/front/volume/index.js b/modules/ticket/front/volume/index.js index 33fe66bdb..81491bca0 100644 --- a/modules/ticket/front/volume/index.js +++ b/modules/ticket/front/volume/index.js @@ -24,15 +24,18 @@ class Controller extends Section { } applyVolumes() { - const ticket = this.sales[0].ticketFk + const ticket = this.sales[0].ticketFk; this.$http.get(`Tickets/${ticket}/getVolume`).then(res => { - this.sales.forEach(sale => { - res.data.saleVolume.forEach(volume => { - if (sale.id === volume.saleFk) - sale.saleVolume = volume; - }); - }); - this.packingTypeVolume = res.data.packingTypeVolume + const saleVolume = res.data.saleVolume; + + const volumes = new Map(); + for (const volume of saleVolume) + volumes.set(volume.saleFk, volume); + + for (const sale of this.sales) + sale.saleVolume = volumes.get(sale.id); + + this.packingTypeVolume = res.data.packingTypeVolume; }); } } diff --git a/modules/ticket/front/volume/index.spec.js b/modules/ticket/front/volume/index.spec.js index 578c6109c..6ab968503 100644 --- a/modules/ticket/front/volume/index.spec.js +++ b/modules/ticket/front/volume/index.spec.js @@ -35,18 +35,18 @@ describe('ticket', () => { describe('applyVolumes()', () => { const ticket = 1; - const respondGet = + const response = { saleVolume: [ - {saleFk: 1, volume: 0.012}, + {saleFk: 1, volume: 0.012}, {saleFk: 2, volume: 0.015} ], packingTypeVolume: [ - {code: 'V', volume: 1}, - {code: 'H',volume: 2}, + {code: 'V', volume: 1}, + {code: 'H', volume: 2} ] }; - + it(`should not apply volumes to the sales if sales property is not defined on controller`, () => { controller.sales = [{id: 1, name: 'Sale one'}, {id: 2, name: 'Sale two'}]; @@ -61,45 +61,32 @@ describe('ticket', () => { }); it(`should apply volumes to the sales if sales and volumes properties are defined on controller`, () => { - $httpBackend.expectGET(`Tickets/${ticket}/getVolume`).respond(respondGet); + const expectedResultOne = response.saleVolume[0].volume; + const expectedResultTwo = response.saleVolume[1].volume; + $httpBackend.expectGET(`Tickets/${ticket}/getVolume`).respond(response); controller.sales = [ - {id: 1, name: 'Sale one', ticketFk: ticket}, + {id: 1, name: 'Sale one', ticketFk: ticket}, {id: 2, name: 'Sale two'} ]; $httpBackend.flush(); - expect(controller.sales[0].saleVolume.volume).toEqual(0.012); - expect(controller.sales[1].saleVolume.volume).toEqual(0.015); + expect(controller.sales[0].saleVolume.volume).toEqual(expectedResultOne); + expect(controller.sales[1].saleVolume.volume).toEqual(expectedResultTwo); }); it(`should apply packing volumes to the sales if sales and volumes properties are defined on controller`, () => { - $httpBackend.expectGET(`Tickets/${ticket}/getVolume`).respond(respondGet); + const expectedResultOne = response.packingTypeVolume[0].code; + const expectedResultTwo = response.packingTypeVolume[1].code; + $httpBackend.expectGET(`Tickets/${ticket}/getVolume`).respond(response); controller.sales = [ - {id: 1, name: 'Sale one', ticketFk: ticket}, + {id: 1, name: 'Sale one', ticketFk: ticket}, {id: 2, name: 'Sale two'} ]; $httpBackend.flush(); - expect(controller.packingTypeVolume[0]).toBeDefined; - expect(controller.packingTypeVolume[1]).toBeDefined + expect(controller.packingTypeVolume[0].code).toEqual(expectedResultOne); + expect(controller.packingTypeVolume[1].code).toEqual(expectedResultTwo); }); }); - - /* - it('should join the sale volumes to its respective sale', () => { - controller.ticket = {id: 1}; - let response = {volumes: [ - {saleFk: 1, m3: 0.008}, - {saleFk: 2, m3: 0.003} - ]}; - - $httpBackend.expectGET(`tickets/1/getVolume`).respond(response); - controller.onDataChange(); - $httpBackend.flush(); - - expect($scope.model.data[0].volume.m3).toBe(0.008); - expect($scope.model.data[1].volume.m3).toBe(0.003); - }); - */ }); });