diff --git a/back/methods/account/specs/login.spec.js b/back/methods/account/specs/login.spec.js index ffb19637f..59eea2612 100644 --- a/back/methods/account/specs/login.spec.js +++ b/back/methods/account/specs/login.spec.js @@ -3,15 +3,23 @@ const app = require('vn-loopback/server/server'); describe('account login()', () => { describe('when credentials are correct', () => { it('should return the token', async() => { - let response = await app.models.Account.login('employee', 'nightmare'); + let login = await app.models.Account.login('salesAssistant', 'nightmare'); + let accessToken = await app.models.AccessToken.findById(login.token); + let ctx = {req: {accessToken: accessToken}}; - expect(response.token).toBeDefined(); + expect(login.token).toBeDefined(); + + await app.models.Account.logout(ctx); }); it('should return the token if the user doesnt exist but the client does', async() => { - let response = await app.models.Account.login('PetterParker', 'nightmare'); + let login = await app.models.Account.login('PetterParker', 'nightmare'); + let accessToken = await app.models.AccessToken.findById(login.token); + let ctx = {req: {accessToken: accessToken}}; - expect(response.token).toBeDefined(); + expect(login.token).toBeDefined(); + + await app.models.Account.logout(ctx); }); }); diff --git a/back/methods/account/specs/logout.spec.js b/back/methods/account/specs/logout.spec.js index 5770be91f..b3d69d6ef 100644 --- a/back/methods/account/specs/logout.spec.js +++ b/back/methods/account/specs/logout.spec.js @@ -2,15 +2,15 @@ const app = require('vn-loopback/server/server'); describe('account logout()', () => { it('should logout and remove token after valid login', async() => { - let loginResponse = await app.models.Account.login('employee', 'nightmare'); + let loginResponse = await app.models.Account.login('buyer', 'nightmare'); let accessToken = await app.models.AccessToken.findById(loginResponse.token); let ctx = {req: {accessToken: accessToken}}; - let response = await app.models.Account.logout(ctx); - let afterToken = await app.models.AccessToken.findById(loginResponse.token); + let logoutResponse = await app.models.Account.logout(ctx); + let tokenAfterLogout = await app.models.AccessToken.findById(loginResponse.token); - expect(response).toBeTruthy(); - expect(afterToken).toBeNull(); + expect(logoutResponse).toBeTrue(); + expect(tokenAfterLogout).toBeNull(); }); it('should throw a 401 error when token is invalid', async() => { diff --git a/back/methods/chat/spec/sendCheckingPresence.spec.js b/back/methods/chat/spec/sendCheckingPresence.spec.js index 1523cb1d0..497f4947b 100644 --- a/back/methods/chat/spec/sendCheckingPresence.spec.js +++ b/back/methods/chat/spec/sendCheckingPresence.spec.js @@ -1,55 +1,17 @@ const app = require('vn-loopback/server/server'); describe('chat sendCheckingPresence()', () => { + const today = new Date(); + today.setHours(6, 0); + const ctx = {req: {accessToken: {userId: 1}}}; + const chatModel = app.models.Chat; const departmentId = 23; const workerId = 107; - let timeEntry; - afterAll(async done => { - const department = await app.models.Department.findById(departmentId); - await department.updateAttribute('chatName', null); - await app.models.WorkerTimeControl.destroyById(timeEntry.id); - done(); - }); - - it(`should call to send() method with the worker username when no department channel is specified - and then return a "Fake notification sent" as response`, async() => { - const ctx = {req: {accessToken: {userId: 1}}}; - const chatModel = app.models.Chat; + it(`should call send() method with the worker name if he's currently working then return a response`, async() => { spyOn(chatModel, 'send').and.callThrough(); - const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something'); - - expect(response.statusCode).toEqual(200); - expect(response.message).toEqual('Fake notification sent'); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something'); - }); - - it(`should call to send() method with the worker department channel if is specified - and then return a "Fake notification sent" as response`, async() => { - const ctx = {req: {accessToken: {userId: 1}}}; - const chatModel = app.models.Chat; - spyOn(chatModel, 'send').and.callThrough(); - - const department = await app.models.Department.findById(departmentId); - await department.updateAttribute('chatName', 'cooler'); - - const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something'); - - expect(response.statusCode).toEqual(200); - expect(response.message).toEqual('Fake notification sent'); - expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', '@HankPym => I changed something'); - }); - - it(`should call to send() method with the worker username when the worker is working`, async() => { - const ctx = {req: {accessToken: {userId: 1}}}; - const chatModel = app.models.Chat; - spyOn(chatModel, 'send').and.callThrough(); - - const today = new Date(); - today.setHours(6, 0); - - timeEntry = await app.models.WorkerTimeControl.create({ + const timeEntry = await app.models.WorkerTimeControl.create({ userFk: workerId, timed: today, manual: false, @@ -61,5 +23,24 @@ describe('chat sendCheckingPresence()', () => { expect(response.statusCode).toEqual(200); expect(response.message).toEqual('Fake notification sent'); expect(chatModel.send).toHaveBeenCalledWith(ctx, '@HankPym', 'I changed something'); + + // restores + await app.models.WorkerTimeControl.destroyById(timeEntry.id); + }); + + it(`should call to send() method with the worker department channel if he's not currently working then return a response`, async() => { + spyOn(chatModel, 'send').and.callThrough(); + + const department = await app.models.Department.findById(departmentId); + await department.updateAttribute('chatName', 'cooler'); + + const response = await chatModel.sendCheckingPresence(ctx, workerId, 'I changed something'); + + expect(response.statusCode).toEqual(200); + expect(response.message).toEqual('Fake notification sent'); + expect(chatModel.send).toHaveBeenCalledWith(ctx, '#cooler', '@HankPym => I changed something'); + + // restores + await department.updateAttribute('chatName', null); }); }); diff --git a/back/methods/collection/spec/updateCollectionSale.spec.js b/back/methods/collection/spec/updateCollectionSale.spec.js index 4695f6eec..2f150aba9 100644 --- a/back/methods/collection/spec/updateCollectionSale.spec.js +++ b/back/methods/collection/spec/updateCollectionSale.spec.js @@ -1,6 +1,7 @@ const app = require('vn-loopback/server/server'); -describe('updateCollectionSale()', () => { +// #2495 updateCollectionSale reparar polución de unitarios +xdescribe('updateCollectionSale()', () => { it('return a new collection', async() => { let ctx = {req: {accessToken: {userId: 106}}}; let response = await app.models.Collection.updateCollectionSale(ctx, 1, 5, 5, 5, 1, 4, false, 'UXN', 1, 1); diff --git a/db/changes/10221-accountModule/00-account.sql b/db/changes/10221-accountModule/00-account.sql index d26d61c19..61f37cc4d 100644 --- a/db/changes/10221-accountModule/00-account.sql +++ b/db/changes/10221-accountModule/00-account.sql @@ -110,13 +110,15 @@ BEGIN SELECT `name` FROM `user` WHERE id = OLD.id; END$$ -CREATE TRIGGER role_beforeInsert +DROP TRIGGER IF EXISTS account.role_beforeInsert$$ +CREATE DEFINER=`root`@`%` TRIGGER role_beforeInsert BEFORE INSERT ON `role` FOR EACH ROW BEGIN CALL role_checkName(NEW.`name`); -END$$ +END -CREATE TRIGGER role_beforeUpdate +DROP TRIGGER IF EXISTS account.role_beforeUpdate$$ +CREATE DEFINER=`root`@`%` TRIGGER role_beforeUpdate BEFORE UPDATE ON `role` FOR EACH ROW BEGIN IF !(NEW.`name` <=> OLD.`name`) THEN diff --git a/db/changes/10221-accountModule/00-role_checkName.sql b/db/changes/10221-accountModule/00-role_checkName.sql index 1e4f31767..260ba7c29 100644 --- a/db/changes/10221-accountModule/00-role_checkName.sql +++ b/db/changes/10221-accountModule/00-role_checkName.sql @@ -1,7 +1,7 @@ DROP PROCEDURE IF EXISTS account.role_checkName; DELIMITER $$ -CREATE PROCEDURE account.role_checkName(vRoleName VARCHAR(255)) +CREATE DEFINER=`root`@`%` PROCEDURE account.role_checkName(vRoleName VARCHAR(255)) BEGIN /** * Checks that role name meets the necessary syntax requirements, otherwise it diff --git a/db/changes/10240-allSaints/00-ACL.sql b/db/changes/10240-allSaints/00-ACL.sql new file mode 100644 index 000000000..60882e308 --- /dev/null +++ b/db/changes/10240-allSaints/00-ACL.sql @@ -0,0 +1,3 @@ +UPDATE `salix`.`ACL` SET `principalId` = 'deliveryBoss' WHERE (`id` = '194'); +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Town', '*', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss'); +INSERT INTO `salix`.`ACL` (`model`, `property`, `accessType`, `permission`, `principalType`, `principalId`) VALUES ('Province', '*', 'WRITE', 'ALLOW', 'ROLE', 'deliveryBoss'); diff --git a/db/dump/dumpedFixtures.sql b/db/dump/dumpedFixtures.sql index bdc65c914..ffbece93b 100644 --- a/db/dump/dumpedFixtures.sql +++ b/db/dump/dumpedFixtures.sql @@ -23,7 +23,7 @@ USE `util`; LOCK TABLES `config` WRITE; /*!40000 ALTER TABLE `config` DISABLE KEYS */; -INSERT INTO `config` VALUES (1,'10210',0,'production',NULL); +INSERT INTO `config` VALUES (1,'10230',0,'production',NULL); /*!40000 ALTER TABLE `config` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -36,7 +36,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:31 +-- Dump completed on 2020-10-20 10:02:40 USE `account`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -61,7 +61,7 @@ USE `account`; LOCK TABLES `role` WRITE; /*!40000 ALTER TABLE `role` DISABLE KEYS */; -INSERT INTO `role` VALUES (0,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2018-04-23 14:33:59'),(1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',0,'2018-02-26 15:28:23','2019-01-21 12:57:21'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23'),(69,'coolerAssist','Empleado cámara con permiso compras',1,'2020-02-05 12:36:09','2020-02-05 12:36:09'),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25'); +INSERT INTO `role` VALUES (0,'root','Rol con todos los privilegios',0,'2018-04-23 14:33:36','2018-04-23 14:33:59'),(1,'employee','Empleado básico',1,'2017-05-19 07:04:58','2017-11-29 10:06:31'),(2,'customer','Privilegios básicos de un cliente',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(3,'agency','Consultar tablas de predicciones de bultos',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(5,'administrative','Tareas relacionadas con la contabilidad',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(6,'guest','Privilegios para usuarios sin cuenta',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(9,'developer','Desarrolladores del sistema',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(11,'account','Privilegios relacionados con el login',0,'2017-05-19 07:04:58','2017-09-20 17:06:35'),(13,'teamBoss','Jefe de departamento',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(15,'logistic','Departamento de compras, responsables de la logistica',1,'2017-05-19 07:04:58','2018-02-12 10:50:10'),(16,'logisticBoss','Jefe del departamento de logística',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(17,'adminBoss','Jefe del departamento de administración',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(18,'salesPerson','Departamento de ventas',1,'2017-05-19 07:04:58','2017-05-19 07:04:58'),(19,'salesBoss','Jefe del departamento de ventas',1,'2017-05-19 07:04:58','2017-08-16 12:38:27'),(20,'manager','Departamento de gerencia',1,'2017-06-01 14:57:02','2017-06-01 14:57:51'),(21,'salesAssistant','Jefe auxiliar de ventas',1,'2017-08-16 12:40:52','2017-08-16 12:40:52'),(22,'teamManager','Jefe de departamento con privilegios de auxiliar de venta.',1,'2017-09-07 09:08:12','2017-09-07 09:08:12'),(30,'financialBoss','Director finaciero',1,'2017-09-21 11:05:36','2017-09-21 11:05:36'),(31,'freelancer','Trabajadores por cuenta ajena',1,'2017-10-10 12:57:26','2017-10-10 12:59:27'),(32,'ett','Trabajadores de empresa temporal',1,'2017-10-10 12:58:58','2017-10-10 12:59:20'),(33,'invoicing','Personal con acceso a facturación',0,'2018-01-29 16:43:34','2018-01-29 16:43:34'),(34,'agencyBoss','Jefe/a del departamento de agencias',1,'2018-01-29 16:44:39','2018-02-23 07:58:53'),(35,'buyer','Departamento de compras',1,'2018-02-12 10:35:42','2018-02-12 10:35:42'),(36,'replenisher','Trabajadores de camara',1,'2018-02-16 14:07:10','2019-04-12 05:38:08'),(37,'hr','Gestor/a de recursos humanos',1,'2018-02-22 17:34:53','2018-02-22 17:34:53'),(38,'hrBoss','Jefe/a de recursos humanos',1,'2018-02-22 17:35:09','2018-02-22 17:35:09'),(39,'adminAssistant','Jefe auxiliar administrativo',1,'2018-02-23 10:37:36','2018-02-23 10:38:41'),(40,'handmade','Departamento de confección',1,'2018-02-23 11:14:53','2018-02-23 11:39:12'),(41,'handmadeBoss','Jefe de departamento de confección',1,'2018-02-23 11:15:09','2018-02-23 11:39:26'),(42,'artificial','Departamento de artificial',1,'2018-02-23 11:39:59','2018-02-23 11:39:59'),(43,'artificialBoss','Jefe del departamento de artificial',1,'2018-02-23 11:40:16','2018-02-23 11:40:16'),(44,'accessory','Departamento de complementos',1,'2018-02-23 11:41:12','2018-02-23 11:41:12'),(45,'accessoryBoss','Jefe del departamento de complementos',1,'2018-02-23 11:41:23','2018-02-23 11:41:23'),(47,'cooler','Empleados de cámara',1,'2018-02-23 13:08:18','2018-02-23 13:08:18'),(48,'coolerBoss','Jefe del departamento de cámara',1,'2018-02-23 13:12:01','2018-02-23 13:12:01'),(49,'production','Empleado de producción',0,'2018-02-26 15:28:23','2019-01-21 12:57:21'),(50,'productionBoss','Jefe de producción',1,'2018-02-26 15:34:12','2018-02-26 15:34:12'),(51,'marketing','Departamento de marketing',1,'2018-03-01 07:28:39','2018-03-01 07:28:39'),(52,'marketingBoss','Jefe del departamento de marketing',1,'2018-03-01 07:28:57','2018-03-01 07:28:57'),(53,'insurance','Gestor de seguros de cambio',0,'2018-03-05 07:44:35','2019-02-01 13:47:57'),(54,'itemPicker','Sacador en cámara',1,'2018-03-05 12:08:17','2018-03-05 12:08:17'),(55,'itemPickerBoss','Jefe de sacadores',1,'2018-03-05 12:08:31','2018-03-05 12:08:31'),(56,'delivery','Personal de reparto',1,'2018-05-30 06:07:02','2018-05-30 06:07:02'),(57,'deliveryBoss','Jefe de personal de reparto',1,'2018-05-30 06:07:19','2018-05-30 06:07:19'),(58,'packager','Departamento encajadores',1,'2019-01-21 12:43:45','2019-01-21 12:43:45'),(59,'packagerBoss','Jefe departamento encajadores',1,'2019-01-21 12:44:10','2019-01-21 12:44:10'),(60,'productionAssi','Tareas relacionadas con producción y administración',1,'2019-01-29 13:29:01','2019-01-29 13:29:01'),(61,'replenisherBos','Jefe de Complementos/Camara',1,'2019-07-01 06:44:07','2019-07-01 06:44:07'),(62,'noLogin','Role without login access to MySQL',0,'2019-07-01 06:50:19','2019-07-02 13:42:05'),(64,'balanceSheet','Consulta de Balance',0,'2019-07-16 12:12:08','2019-07-16 12:12:08'),(65,'officeBoss','Jefe de filial',1,'2019-08-02 06:54:26','2019-08-02 06:54:26'),(66,'sysadmin','Administrador de sistema',1,'2019-08-08 06:58:56','2019-08-08 06:58:56'),(67,'adminOfficer','categoria profesional oficial de administración',1,'2020-01-03 08:09:23','2020-01-03 08:09:23'),(69,'coolerAssist','Empleado cámara con permiso compras',1,'2020-02-05 12:36:09','2020-02-05 12:36:09'),(70,'trainee','Alumno de prácticas',1,'2020-03-04 11:00:25','2020-03-04 11:00:25'),(71,'checker','Rol de revisor con privilegios de itemPicker',1,'2020-10-02 10:50:07','2020-10-02 10:50:07'),(72,'claim','Personal de reclamaciones',1,'2020-10-13 10:01:32','2020-10-13 10:01:32'); /*!40000 ALTER TABLE `role` ENABLE KEYS */; UNLOCK TABLES; @@ -71,7 +71,7 @@ UNLOCK TABLES; LOCK TABLES `roleInherit` WRITE; /*!40000 ALTER TABLE `roleInherit` DISABLE KEYS */; -INSERT INTO `roleInherit` VALUES (9,0),(66,0),(5,1),(13,1),(18,1),(31,1),(32,1),(34,1),(35,1),(37,1),(40,1),(44,1),(47,1),(51,1),(53,1),(54,1),(56,1),(58,1),(1,2),(1,3),(30,5),(39,5),(60,5),(67,5),(11,6),(2,11),(3,11),(70,11),(16,13),(20,13),(21,13),(22,13),(34,13),(41,13),(43,13),(45,13),(48,13),(50,13),(52,13),(55,13),(57,13),(59,13),(61,13),(16,15),(20,16),(21,18),(52,19),(65,19),(17,20),(30,20),(5,21),(19,21),(22,21),(39,21),(50,21),(30,22),(5,33),(34,33),(15,35),(41,35),(42,35),(50,35),(52,35),(65,35),(69,35),(49,36),(61,36),(17,37),(38,37),(60,37),(67,37),(17,39),(41,40),(43,42),(36,44),(45,44),(36,47),(48,47),(69,47),(40,49),(42,49),(50,49),(59,49),(60,50),(65,50),(52,51),(21,53),(30,53),(55,54),(57,56),(15,57),(39,57),(50,57),(60,57),(49,58),(50,59),(17,64),(30,64),(38,64),(20,65),(1,70); +INSERT INTO `roleInherit` VALUES (1,1,2),(2,1,3),(3,1,70),(4,2,11),(5,3,11),(6,5,1),(7,5,21),(8,5,33),(9,9,0),(10,11,6),(11,13,1),(12,15,35),(13,15,57),(14,16,13),(15,16,15),(16,17,20),(17,17,37),(18,17,39),(19,17,64),(20,18,1),(21,19,21),(22,20,13),(23,20,16),(24,20,65),(25,21,13),(26,21,18),(27,21,53),(28,22,13),(29,22,21),(30,30,5),(31,30,20),(32,30,22),(33,30,53),(34,30,64),(35,31,1),(36,32,1),(37,34,1),(38,34,13),(39,34,33),(40,35,1),(41,36,44),(42,36,47),(43,37,1),(44,38,37),(45,38,64),(46,39,5),(47,39,21),(48,39,57),(49,40,1),(50,40,49),(51,41,13),(52,41,35),(53,41,40),(54,42,35),(55,42,49),(56,43,13),(57,43,42),(58,44,1),(59,45,13),(60,45,44),(61,47,1),(62,48,13),(63,48,47),(64,49,36),(65,49,58),(66,50,13),(67,50,21),(68,50,35),(69,50,49),(70,50,57),(71,50,59),(72,51,1),(73,52,13),(74,52,19),(75,52,35),(76,52,51),(77,53,1),(78,54,1),(79,55,13),(80,55,54),(81,56,1),(82,57,13),(83,57,56),(84,58,1),(85,59,13),(86,59,49),(87,60,5),(88,60,37),(89,60,50),(90,60,57),(91,61,13),(92,61,36),(93,65,19),(94,65,35),(95,65,50),(96,66,0),(97,67,5),(98,67,37),(99,69,35),(100,69,47),(101,70,11),(102,71,1),(103,71,58),(104,72,13),(105,72,18); /*!40000 ALTER TABLE `roleInherit` ENABLE KEYS */; UNLOCK TABLES; @@ -81,7 +81,7 @@ UNLOCK TABLES; LOCK TABLES `roleRole` WRITE; /*!40000 ALTER TABLE `roleRole` DISABLE KEYS */; -INSERT INTO `roleRole` VALUES (0,0),(0,1),(0,2),(0,3),(0,5),(0,6),(0,9),(0,11),(0,13),(0,15),(0,16),(0,17),(0,18),(0,19),(0,20),(0,21),(0,22),(0,30),(0,31),(0,32),(0,33),(0,34),(0,35),(0,36),(0,37),(0,38),(0,39),(0,40),(0,41),(0,42),(0,43),(0,44),(0,45),(0,47),(0,48),(0,49),(0,50),(0,51),(0,52),(0,53),(0,54),(0,55),(0,56),(0,57),(0,58),(0,59),(0,60),(0,61),(0,62),(0,64),(0,65),(0,66),(0,67),(0,69),(0,70),(1,1),(1,2),(1,3),(1,6),(1,11),(1,70),(2,2),(2,6),(2,11),(3,3),(3,6),(3,11),(5,1),(5,2),(5,3),(5,5),(5,6),(5,11),(5,13),(5,18),(5,21),(5,33),(5,53),(5,70),(6,6),(9,0),(9,1),(9,2),(9,3),(9,5),(9,6),(9,9),(9,11),(9,13),(9,15),(9,16),(9,17),(9,18),(9,19),(9,20),(9,21),(9,22),(9,30),(9,31),(9,32),(9,33),(9,34),(9,35),(9,36),(9,37),(9,38),(9,39),(9,40),(9,41),(9,42),(9,43),(9,44),(9,45),(9,47),(9,48),(9,49),(9,50),(9,51),(9,52),(9,53),(9,54),(9,55),(9,56),(9,57),(9,58),(9,59),(9,60),(9,61),(9,62),(9,64),(9,65),(9,66),(9,67),(9,69),(9,70),(11,6),(11,11),(13,1),(13,2),(13,3),(13,6),(13,11),(13,13),(13,70),(15,1),(15,2),(15,3),(15,6),(15,11),(15,13),(15,15),(15,35),(15,56),(15,57),(15,70),(16,1),(16,2),(16,3),(16,6),(16,11),(16,13),(16,15),(16,16),(16,35),(16,56),(16,57),(16,70),(17,1),(17,2),(17,3),(17,5),(17,6),(17,11),(17,13),(17,15),(17,16),(17,17),(17,18),(17,19),(17,20),(17,21),(17,33),(17,35),(17,36),(17,37),(17,39),(17,44),(17,47),(17,49),(17,50),(17,53),(17,56),(17,57),(17,58),(17,59),(17,64),(17,65),(17,70),(18,1),(18,2),(18,3),(18,6),(18,11),(18,18),(18,70),(19,1),(19,2),(19,3),(19,6),(19,11),(19,13),(19,18),(19,19),(19,21),(19,53),(19,70),(20,1),(20,2),(20,3),(20,6),(20,11),(20,13),(20,15),(20,16),(20,18),(20,19),(20,20),(20,21),(20,35),(20,36),(20,44),(20,47),(20,49),(20,50),(20,53),(20,56),(20,57),(20,58),(20,59),(20,65),(20,70),(21,1),(21,2),(21,3),(21,6),(21,11),(21,13),(21,18),(21,21),(21,53),(21,70),(22,1),(22,2),(22,3),(22,6),(22,11),(22,13),(22,18),(22,21),(22,22),(22,53),(22,70),(30,1),(30,2),(30,3),(30,5),(30,6),(30,11),(30,13),(30,15),(30,16),(30,18),(30,19),(30,20),(30,21),(30,22),(30,30),(30,33),(30,35),(30,36),(30,44),(30,47),(30,49),(30,50),(30,53),(30,56),(30,57),(30,58),(30,59),(30,64),(30,65),(30,70),(31,1),(31,2),(31,3),(31,6),(31,11),(31,31),(31,70),(32,1),(32,2),(32,3),(32,6),(32,11),(32,32),(32,70),(33,33),(34,1),(34,2),(34,3),(34,6),(34,11),(34,13),(34,33),(34,34),(34,70),(35,1),(35,2),(35,3),(35,6),(35,11),(35,35),(35,70),(36,1),(36,2),(36,3),(36,6),(36,11),(36,36),(36,44),(36,47),(36,70),(37,1),(37,2),(37,3),(37,6),(37,11),(37,37),(37,70),(38,1),(38,2),(38,3),(38,6),(38,11),(38,37),(38,38),(38,64),(38,70),(39,1),(39,2),(39,3),(39,5),(39,6),(39,11),(39,13),(39,18),(39,21),(39,33),(39,39),(39,53),(39,56),(39,57),(39,70),(40,1),(40,2),(40,3),(40,6),(40,11),(40,36),(40,40),(40,44),(40,47),(40,49),(40,58),(40,70),(41,1),(41,2),(41,3),(41,6),(41,11),(41,13),(41,35),(41,36),(41,40),(41,41),(41,44),(41,47),(41,49),(41,58),(41,70),(42,1),(42,2),(42,3),(42,6),(42,11),(42,35),(42,36),(42,42),(42,44),(42,47),(42,49),(42,58),(42,70),(43,1),(43,2),(43,3),(43,6),(43,11),(43,13),(43,35),(43,36),(43,42),(43,43),(43,44),(43,47),(43,49),(43,58),(43,70),(44,1),(44,2),(44,3),(44,6),(44,11),(44,44),(44,70),(45,1),(45,2),(45,3),(45,6),(45,11),(45,13),(45,44),(45,45),(45,70),(47,1),(47,2),(47,3),(47,6),(47,11),(47,47),(47,70),(48,1),(48,2),(48,3),(48,6),(48,11),(48,13),(48,47),(48,48),(48,70),(49,1),(49,2),(49,3),(49,6),(49,11),(49,36),(49,44),(49,47),(49,49),(49,58),(49,70),(50,1),(50,2),(50,3),(50,6),(50,11),(50,13),(50,18),(50,21),(50,35),(50,36),(50,44),(50,47),(50,49),(50,50),(50,53),(50,56),(50,57),(50,58),(50,59),(50,70),(51,1),(51,2),(51,3),(51,6),(51,11),(51,51),(51,70),(52,1),(52,2),(52,3),(52,6),(52,11),(52,13),(52,18),(52,19),(52,21),(52,35),(52,51),(52,52),(52,53),(52,70),(53,1),(53,2),(53,3),(53,6),(53,11),(53,53),(53,70),(54,1),(54,2),(54,3),(54,6),(54,11),(54,54),(54,70),(55,1),(55,2),(55,3),(55,6),(55,11),(55,13),(55,54),(55,55),(55,70),(56,1),(56,2),(56,3),(56,6),(56,11),(56,56),(56,70),(57,1),(57,2),(57,3),(57,6),(57,11),(57,13),(57,56),(57,57),(57,70),(58,1),(58,2),(58,3),(58,6),(58,11),(58,58),(58,70),(59,1),(59,2),(59,3),(59,6),(59,11),(59,13),(59,36),(59,44),(59,47),(59,49),(59,58),(59,59),(59,70),(60,1),(60,2),(60,3),(60,5),(60,6),(60,11),(60,13),(60,18),(60,21),(60,33),(60,35),(60,36),(60,37),(60,44),(60,47),(60,49),(60,50),(60,53),(60,56),(60,57),(60,58),(60,59),(60,60),(60,70),(61,1),(61,2),(61,3),(61,6),(61,11),(61,13),(61,36),(61,44),(61,47),(61,61),(61,70),(62,62),(64,64),(65,1),(65,2),(65,3),(65,6),(65,11),(65,13),(65,18),(65,19),(65,21),(65,35),(65,36),(65,44),(65,47),(65,49),(65,50),(65,53),(65,56),(65,57),(65,58),(65,59),(65,65),(65,70),(66,0),(66,1),(66,2),(66,3),(66,5),(66,6),(66,9),(66,11),(66,13),(66,15),(66,16),(66,17),(66,18),(66,19),(66,20),(66,21),(66,22),(66,30),(66,31),(66,32),(66,33),(66,34),(66,35),(66,36),(66,37),(66,38),(66,39),(66,40),(66,41),(66,42),(66,43),(66,44),(66,45),(66,47),(66,48),(66,49),(66,50),(66,51),(66,52),(66,53),(66,54),(66,55),(66,56),(66,57),(66,58),(66,59),(66,60),(66,61),(66,62),(66,64),(66,65),(66,66),(66,67),(66,69),(66,70),(67,1),(67,2),(67,3),(67,5),(67,6),(67,11),(67,13),(67,18),(67,21),(67,33),(67,37),(67,53),(67,67),(67,70),(69,1),(69,2),(69,3),(69,6),(69,11),(69,35),(69,47),(69,69),(69,70),(70,6),(70,11),(70,70); +INSERT INTO `roleRole` VALUES (0,0),(0,1),(0,2),(0,3),(0,5),(0,6),(0,9),(0,11),(0,13),(0,15),(0,16),(0,17),(0,18),(0,19),(0,20),(0,21),(0,22),(0,30),(0,31),(0,32),(0,33),(0,34),(0,35),(0,36),(0,37),(0,38),(0,39),(0,40),(0,41),(0,42),(0,43),(0,44),(0,45),(0,47),(0,48),(0,49),(0,50),(0,51),(0,52),(0,53),(0,54),(0,55),(0,56),(0,57),(0,58),(0,59),(0,60),(0,61),(0,62),(0,64),(0,65),(0,66),(0,67),(0,69),(0,70),(0,71),(0,72),(1,1),(1,2),(1,3),(1,6),(1,11),(1,70),(2,2),(2,6),(2,11),(3,3),(3,6),(3,11),(5,1),(5,2),(5,3),(5,5),(5,6),(5,11),(5,13),(5,18),(5,21),(5,33),(5,53),(5,70),(6,6),(9,0),(9,1),(9,2),(9,3),(9,5),(9,6),(9,9),(9,11),(9,13),(9,15),(9,16),(9,17),(9,18),(9,19),(9,20),(9,21),(9,22),(9,30),(9,31),(9,32),(9,33),(9,34),(9,35),(9,36),(9,37),(9,38),(9,39),(9,40),(9,41),(9,42),(9,43),(9,44),(9,45),(9,47),(9,48),(9,49),(9,50),(9,51),(9,52),(9,53),(9,54),(9,55),(9,56),(9,57),(9,58),(9,59),(9,60),(9,61),(9,62),(9,64),(9,65),(9,66),(9,67),(9,69),(9,70),(9,71),(9,72),(11,6),(11,11),(13,1),(13,2),(13,3),(13,6),(13,11),(13,13),(13,70),(15,1),(15,2),(15,3),(15,6),(15,11),(15,13),(15,15),(15,35),(15,56),(15,57),(15,70),(16,1),(16,2),(16,3),(16,6),(16,11),(16,13),(16,15),(16,16),(16,35),(16,56),(16,57),(16,70),(17,1),(17,2),(17,3),(17,5),(17,6),(17,11),(17,13),(17,15),(17,16),(17,17),(17,18),(17,19),(17,20),(17,21),(17,33),(17,35),(17,36),(17,37),(17,39),(17,44),(17,47),(17,49),(17,50),(17,53),(17,56),(17,57),(17,58),(17,59),(17,64),(17,65),(17,70),(18,1),(18,2),(18,3),(18,6),(18,11),(18,18),(18,70),(19,1),(19,2),(19,3),(19,6),(19,11),(19,13),(19,18),(19,19),(19,21),(19,53),(19,70),(20,1),(20,2),(20,3),(20,6),(20,11),(20,13),(20,15),(20,16),(20,18),(20,19),(20,20),(20,21),(20,35),(20,36),(20,44),(20,47),(20,49),(20,50),(20,53),(20,56),(20,57),(20,58),(20,59),(20,65),(20,70),(21,1),(21,2),(21,3),(21,6),(21,11),(21,13),(21,18),(21,21),(21,53),(21,70),(22,1),(22,2),(22,3),(22,6),(22,11),(22,13),(22,18),(22,21),(22,22),(22,53),(22,70),(30,1),(30,2),(30,3),(30,5),(30,6),(30,11),(30,13),(30,15),(30,16),(30,18),(30,19),(30,20),(30,21),(30,22),(30,30),(30,33),(30,35),(30,36),(30,44),(30,47),(30,49),(30,50),(30,53),(30,56),(30,57),(30,58),(30,59),(30,64),(30,65),(30,70),(31,1),(31,2),(31,3),(31,6),(31,11),(31,31),(31,70),(32,1),(32,2),(32,3),(32,6),(32,11),(32,32),(32,70),(33,33),(34,1),(34,2),(34,3),(34,6),(34,11),(34,13),(34,33),(34,34),(34,70),(35,1),(35,2),(35,3),(35,6),(35,11),(35,35),(35,70),(36,1),(36,2),(36,3),(36,6),(36,11),(36,36),(36,44),(36,47),(36,70),(37,1),(37,2),(37,3),(37,6),(37,11),(37,37),(37,70),(38,1),(38,2),(38,3),(38,6),(38,11),(38,37),(38,38),(38,64),(38,70),(39,1),(39,2),(39,3),(39,5),(39,6),(39,11),(39,13),(39,18),(39,21),(39,33),(39,39),(39,53),(39,56),(39,57),(39,70),(40,1),(40,2),(40,3),(40,6),(40,11),(40,36),(40,40),(40,44),(40,47),(40,49),(40,58),(40,70),(41,1),(41,2),(41,3),(41,6),(41,11),(41,13),(41,35),(41,36),(41,40),(41,41),(41,44),(41,47),(41,49),(41,58),(41,70),(42,1),(42,2),(42,3),(42,6),(42,11),(42,35),(42,36),(42,42),(42,44),(42,47),(42,49),(42,58),(42,70),(43,1),(43,2),(43,3),(43,6),(43,11),(43,13),(43,35),(43,36),(43,42),(43,43),(43,44),(43,47),(43,49),(43,58),(43,70),(44,1),(44,2),(44,3),(44,6),(44,11),(44,44),(44,70),(45,1),(45,2),(45,3),(45,6),(45,11),(45,13),(45,44),(45,45),(45,70),(47,1),(47,2),(47,3),(47,6),(47,11),(47,47),(47,70),(48,1),(48,2),(48,3),(48,6),(48,11),(48,13),(48,47),(48,48),(48,70),(49,1),(49,2),(49,3),(49,6),(49,11),(49,36),(49,44),(49,47),(49,49),(49,58),(49,70),(50,1),(50,2),(50,3),(50,6),(50,11),(50,13),(50,18),(50,21),(50,35),(50,36),(50,44),(50,47),(50,49),(50,50),(50,53),(50,56),(50,57),(50,58),(50,59),(50,70),(51,1),(51,2),(51,3),(51,6),(51,11),(51,51),(51,70),(52,1),(52,2),(52,3),(52,6),(52,11),(52,13),(52,18),(52,19),(52,21),(52,35),(52,51),(52,52),(52,53),(52,70),(53,1),(53,2),(53,3),(53,6),(53,11),(53,53),(53,70),(54,1),(54,2),(54,3),(54,6),(54,11),(54,54),(54,70),(55,1),(55,2),(55,3),(55,6),(55,11),(55,13),(55,54),(55,55),(55,70),(56,1),(56,2),(56,3),(56,6),(56,11),(56,56),(56,70),(57,1),(57,2),(57,3),(57,6),(57,11),(57,13),(57,56),(57,57),(57,70),(58,1),(58,2),(58,3),(58,6),(58,11),(58,58),(58,70),(59,1),(59,2),(59,3),(59,6),(59,11),(59,13),(59,36),(59,44),(59,47),(59,49),(59,58),(59,59),(59,70),(60,1),(60,2),(60,3),(60,5),(60,6),(60,11),(60,13),(60,18),(60,21),(60,33),(60,35),(60,36),(60,37),(60,44),(60,47),(60,49),(60,50),(60,53),(60,56),(60,57),(60,58),(60,59),(60,60),(60,70),(61,1),(61,2),(61,3),(61,6),(61,11),(61,13),(61,36),(61,44),(61,47),(61,61),(61,70),(62,62),(64,64),(65,1),(65,2),(65,3),(65,6),(65,11),(65,13),(65,18),(65,19),(65,21),(65,35),(65,36),(65,44),(65,47),(65,49),(65,50),(65,53),(65,56),(65,57),(65,58),(65,59),(65,65),(65,70),(66,0),(66,1),(66,2),(66,3),(66,5),(66,6),(66,9),(66,11),(66,13),(66,15),(66,16),(66,17),(66,18),(66,19),(66,20),(66,21),(66,22),(66,30),(66,31),(66,32),(66,33),(66,34),(66,35),(66,36),(66,37),(66,38),(66,39),(66,40),(66,41),(66,42),(66,43),(66,44),(66,45),(66,47),(66,48),(66,49),(66,50),(66,51),(66,52),(66,53),(66,54),(66,55),(66,56),(66,57),(66,58),(66,59),(66,60),(66,61),(66,62),(66,64),(66,65),(66,66),(66,67),(66,69),(66,70),(66,71),(66,72),(67,1),(67,2),(67,3),(67,5),(67,6),(67,11),(67,13),(67,18),(67,21),(67,33),(67,37),(67,53),(67,67),(67,70),(69,1),(69,2),(69,3),(69,6),(69,11),(69,35),(69,47),(69,69),(69,70),(70,6),(70,11),(70,70),(71,1),(71,2),(71,3),(71,6),(71,11),(71,58),(71,70),(71,71),(72,1),(72,2),(72,3),(72,6),(72,11),(72,13),(72,18),(72,70),(72,72); /*!40000 ALTER TABLE `roleRole` ENABLE KEYS */; UNLOCK TABLES; @@ -124,7 +124,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:33 +-- Dump completed on 2020-10-20 10:02:42 USE `salix`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -149,7 +149,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'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','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','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','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'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','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','salesAssistant'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(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','hr'),(235,'CustomsAgent','*','*','ALLOW','ROLE','employee'),(236,'Buy','*','*','ALLOW','ROLE','buyer'),(237,'WorkerDms','filter','*','ALLOW','ROLE','employee'); +INSERT INTO `ACL` VALUES (1,'Account','*','*','ALLOW','ROLE','employee'),(3,'Address','*','*','ALLOW','ROLE','employee'),(5,'AgencyService','*','READ','ALLOW','ROLE','employee'),(7,'Client','*','*','ALLOW','ROLE','employee'),(9,'ClientObservation','*','*','ALLOW','ROLE','employee'),(11,'ContactChannel','*','READ','ALLOW','ROLE','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'),(48,'ItemNiche','*','READ','ALLOW','ROLE','employee'),(49,'ItemNiche','*','WRITE','ALLOW','ROLE','buyer'),(50,'ItemNiche','*','WRITE','ALLOW','ROLE','replenisher'),(51,'ItemTag','*','READ','ALLOW','ROLE','employee'),(53,'Item','*','READ','ALLOW','ROLE','employee'),(54,'Item','*','WRITE','ALLOW','ROLE','buyer'),(55,'Recovery','*','READ','ALLOW','ROLE','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','salesAssistant'),(98,'ClaimBeginning','*','*','ALLOW','ROLE','employee'),(99,'ClaimDevelopment','*','READ','ALLOW','ROLE','employee'),(100,'ClaimDevelopment','*','WRITE','ALLOW','ROLE','salesAssistant'),(101,'Claim','*','*','ALLOW','ROLE','employee'),(102,'Claim','createFromSales','*','ALLOW','ROLE','employee'),(103,'ClaimEnd','importTicketSales','WRITE','ALLOW','ROLE','salesAssistant'),(104,'Item','*','WRITE','ALLOW','ROLE','marketingBoss'),(105,'ItemBarcode','*','WRITE','ALLOW','ROLE','marketingBoss'),(106,'ItemBotanical','*','WRITE','ALLOW','ROLE','marketingBoss'),(107,'ItemNiche','*','WRITE','ALLOW','ROLE','marketingBoss'),(108,'ItemPlacement','*','WRITE','ALLOW','ROLE','marketingBoss'),(109,'UserConfig','*','*','ALLOW','ROLE','employee'),(110,'Bank','*','READ','ALLOW','ROLE','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'),(164,'InvoiceOut','regenerate','WRITE','ALLOW','ROLE','invoicing'),(165,'TicketDms','*','READ','ALLOW','ROLE','employee'),(167,'Worker','isSubordinate','READ','ALLOW','ROLE','employee'),(168,'Worker','mySubordinates','READ','ALLOW','ROLE','employee'),(169,'WorkerTimeControl','filter','READ','ALLOW','ROLE','employee'),(170,'WorkerTimeControl','addTime','WRITE','ALLOW','ROLE','employee'),(171,'TicketServiceType','*','WRITE','ALLOW','ROLE','administrative'),(172,'Sms','*','READ','ALLOW','ROLE','employee'),(173,'Sms','send','WRITE','ALLOW','ROLE','employee'),(174,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(175,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(176,'Device','*','*','ALLOW','ROLE','employee'),(177,'Device','*','*','ALLOW','ROLE','employee'),(178,'WorkerTimeControl','*','*','ALLOW','ROLE','employee'),(179,'ItemLog','*','READ','ALLOW','ROLE','employee'),(180,'RouteLog','*','READ','ALLOW','ROLE','employee'),(181,'Dms','removeFile','WRITE','ALLOW','ROLE','employee'),(182,'Dms','uploadFile','WRITE','ALLOW','ROLE','employee'),(183,'Dms','downloadFile','READ','ALLOW','ROLE','employee'),(184,'Client','uploadFile','WRITE','ALLOW','ROLE','employee'),(185,'ClientDms','removeFile','WRITE','ALLOW','ROLE','employee'),(186,'ClientDms','*','READ','ALLOW','ROLE','trainee'),(187,'Ticket','uploadFile','WRITE','ALLOW','ROLE','employee'),(188,'TicketDms','removeFile','WRITE','ALLOW','ROLE','employee'),(189,'TicketDms','*','READ','ALLOW','ROLE','employee'),(190,'Route','updateVolume','WRITE','ALLOW','ROLE','deliveryBoss'),(191,'Agency','getLanded','READ','ALLOW','ROLE','employee'),(192,'Agency','getShipped','READ','ALLOW','ROLE','employee'),(194,'Postcode','*','WRITE','ALLOW','ROLE','employee'),(195,'Ticket','addSale','WRITE','ALLOW','ROLE','employee'),(196,'Dms','updateFile','WRITE','ALLOW','ROLE','employee'),(197,'Dms','*','READ','ALLOW','ROLE','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','salesAssistant'),(203,'UserPhone','*','*','ALLOW','ROLE','employee'),(204,'WorkerDms','removeFile','WRITE','ALLOW','ROLE','hr'),(205,'WorkerDms','*','READ','ALLOW','ROLE','hr'),(206,'Chat','*','*','ALLOW','ROLE','employee'),(207,'Chat','sendMessage','*','ALLOW','ROLE','employee'),(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'); /*!40000 ALTER TABLE `ACL` ENABLE KEYS */; UNLOCK TABLES; @@ -172,7 +172,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:34 +-- Dump completed on 2020-10-20 10:02:43 USE `vn`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -347,7 +347,7 @@ UNLOCK TABLES; LOCK TABLES `department` WRITE; /*!40000 ALTER TABLE `department` DISABLE KEYS */; -INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL,1),(23,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL,0),(31,'INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica',1),(34,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1),(35,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1),(36,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1),(37,'PRODUCCION',13,52,NULL,72,230,3,11,1,0,0,17,NULL,'/',NULL,0),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL,0),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL,0),(41,'ADMINISTRACION',53,54,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL,1),(43,'VENTAS',55,76,NULL,0,NULL,NULL,NULL,0,0,0,10,NULL,'/',NULL,1),(44,'GERENCIA',77,78,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL,0),(45,'LOGISTICA',79,80,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL,1),(46,'REPARTO',81,84,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL,0),(48,'ALMACENAJE',85,86,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0),(49,'PROPIEDAD',87,88,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL,0),(52,'CARGA AEREA',89,90,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL,0),(53,'MARKETING Y COMUNICACIÓN',91,92,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL,1),(54,'ORNAMENTALES',93,94,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL,0),(55,'TALLER NATURAL',95,96,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL,0),(56,'TALLER ARTIFICIAL',97,98,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL,0),(58,'CAMPOS',99,100,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL,0),(59,'MANTENIMIENTO',101,102,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL,0),(60,'RECLAMACIONES',103,104,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL,1),(61,'VNH',105,106,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL,0),(63,'VENTAS FRANCIA',56,57,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL,0),(66,'VERDNAMADRID',107,108,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL,0),(68,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL,0),(69,'VERDNABARNA',109,110,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL,0),(77,'PALETIZADO',82,83,NULL,72,230,4,15,1,0,1,0,46,'/46/',NULL,0),(80,'EQUIPO J VALLES',58,59,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo',1),(86,'LIMPIEZA',111,112,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL,0),(89,'COORDINACION',113,114,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0),(90,'TRAILER',115,116,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0),(91,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(92,'EQUIPO SILVERIO',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo',1),(93,'CONFECCION',117,118,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0),(94,'EQUIPO J BROCAL',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo',1),(95,'EQUIPO C ZAMBRANO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo',1),(96,'EQUIPO C LOPEZ',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo',1),(98,'EQUIPO RODRIGO',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo',1),(101,'EQUIPO J IBAÑEZ',70,71,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo',1),(102,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(103,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(104,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(105,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(106,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(107,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(110,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(111,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(112,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0),(113,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0),(114,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(115,'EQUIPO CLAUDI',72,73,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','csr_equipo',1),(120,'PCA PRODUCCION',46,47,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(121,'FV PRODUCCION',48,49,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(122,'PCA ALMACEN',50,51,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0),(123,'EQUIPO ELENA BASCUÑANA',74,75,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','ebt_equipo',0),(124,'CONTROL INTERNO',119,120,NULL,72,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0); +INSERT INTO `department` VALUES (1,'VERDNATURA',1,2,763,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL),(22,'COMPRAS',3,4,NULL,72,596,2,5,0,0,0,0,NULL,'/',NULL,1,NULL),(23,'CAMARA',14,19,NULL,72,604,2,6,1,0,1,2,37,'/37/',NULL,0,NULL),(31,'INFORMATICA',5,6,NULL,72,127,3,9,0,0,0,0,NULL,'/','informatica',1,NULL),(34,'CONTABILIDAD',7,8,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL),(35,'FINANZAS',9,10,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL),(36,'LABORAL',11,12,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,1,NULL),(37,'PRODUCCION',13,52,NULL,72,230,3,11,1,0,0,17,NULL,'/',NULL,0,NULL),(38,'SACADO',20,21,NULL,72,230,4,14,1,0,1,0,37,'/37/',NULL,0,NULL),(39,'ENCAJADO',22,23,NULL,72,230,4,12,1,0,1,0,37,'/37/',NULL,0,NULL),(41,'ADMINISTRACION',53,54,NULL,72,599,3,8,0,0,0,0,NULL,'/',NULL,1,NULL),(43,'VENTAS',55,76,NULL,0,NULL,NULL,NULL,0,0,0,10,NULL,'/',NULL,1,'direccioncomercial@verdnatura.es'),(44,'GERENCIA',77,78,NULL,72,300,2,7,0,0,0,0,NULL,'/',NULL,0,NULL),(45,'LOGISTICA',79,80,NULL,72,596,3,19,0,0,0,0,NULL,'/',NULL,1,NULL),(46,'REPARTO',81,84,NULL,72,659,3,10,0,0,0,1,NULL,'/',NULL,0,NULL),(48,'ALMACENAJE',85,86,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0,NULL),(49,'PROPIEDAD',87,88,NULL,72,1008,1,1,0,0,0,0,NULL,'/',NULL,0,NULL),(52,'CARGA AEREA',89,90,NULL,72,163,4,28,0,0,0,0,NULL,'/',NULL,0,NULL),(53,'MARKETING Y COMUNICACIÓN',91,92,NULL,72,1238,0,0,0,0,0,0,NULL,'/',NULL,1,NULL),(54,'ORNAMENTALES',93,94,NULL,72,433,3,21,0,0,0,0,NULL,'/',NULL,0,NULL),(55,'TALLER NATURAL',95,96,NULL,72,695,2,23,0,0,0,0,NULL,'/',NULL,0,NULL),(56,'TALLER ARTIFICIAL',97,98,NULL,72,1780,2,24,0,0,0,0,NULL,'/',NULL,0,NULL),(58,'CAMPOS',99,100,NULL,72,225,2,2,0,0,0,0,NULL,'/',NULL,0,NULL),(59,'MANTENIMIENTO',101,102,NULL,72,1907,4,16,0,0,0,0,NULL,'/',NULL,0,NULL),(60,'RECLAMACIONES',103,104,NULL,72,563,3,20,0,0,0,0,NULL,'/',NULL,1,NULL),(61,'VNH',105,106,NULL,73,1297,3,17,0,0,0,0,NULL,'/',NULL,0,NULL),(63,'VENTAS FRANCIA',56,57,NULL,72,277,2,27,0,0,1,0,43,'/43/',NULL,0,NULL),(66,'VERDNAMADRID',107,108,NULL,72,163,3,18,0,0,0,0,NULL,'/',NULL,0,NULL),(68,'COMPLEMENTOS',24,25,NULL,72,617,3,26,1,0,1,0,37,'/37/',NULL,0,NULL),(69,'VERDNABARNA',109,110,NULL,74,432,3,22,0,0,0,0,NULL,'/',NULL,0,NULL),(77,'PALETIZADO',82,83,NULL,72,230,4,15,1,0,1,0,46,'/46/',NULL,0,NULL),(80,'EQUIPO J VALLES',58,59,NULL,72,693,3,4,0,0,1,0,43,'/43/','jvp_equipo',1,NULL),(86,'LIMPIEZA',111,112,NULL,72,599,0,0,0,0,0,0,NULL,'/',NULL,0,NULL),(89,'COORDINACION',113,114,NULL,0,NULL,NULL,NULL,1,0,0,0,NULL,'/',NULL,0,NULL),(90,'TRAILER',115,116,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL),(91,'ARTIFICIAL',26,27,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(92,'EQUIPO SILVERIO',60,61,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','sdc_equipo',1,NULL),(93,'CONFECCION',117,118,NULL,0,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL),(94,'EQUIPO J BROCAL',62,63,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jes_equipo',1,NULL),(95,'EQUIPO C ZAMBRANO',64,65,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','czg_equipo',1,NULL),(96,'EQUIPO C LOPEZ',66,67,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','cla_equipo',1,NULL),(98,'EQUIPO RODRIGO',68,69,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','rhr_equipo',1,NULL),(101,'EQUIPO J IBAÑEZ',70,71,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','jmi_equipo',1,NULL),(102,'EQ ROJO FV RUBEN C',28,29,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(103,'EQ AZUL FV A FOLQUES',30,31,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(104,'EQ AMARILLO FV NORMAN G',32,33,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(105,'EQ MORADO FV MATOU',34,35,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(106,'EQ VERDE PCA KEVIN GIMENEZ',36,37,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(107,'EQ NARANJA PCA RUBEN ZANON',38,39,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(110,'EQ ROSA PCA J BONDIA',40,41,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(111,'EQ REPONEDOR CAJAS',42,43,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(112,'CAMARA EQ EDGAR LLEO',15,16,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0,NULL),(113,'CAMARA EQ MARC ROCA',17,18,NULL,0,NULL,NULL,NULL,1,0,2,0,23,'/37/23/',NULL,0,NULL),(114,'EQ MARRON PCA JL NUEVO',44,45,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(115,'EQUIPO CLAUDI',72,73,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','csr_equipo',1,NULL),(120,'PCA PRODUCCION',46,47,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(121,'FV PRODUCCION',48,49,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(122,'PCA ALMACEN',50,51,NULL,0,NULL,NULL,NULL,1,0,1,0,37,'/37/',NULL,0,NULL),(123,'EQUIPO ELENA BASCUÑANA',74,75,NULL,0,NULL,NULL,NULL,0,0,1,0,43,'/43/','ebt_equipo',0,NULL),(124,'CONTROL INTERNO',119,120,NULL,72,NULL,NULL,NULL,0,0,0,0,NULL,'/',NULL,0,NULL); /*!40000 ALTER TABLE `department` ENABLE KEYS */; UNLOCK TABLES; @@ -380,7 +380,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:38 +-- Dump completed on 2020-10-20 10:02:48 USE `cache`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -418,7 +418,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:39 +-- Dump completed on 2020-10-20 10:02:48 USE `hedera`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -476,7 +476,7 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:40 +-- Dump completed on 2020-10-20 10:02:50 USE `postgresql`; -- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) -- @@ -551,7 +551,7 @@ UNLOCK TABLES; LOCK TABLES `workcenter` WRITE; /*!40000 ALTER TABLE `workcenter` DISABLE KEYS */; -INSERT INTO `workcenter` VALUES (1,'Silla',20,1073,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2852,5,'Av constitución 3',554145),(6,'Vilassar',88,88031,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL); +INSERT INTO `workcenter` VALUES (1,'Silla',20,1080,1,'Av espioca 100',552703),(2,'Mercaflor',19,NULL,NULL,NULL,NULL),(3,'Marjales',26,20008,NULL,NULL,NULL),(4,'VNH',NULL,NULL,3,NULL,NULL),(5,'Madrid',28,2853,5,'Av constitución 3',554145),(6,'Vilassar',88,88031,2,'Cami del Crist, 33',556412),(7,'Tenerife',NULL,NULL,10,NULL,NULL); /*!40000 ALTER TABLE `workcenter` ENABLE KEYS */; UNLOCK TABLES; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; @@ -564,4 +564,52 @@ UNLOCK TABLES; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 13:28:42 +-- Dump completed on 2020-10-20 10:02:51 +USE `sage`; +-- MySQL dump 10.13 Distrib 5.7.28, for osx10.15 (x86_64) +-- +-- Host: db.verdnatura.es Database: sage +-- ------------------------------------------------------ +-- Server version 5.6.25-4-log + +/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; +/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; +/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; +/*!40101 SET NAMES utf8 */; +/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; +/*!40103 SET TIME_ZONE='+00:00' */; +/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; +/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; +/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; +/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; + +-- +-- Dumping data for table `TiposIva` +-- + +LOCK TABLES `TiposIva` WRITE; +/*!40000 ALTER TABLE `TiposIva` DISABLE KEYS */; +INSERT INTO `TiposIva` VALUES (2,0,'Operaciones no sujetas',0.0000000000,0.0000000000,0.0000000000,'','4770000020','','','','','','','95B21A93-5910-489D-83BB-C32788C9B19D','','','','','','','','','',0,0),(4,0,'I.V.A. 4%',0.0000000000,4.0000000000,0.0000000000,'4720000004','4770000004','','6310000000','','','','','9E6160D5-984E-4643-ACBC-1EBC3BF73360','','','','','','','','','',0,0),(5,0,'I.V.A. 4% y R.E. 0.5%',0.0000000000,4.0000000000,0.5000000000,'','4770000504','4770000405','','','','','','DBEFA562-63FB-4FFC-8171-64F0C6F065FF','','','','','','','','','',0,0),(6,0,'H.P. IVA 4% CEE',0.0000000000,4.0000000000,0.0000000000,'4721000004','4771008888','','','','','','','DD0ECBA8-2EF5-425E-911B-623580BADA77','','','','','','','','','',0,1),(7,0,'H.P. IVA 10% CEE',0.0000000000,10.0000000000,0.0000000000,'4721000011','4771008888','','','','','','','593208CD-6F28-4489-B6EC-907AD689EAC9','','','','','','','','','',0,1),(8,0,'H.P. IVA 21% CEE',0.0000000000,21.0000000000,0.0000000000,'4721000021','4771008888','','','','','','','27061852-9BC1-4C4F-9B6E-69970E208F23','','','','','','','','','',0,1),(10,0,'I.V.A. 10% Nacional',0.0000000000,10.0000000000,0.0000000000,'4720000011','4770000010','','','','','','','828A9D6F-5C01-4C3A-918A-B2E4482830D3','','','','','','','','','',0,0),(11,0,'I.V.A. 10% y R.E. 1,4%',0.0000000000,10.0000000000,1.4000000000,'','4770000101','4770000110','','','','','','C1F2D910-83A1-4191-A76C-8B3D7AB98348','','','','','','','','','',0,0),(16,0,'I.V.A. Adqui. servicios CEE',0.0000000000,21.0000000000,0.0000000000,'4721000015','4771000016','','','','','','','E3EDE961-CE8F-41D4-9E6C-D8BCD32275A1','','','','','','','','','',0,1),(18,0,'H.P. Iva Importación 0% ISP',0.0000000000,0.0000000000,0.0000000000,'4720000005','4770000005','','','','','','','27AD4158-2349-49C2-B53A-A4E0EFAC5D09','','','','','','','','','',0,0),(20,0,'I.V.A 0% Nacional',0.0000000000,0.0000000000,0.0000000000,'4720000000','','','','','','','','B90B0FBD-E513-4F04-9721-C873504E08DF','','','','','','','','','',0,0),(21,0,'I.V.A. 21%',0.0000000000,21.0000000000,0.0000000000,'4720000021','4770000021','4770000000','','','','','','BA8C4E28-DCFA-4F7B-AE4F-CA044626B55E','','','','','','','','','',0,0),(22,0,'IVA 10% importaciones',0.0000000000,10.0000000000,0.0000000000,'4722000010','','','','','','','','540450A8-4B41-4607-96D1-E7F296FB6933','','','','','','','','','',0,0),(26,0,'I.V.A. 21% y R.E. 5,2%',0.0000000000,21.0000000000,5.2000000000,'4720000021','4770000215','4770000521','631000000','','','','','2BC0765F-7739-49AE-A5F0-28B648B81677','','','','','','','','','',0,0),(90,0,'IVA 21% importaciones',0.0000000000,21.0000000000,0.0000000000,'4722000021','','','','','','','','EB675F91-5FF2-4E26-A31E-EEB674125945','','','','','','','','','',0,0),(91,0,'IVA 0% importaciones',0.0000000000,0.0000000000,0.0000000000,'4723000000','','','','','','','','5E5EFA56-2A99-4D54-A16B-5D818274CA18','','','','','','','','','',0,0),(93,0,'12% com. agrícola o forestal',0.0000000000,12.0000000000,0.0000000000,'4720000012','','','','','','','','267B1DDB-247F-4A71-AB95-3349FEFC5F92','','','','','','','','','',0,0),(110,0,'HP IVA Devengado Exento CEE',0.0000000000,0.0000000000,0.0000000000,'','4771000000','','','','','','','C605BC32-E161-42FD-83F3-3A66B1FBE399','','','','','','','','','',0,1),(111,0,'H.P. Iva Devengado Exento Ser',0.0000000000,0.0000000000,0.0000000000,'','4771000001','','','','','','','F1AEC4DC-AFE5-498E-A713-2648FFB6DA32','','','','','','','','','',0,0),(112,0,'H.P. IVA Devengado en exportac',0.0000000000,0.0000000000,0.0000000000,'','4770000002','','','','','','','F980AE74-BF75-4F4C-927F-0CCCE0DB8D15','','','','','','','','','',0,0),(113,0,'HP DEVENGADO 21 ISP ',0.0000000000,21.0000000000,0.0000000000,'4720000006','4770000006','','','','','','','728D7A76-E936-438C-AF05-3CA38FE16EA5','','','','','','','','','',0,0); +/*!40000 ALTER TABLE `TiposIva` ENABLE KEYS */; +UNLOCK TABLES; + +-- +-- Dumping data for table `TiposTransacciones` +-- + +LOCK TABLES `TiposTransacciones` WRITE; +/*!40000 ALTER TABLE `TiposTransacciones` DISABLE KEYS */; +INSERT INTO `TiposTransacciones` VALUES (1,'Rég.general/Oper.interiores bienes y serv.corrien.','',0,''),(2,'Régimen especial de bienes usados','E',0,''),(3,'Régimen especial de obj. de arte y antigüedades','E',0,''),(4,'Régimen especial agencias de viaje','',0,''),(5,'Régimen especial determinación proporcional','E',0,''),(6,'Oper.en rég.simplificado art.37.1.2º Rgto.IVA','E',0,''),(7,'Oper.en rég.simplificado art.37.1.1º Rgto.IVA','E',0,''),(8,'Oper.en rég.de agricultura, ganadería y pesca','E',0,''),(9,'Oper.en rég.especial de recargo de equivalencia','E',0,''),(10,'Entregas intracomunitarias','E',0,''),(11,'Entregas intermediarias intracomunitarias','E',0,''),(12,'Operaciones sujetas con derecho a devolución','E',0,''),(13,'Prest. Serv. No sujetas derecho devolución','E',0,''),(14,'Exportaciones definitivas','E',0,''),(15,'Envíos definitivos a Canarias, Ceuta y Melilla','E',0,''),(16,'Devoluciones en régimen de viajeros','E',0,''),(17,'Operaciones con áreas exentas','E',0,''),(18,'Operaciones exentas con derecho a deducción','E',0,''),(19,'Operaciones exentas sin derecho a deducción','E',0,''),(20,'Adquisic.intracomunitarias de bienes y serv.corr.','',-1,'P'),(21,'Adquisic.intracomunitarias de bienes de inversión','',-1,'P'),(22,'Adquisic.intermediarias intracomunitarias','',-1,'P'),(23,'Modif.autorizadas en quiebras y susp.de pagos','',0,''),(24,'Entrega de bienes inmuebles no habituales','E',0,''),(25,'Entrega de bienes de inversión','E',0,''),(26,'Op.finan. y Entregas oro inversión, no habituales','E',0,''),(27,'Inversión sujeto pasivo','',-1,'I'),(28,'Prestaciones intracomunitarias de servicios','E',0,''),(29,'Adquisiciones intracomunitarias de servicios','',-1,'I'),(30,'Operaciones interiores de bienes de inversión','R',0,''),(31,'Importaciones de bienes y servicios corrientes','R',0,''),(32,'Importaciones de bienes de inversión','R',0,''),(33,'Operaciones que generan inversión sujeto pasivo','E',0,''),(35,'Compensaciones en rég.de agricultura, gan.y pesca','R',0,''),(36,'Regularización de inversiones','R',0,''),(37,'Operaciones exentas','R',0,''),(38,'Operaciones no sujetas','',0,''),(39,'Gastos devengados op interiores (País Vasco)','R',0,''),(40,'Gastos Adq.intracom. bienes (País Vasco)','',-1,'P'),(42,'Gastos Adq.intermediarias intracom. (País Vasco)','',-1,'P'),(47,'Gastos Inversión sujeto pasivo (País Vasco)','',-1,'I'),(49,'Gastos Adq. intracom. servicios (País Vasco)','',-1,'I'),(51,'Gastos Importaciones (País Vasco)','R',0,''),(53,'Adquisiciones a agencias de viajes en rég.especial','R',0,''),(54,'Entregas intrac.posteriores a importaciones','E',0,''),(55,'Entregas intrac.post.impor.con representante','E',0,''),(56,'Import. bienes y serv. corrientes pdte. liquidar','R',0,''),(57,'Import. bienes de inversión pdte. liquidar','R',0,''),(58,'Servicios prestados por Internet desde España','E',0,''),(59,'Servicios prestados por Internet fuera de España','E',0,''),(60,'Régimen depósito distinto al aduanero','',0,''),(61,'Adquisición de bienes de inversión con ISP','',-1,'I'),(62,'Prest. Serv. Interiores clientes comunit./extranj.','',0,''),(63,'Prest. Serv. Ex. con derecho a deducc. comu./extr.','E',0,''),(64,'Prest. Serv. Ex. sin derecho a deducc. comu./extr.','E',0,''),(65,'Entregas No sujetas derecho devolución','E',0,''),(66,'Operaciones exentas art. 25 ley 19/1994 (Canarias)','',0,''),(67,'Entrega de bienes exenta \"Zona Especial Canaria\"','',0,''),(68,'Prestac. servicios exenta \"Zona Especial Canaria\"','',0,''); +/*!40000 ALTER TABLE `TiposTransacciones` ENABLE KEYS */; +UNLOCK TABLES; +/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; + +/*!40101 SET SQL_MODE=@OLD_SQL_MODE */; +/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; +/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; +/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; +/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; +/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; +/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; + +-- Dump completed on 2020-10-20 10:02:52 diff --git a/db/dump/fixtures.sql b/db/dump/fixtures.sql index ae7fbe67e..0bee9cf65 100644 --- a/db/dump/fixtures.sql +++ b/db/dump/fixtures.sql @@ -2116,4 +2116,18 @@ INSERT INTO `vn`.`tabletDepartment`(`tabletFk`, `departmentFk`) (1, 23), (2, 1); +INSERT INTO `vn`.`campaign`(`code`, `dated`) + VALUES + ('valentinesDay', CONCAT(YEAR(CURDATE()), '-02-14')), + ('valentinesDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-02-14')), + ('valentinesDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -2 YEAR)), '-02-14')), + ('valentinesDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -3 YEAR)), '-02-14')), + ('mothersDay', CONCAT(YEAR(CURDATE()), '-05-05')), + ('mothersDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-05-05')), + ('mothersDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -2 YEAR)), '-05-05')), + ('mothersDay', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -3 YEAR)), '-05-05')), + ('allSaints', CONCAT(YEAR(CURDATE()), '-11-01')), + ('allSaints', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -1 YEAR)), '-11-01')), + ('allSaints', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -2 YEAR)), '-11-01')), + ('allSaints', CONCAT(YEAR(DATE_ADD(CURDATE(), INTERVAL -3 YEAR)), '-11-01')); diff --git a/db/dump/structure.sql b/db/dump/structure.sql index b1362bdb3..2cbe2c105 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -39,18 +39,17 @@ CREATE TABLE `account` ( /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`account_afterInsert` - AFTER INSERT ON `account` - FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account_afterInsert` + AFTER INSERT ON `account` FOR EACH ROW BEGIN - UPDATE user SET sync = FALSE - WHERE id = NEW.id; + INSERT IGNORE INTO userSync (`name`) + SELECT `name` FROM `user` WHERE id = NEW.id; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -60,18 +59,17 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account`.`account_afterDelete` - AFTER DELETE ON `account` - FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `account_afterDelete` + AFTER DELETE ON `account` FOR EACH ROW BEGIN - UPDATE user SET sync = FALSE - WHERE id = OLD.id; + INSERT IGNORE INTO userSync (`name`) + SELECT `name` FROM `user` WHERE id = OLD.id; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -158,6 +156,7 @@ CREATE TABLE `ldapConfig` ( `password` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Base64 encoded password', `baseDn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The base DN to do the query', `filter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Filter to apply to the query', + `groupDn` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='LDAP server configuration parameters'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -172,6 +171,7 @@ DROP TABLE IF EXISTS `mailAlias`; CREATE TABLE `mailAlias` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `alias` varchar(50) CHARACTER SET utf8 NOT NULL, + `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `isPublic` tinyint(4) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `alias` (`alias`) @@ -186,13 +186,15 @@ DROP TABLE IF EXISTS `mailAliasAccount`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `mailAliasAccount` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `mailAlias` int(10) unsigned NOT NULL, `account` int(10) unsigned NOT NULL, - PRIMARY KEY (`mailAlias`,`account`), + PRIMARY KEY (`id`), + UNIQUE KEY `mailAlias` (`mailAlias`,`account`), KEY `account` (`account`), CONSTRAINT `account` FOREIGN KEY (`account`) REFERENCES `account` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `mailAlias` FOREIGN KEY (`mailAlias`) REFERENCES `mailAlias` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail alias that is assigned to each account'; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Mail alias that is assigned to each account'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -266,13 +268,53 @@ CREATE TABLE `role` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(14) COLLATE utf8_unicode_ci NOT NULL COMMENT 'MySQL doesn''t support more than 14 chars for proxied user names', `description` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL, - `hasLogin` tinyint(3) unsigned NOT NULL DEFAULT '0', + `hasLogin` tinyint(3) unsigned NOT NULL DEFAULT '1', `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `name` (`name`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Roles'; /*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER role_beforeInsert + BEFORE INSERT ON `role` FOR EACH ROW +BEGIN + CALL role_checkName(NEW.`name`); +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER role_beforeUpdate + BEFORE UPDATE ON `role` FOR EACH ROW +BEGIN + IF !(NEW.`name` <=> OLD.`name`) THEN + CALL role_checkName (NEW.`name`); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `roleConfig` @@ -296,13 +338,15 @@ DROP TABLE IF EXISTS `roleInherit`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `roleInherit` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `role` int(10) unsigned NOT NULL, `inheritsFrom` int(10) unsigned NOT NULL, - PRIMARY KEY (`role`,`inheritsFrom`), + PRIMARY KEY (`id`), + UNIQUE KEY `role` (`role`,`inheritsFrom`), KEY `owner_id` (`inheritsFrom`), CONSTRAINT `roleInherit_ibfk_1` FOREIGN KEY (`role`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `roleInherit_ibfk_2` FOREIGN KEY (`inheritsFrom`) REFERENCES `role` (`id`) ON DELETE CASCADE ON UPDATE CASCADE -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Role inheritance'; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Role inheritance'; /*!40101 SET character_set_client = @saved_cs_client */; -- @@ -352,7 +396,7 @@ CREATE TABLE `user` ( `active` tinyint(1) NOT NULL DEFAULT '1', `email` varchar(255) CHARACTER SET utf8 DEFAULT NULL, `lang` char(2) CHARACTER SET utf8 DEFAULT NULL, - `sync` tinyint(4) NOT NULL DEFAULT '0', + `sync` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Deprecated', `recoverPass` tinyint(3) unsigned NOT NULL DEFAULT '1', `lastPassChange` datetime DEFAULT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, @@ -394,33 +438,16 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_beforeUpdate` - BEFORE UPDATE ON `user` - FOR EACH ROW +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_afterInsert` + AFTER INSERT ON `user` FOR EACH ROW BEGIN - IF !(NEW.`name` <=> OLD.`name`) THEN - CALL user_checkName (NEW.`name`); - END IF; - - IF NEW.`sync` <=> OLD.`sync` THEN - SET NEW.`sync` = FALSE; - END IF; - - IF !(NEW.`password` <=> OLD.`password`) THEN - SET NEW.bcryptPassword = NULL; - SET NEW.lastPassChange = NOW(); - END IF; - - /*borrar el lunes*/ - IF (NEW.`id` = 14255) THEN - SET NEW.role = 9; - END IF; + INSERT IGNORE INTO userSync SET `name` = NEW.`name`; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -430,23 +457,54 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_beforeUpdate` + BEFORE UPDATE ON `user` FOR EACH ROW +BEGIN + IF !(NEW.`name` <=> OLD.`name`) THEN + CALL user_checkName (NEW.`name`); + END IF; + + IF !(NEW.`password` <=> OLD.`password`) THEN + SET NEW.bcryptPassword = NULL; + SET NEW.lastPassChange = NOW(); + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; /*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_afterUpdate` - AFTER UPDATE ON `user` - FOR EACH ROW + AFTER UPDATE ON `user` FOR EACH ROW BEGIN + INSERT IGNORE INTO userSync SET `name` = NEW.`name`; + + IF !(OLD.`name` <=> NEW.`name`) THEN + INSERT IGNORE INTO userSync SET `name` = OLD.`name`; + END IF; + IF !(NEW.`role` <=> OLD.`role`) - THEN + THEN INSERT INTO vn.mail SET `sender` = 'jgallego@verdnatura.es', - `replyTo` = 'jgallego@verdnatura.es', - `subject` = 'Rol modificado', - `body` = CONCAT(myUserGetName(), ' ha modificado el rol del usuario ', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Rol modificado', + `body` = CONCAT(myUserGetName(), ' ha modificado el rol del usuario ', NEW.`name`, ' de ', OLD.role, ' a ', NEW.role); END IF; END */;; @@ -455,6 +513,25 @@ 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 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `user_afterDelete` + AFTER DELETE ON `user` FOR EACH ROW +BEGIN + INSERT IGNORE INTO userSync SET `name` = OLD.`name`; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; -- -- Table structure for table `userConfig` @@ -488,6 +565,19 @@ CREATE TABLE `userPassword` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Restrictions on user passwords'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `userSync` +-- + +DROP TABLE IF EXISTS `userSync`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `userSync` ( + `name` varchar(30) NOT NULL, + PRIMARY KEY (`name`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Dumping events for database 'account' -- @@ -510,23 +600,9 @@ CREATE DEFINER=`root`@`%` FUNCTION `myUserCheckLogin`() RETURNS tinyint(1) DETERMINISTIC BEGIN /** - * Checks that variables @userId and @userName haven't been altered. - * - * @return %TRUE if they are unaltered or unset, otherwise %FALSE + * @deprecated Use myUser_checkLogin() */ - DECLARE vSignature VARCHAR(128); - DECLARE vKey VARCHAR(255); - - IF @userId IS NOT NULL - AND @userName IS NOT NULL - AND @userSignature IS NOT NULL - THEN - SELECT loginKey INTO vKey FROM userConfig; - SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); - RETURN vSignature = @userSignature; - END IF; - - RETURN FALSE; + RETURN myUser_checkLogin(); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -548,21 +624,9 @@ CREATE DEFINER=`root`@`%` FUNCTION `MYUSERGETID`() RETURNS int(11) DETERMINISTIC BEGIN /** - * Returns the current user id. - * - * @return The user id + * @deprecated Use myUser_getId() */ - DECLARE vUser INT DEFAULT NULL; - - IF myUserCheckLogin() - THEN - SET vUser = @userId; - ELSE - SELECT id INTO vUser FROM user - WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); - END IF; - - RETURN vUser; + RETURN myUser_getId(); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -584,20 +648,9 @@ CREATE DEFINER=`root`@`%` FUNCTION `myUserGetName`() RETURNS varchar(30) CHARSET DETERMINISTIC BEGIN /** - * Returns the current user name. - * - * @return The user name + * @deprecated Use myUser_getName() */ - DECLARE vUser VARCHAR(30) DEFAULT NULL; - - IF myUserCheckLogin() - THEN - SET vUser = @userName; - ELSE - SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); - END IF; - - RETURN vUser; + RETURN myUser_getName(); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -618,12 +671,9 @@ CREATE DEFINER=`root`@`%` FUNCTION `myUserHasRole`(vRoleName VARCHAR(255)) RETUR DETERMINISTIC BEGIN /** - * Comprueba si el usuario actual tiene asociado un rol. - * - * @param vRoleName Nombre del rol a comprobar - * @return %TRUE si tiene el rol, %FALSE en caso contrario - */ - RETURN userHasRole(myUserGetName(), vRoleName); + * @deprecated Use myUser_hasRole() + */ + RETURN myUser_hasRole(vRoleName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -644,19 +694,16 @@ CREATE DEFINER=`root`@`%` FUNCTION `myUserHasRoleId`(vRoleId INT) RETURNS tinyin DETERMINISTIC BEGIN /** - * Comprueba si el usuario actual tiene asociado un rol. - * - * @param vRoleId Identificador del rol a comprobar - * @return %TRUE si tiene el rol, %FALSE en caso contrario - */ - RETURN userHasRoleId(myUserGetName(), vRoleId); + * @deprecated Use myUser_hasRoleId() + */ + RETURN myUser_hasRoleId(vRoleId); 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 `passwordGenerate` */; +/*!50003 DROP FUNCTION IF EXISTS `myUser_checkLogin` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -666,54 +713,151 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `passwordGenerate`() RETURNS text CHARSET utf8 +CREATE DEFINER=`root`@`%` FUNCTION `myUser_checkLogin`() RETURNS tinyint(1) + READS SQL DATA + DETERMINISTIC BEGIN /** - * Genera una contraseña aleatoria - * cumpliendo los requisitos mínimos. + * Checks that variables @userId and @userName haven't been altered. * - * @return Generated password + * @return %TRUE if they are unaltered or unset, otherwise %FALSE */ - DECLARE vMinLength TINYINT(3); - DECLARE vMinAlpha TINYINT(3); - DECLARE vMinUpper TINYINT(3); - DECLARE vMinDigits TINYINT(3); - DECLARE vMinPunct TINYINT(3); - DECLARE vAlpha TINYINT(3) DEFAULT 0; - DECLARE vUpper TINYINT(3) DEFAULT 0; - DECLARE vDigits TINYINT(3) DEFAULT 0; - DECLARE vPunct TINYINT(3) DEFAULT 0; - DECLARE vRandIndex INT; - DECLARE vPwd TEXT DEFAULT ''; - - DECLARE vAlphaChars TEXT DEFAULT 'abcdefghijklmnopqrstuvwxyz'; - DECLARE vUpperChars TEXT DEFAULT 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; - DECLARE vDigitChars TEXT DEFAULT '1234567890'; - DECLARE vPunctChars TEXT DEFAULT '!$%&()=.'; + DECLARE vSignature VARCHAR(128); + DECLARE vKey VARCHAR(255); - SELECT length, nAlpha, nUpper, nDigits, nPunct - INTO vMinLength, vMinAlpha, vMinUpper, vMinDigits, vMinPunct FROM userPassword; + IF @userId IS NOT NULL + AND @userName IS NOT NULL + AND @userSignature IS NOT NULL + THEN + SELECT loginKey INTO vKey FROM userConfig; + SET vSignature = util.hmacSha2(256, CONCAT_WS('/', @userId, @userName), vKey); + RETURN vSignature = @userSignature; + END IF; - WHILE LENGTH(vPwd) < vMinLength OR vAlpha < vMinAlpha - OR vUpper < vMinUpper OR vDigits < vMinDigits OR vPunct < vMinPunct DO - SET vRandIndex = FLOOR((RAND() * 4) + 1); - - CASE - WHEN vRandIndex = 1 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vAlphaChars, FLOOR((RAND() * 26) + 1), 1)); - SET vAlpha = vAlpha + 1; - WHEN vRandIndex = 2 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vUpperChars, FLOOR((RAND() * 26) + 1), 1)); - SET vUpper = vUpper + 1; - WHEN vRandIndex = 3 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vDigitChars, FLOOR((RAND() * 10) + 1), 1)); - SET vDigits = vDigits + 1; - WHEN vRandIndex = 4 THEN - SET vPwd = CONCAT(vPwd, SUBSTRING(vPunctChars, FLOOR((RAND() * LENGTH(vPunctChars)) + 1), 1)); - SET vPunct = vPunct + 1; - END CASE; - END WHILE; -RETURN vPwd; + RETURN FALSE; +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 `myUser_getId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUser_getId`() RETURNS int(11) + READS SQL DATA + DETERMINISTIC +BEGIN +/** + * Returns the current user id. + * + * @return The user id + */ + DECLARE vUser INT DEFAULT NULL; + + IF myUser_checkLogin() + THEN + SET vUser = @userId; + ELSE + SELECT id INTO vUser FROM user + WHERE name = LEFT(USER(), INSTR(USER(), '@') - 1); + END IF; + + RETURN vUser; +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 `myUser_getName` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUser_getName`() RETURNS varchar(30) CHARSET utf8 + NO SQL + DETERMINISTIC +BEGIN +/** + * Returns the current user name. + * + * @return The user name + */ + DECLARE vUser VARCHAR(30) DEFAULT NULL; + + IF myUser_checkLogin() + THEN + SET vUser = @userName; + ELSE + SET vUser = LEFT(USER(), INSTR(USER(), '@') - 1); + END IF; + + RETURN vUser; +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 `myUser_hasRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUser_hasRole`(vRoleName VARCHAR(255)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Checks if current user has/inherits a role. + * + * @param vRoleName Role to check + * @return %TRUE if it has role, %FALSE otherwise + */ + RETURN user_hasRole(myUser_getName(), vRoleName); +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 `myUser_hasRoleId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `myUser_hasRoleId`(vRoleId INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Checks if current user has/inherits a role. + * + * @param vRoleName Role id to check + * @return %TRUE if it has role, %FALSE otherwise + */ + RETURN user_hasRoleId(myUserGetName(), vRoleId); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -761,43 +905,9 @@ CREATE DEFINER=`root`@`%` FUNCTION `userGetId`() RETURNS int(11) DETERMINISTIC BEGIN /** - * @deprecated Use myUserGetId() + * @deprecated Use myUser_getId() */ - RETURN myUserGetId(); -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 `userGetMysqlRole` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userGetMysqlRole`(vUserName VARCHAR(255)) RETURNS varchar(255) CHARSET utf8 -BEGIN -/** - * A partir de un nombre de usuario devuelve el rol - * de MySQL asociado y con el que deberia autenticarse - * cuando se utilice sistemas de autenticación externos. - * - * @param vUserName El nombre de usuario - * @return El rol de MySQL asociado - */ - DECLARE vRole VARCHAR(255); - - SELECT CONCAT(IF(r.hasLogin, 'z-', ''), r.name) INTO vRole - FROM role r - JOIN user u ON u.role = r.id - WHERE u.name = vUserName; - - RETURN vRole; + RETURN myUser_getId(); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -819,40 +929,9 @@ CREATE DEFINER=`root`@`%` FUNCTION `userGetName`() RETURNS varchar(30) CHARSET u DETERMINISTIC BEGIN /** - * @deprecated Use myUserGetName() - */ - RETURN myUserGetName(); -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 `userGetNameFromId` */; -/*!50003 SET @saved_cs_client = @@character_set_client */ ; -/*!50003 SET @saved_cs_results = @@character_set_results */ ; -/*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; -/*!50003 SET @saved_sql_mode = @@sql_mode */ ; -/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; -DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userGetNameFromId`(vId INT) RETURNS varchar(30) CHARSET utf8 -BEGIN -/** - * Obtener nombre de usuari a partir de su id - * - * @param vId Id del usuario - * @return Nombre de usuario - */ - DECLARE vName VARCHAR(30); - - SELECT `name` INTO vName - FROM user - WHERE id = vId; - - RETURN vName; + * @deprecated Use myUser_getName() + */ + RETURN myUser_getName(); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -869,26 +948,13 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` FUNCTION `userHasRole`(vUser VARCHAR(255), vRoleName VARCHAR(255)) RETURNS tinyint(1) +CREATE DEFINER=`root`@`%` FUNCTION `userHasRole`(vUserName VARCHAR(255), vRoleName VARCHAR(255)) RETURNS tinyint(1) DETERMINISTIC BEGIN /** - * Comprueba si un usuario implementa un rol. - * - * @param vUser The user name - * @param vRoleName Nombre del rol a comprobar - * @return %TRUE si tiene el rol, %FALSE en caso contrario + * @deprecated Use user_hasRole() */ - DECLARE vHasRole BOOL DEFAULT FALSE; - - SELECT COUNT(*) > 0 INTO vHasRole - FROM user u - JOIN roleRole rr ON rr.role = u.role - JOIN role r ON r.id = rr.inheritsFrom - WHERE u.`name` = vUser - AND r.`name` = vRoleName COLLATE 'utf8_unicode_ci'; - - RETURN vHasRole; + RETURN user_hasRole(vUserName, vRoleName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -909,21 +975,80 @@ CREATE DEFINER=`root`@`%` FUNCTION `userHasRoleId`(vUser VARCHAR(255), vRoleId I DETERMINISTIC BEGIN /** - * Comprueba si un usuario implementa un rol. + * @deprecated Use user_hasRoleId() + */ + RETURN user_hasRoleId(vUser, vRoleId); +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 `user_hasRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `user_hasRole`(vUserName VARCHAR(255), vRoleName VARCHAR(255)) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Checks if user has/inherits a role. * - * @param vUser The user name - * @param vRoleId Identificador del rol a comprobar - * @return %TRUE si tiene el rol, %FALSE en caso contrario + * @param vUserName The user name + * @param vRoleName Role to check + * @return %TRUE if it has role, %FALSE otherwise */ DECLARE vHasRole BOOL DEFAULT FALSE; - SELECT COUNT(*) > 0 INTO vHasRole + SELECT COUNT(*) > 0 INTO vHasRole + FROM user u + JOIN roleRole rr ON rr.role = u.role + JOIN role r ON r.id = rr.inheritsFrom + WHERE u.`name` = vUserName + AND r.`name` = vRoleName COLLATE 'utf8_unicode_ci'; + + RETURN vHasRole; +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 `user_hasRoleId` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `user_hasRoleId`(vUser VARCHAR(255), vRoleId INT) RETURNS tinyint(1) + DETERMINISTIC +BEGIN +/** + * Checks if user has/inherits a role. + * + * @param vUserName The user name + * @param vRoleId Role id to check + * @return %TRUE if it has role, %FALSE otherwise + */ + DECLARE vHasRole BOOL DEFAULT FALSE; + + SELECT COUNT(*) > 0 INTO vHasRole FROM user u JOIN roleRole rr ON rr.role = u.role JOIN role r ON r.id = rr.inheritsFrom WHERE u.`name` = vUser AND r.id = vRoleId; - + RETURN vHasRole; END ;; DELIMITER ; @@ -944,24 +1069,9 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `myUserChangePassword`(vOldPassword VARCHAR(255), vPassword VARCHAR(255)) BEGIN /** - * Changes the current user password, if user is in recovery - * mode ignores the current password. - * - * @param vOldPassword The current password - * @param vPassword The new password + * @deprecated Use myUser_changePassword() */ - DECLARE vPasswordOk BOOL; - - SELECT `password` = MD5(vOldPassword) OR recoverPass - INTO vPasswordOk - FROM user WHERE id = myUserGetId(); - - IF NOT vPasswordOk THEN - SIGNAL SQLSTATE '45000' - SET MESSAGE_TEXT = 'Invalid password'; - END IF; - - CALL userSetPassword(myUserGetName(), vPassword); + CALL myUser_changePassword(vOldPassword, vPassword); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -981,8 +1091,165 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `myUserLogout`() BEGIN /** - * Logouts the user. + * @deprecated Use myUser_Logout() */ + CALL myUser_logout; +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 `myUser_changePassword` */; +/*!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 `myUser_changePassword`(vOldPassword VARCHAR(255), vPassword VARCHAR(255)) +BEGIN +/** + * Changes the current user password, if user is in recovery mode ignores the + * current password. + * + * @param vOldPassword The current password + * @param vPassword The new password + */ + CALL user_changePassword(myUser_getId(), vOldPassword, vPassword); +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 `myUser_login` */; +/*!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 `myUser_login`(vUserName VARCHAR(255), vPassword VARCHAR(255)) + READS SQL DATA +BEGIN +/** + * Logs in using the user credentials. + * + * @param vUserName The user name + * @param vPassword The user password + */ + DECLARE vAuthIsOk BOOLEAN DEFAULT FALSE; + + SELECT COUNT(*) = 1 INTO vAuthIsOk FROM user + WHERE name = vUserName + AND password = MD5(vPassword) + AND active; + + IF vAuthIsOk + THEN + CALL myUser_loginWithName (vUserName); + ELSE + CALL util.throw ('INVALID_CREDENTIALS'); + 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 `myUser_loginWithKey` */; +/*!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 `myUser_loginWithKey`(vUserName VARCHAR(255), vKey VARCHAR(255)) + READS SQL DATA +BEGIN +/** + * Logs in using the user name and MySQL master key. + * + * @param vUserName The user name + * @param vKey The MySQL master key + */ + DECLARE vLoginKey VARCHAR(255); + + SELECT loginKey INTO vLoginKey FROM userConfig; + + IF vLoginKey = vKey THEN + CALL myUser_loginWithName(vUserName); + ELSE + CALL util.throw('INVALID_KEY'); + 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 `myUser_loginWithName` */; +/*!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 `myUser_loginWithName`(vUserName VARCHAR(255)) + READS SQL DATA +BEGIN +/** + * Logs in using only the user name. This procedure is intended to be executed + * by users with a high level of privileges so that normal users should not have + * execute permissions on it. + * + * @param vUserName The user name + */ + DECLARE vUserId INT DEFAULT NULL; + DECLARE vKey VARCHAR(255); + + SELECT id INTO vUserId FROM user + WHERE name = vUserName; + + SELECT loginKey INTO vKey FROM userConfig; + + SET @userId = vUserId; + SET @userName = vUserName; + SET @userSignature = util.hmacSha2(256, CONCAT_WS('/', vUserId, vUserName), vKey); +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 `myUser_logout` */; +/*!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 `myUser_logout`() +BEGIN +/** + * Logouts the user. + */ SET @userId = NULL; SET @userName = NULL; SET @userSignature = NULL; @@ -992,24 +1259,53 @@ 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 `role_checkName` */; +/*!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 `role_checkName`(vRoleName VARCHAR(255)) +BEGIN +/** + * Checks that role name meets the necessary syntax requirements, otherwise it + * throws an exception. + * Role name must be written in camelCase. + * + * @param vRoleName The role name + */ + IF BINARY vRoleName NOT REGEXP '^[a-z][a-zA-Z]+$' THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Role name must be written in camelCase'; + 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 `role_getDescendents` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `role_getDescendents`(vSelf INT) BEGIN /** - * Obtiene los identificadores de todos los subroles - * implementados por un rol (Incluido el mismo). + * Gets the identifiers of all the subroles implemented by a role (Including + * itself). * - * @param vSelf Identificador del rol - * @table tmp.role Subroles implementados por el rol + * @param vSelf The role identifier + * @table tmp.role Subroles implemented by the role */ DECLARE vIsRoot BOOL; @@ -1050,8 +1346,9 @@ BEGIN -- If it is root all the roles are added SELECT COUNT(*) > 0 INTO vIsRoot - FROM tmp.role - WHERE id = 0; + FROM tmp.role t + JOIN role r ON r.id = t.id + WHERE r.`name` = 'root'; IF vIsRoot THEN INSERT IGNORE INTO tmp.role (id) @@ -1072,19 +1369,18 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `role_sync`() BEGIN /** - * Sincroniza la tabla @roleRole con la jerarquía de roles - * actual. Este procedimiento debe ser llamado cada vez que - * se modifique la tabla @roleInherit para que los cambios - * realizados sobre esta sean efectivos. + * Synchronize the @roleRole table with the current role hierarchy. This + * procedure must be called every time the @roleInherit table is modified so + * that the changes made on it are effective. */ DECLARE vRoleId INT; DECLARE vDone BOOL; @@ -1093,8 +1389,11 @@ BEGIN SELECT id FROM role; DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - TRUNCATE TABLE roleRole; + + DROP TEMPORARY TABLE IF EXISTS tRoleRole; + CREATE TEMPORARY TABLE tRoleRole + ENGINE = MEMORY + SELECT * FROM roleRole LIMIT 0; OPEN cur; @@ -1108,15 +1407,22 @@ BEGIN CALL role_getDescendents(vRoleId); - INSERT INTO roleRole (role, inheritsFrom) + INSERT INTO tRoleRole (role, inheritsFrom) SELECT vRoleId, id FROM tmp.role; - + DROP TEMPORARY TABLE tmp.role; END LOOP; CLOSE cur; - - CALL role_syncPrivileges; + + START TRANSACTION; + DELETE FROM roleRole; + INSERT INTO roleRole SELECT * FROM tRoleRole; + COMMIT; + + DROP TEMPORARY TABLE tRoleRole; + + CALL role_syncPrivileges; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -1127,36 +1433,37 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `role_syncPrivileges`() BEGIN /** - * Sincroniza los permisos de los usuarios 'rol' de MySQL - * en base a la jerarquía de roles. Los usuarios rol resultantes - * de la mezcla de permisos serán nombrados singuiendo el patrón - * z-[nombre_rol]. + * Synchronizes permissions of MySQL role users based on role hierarchy. + * The computed role users of permission mix will be named according to + * pattern z-[role_name]. * - * Si existe el usuario any@localhost que se tomará como plantilla - * para los atributos básicos. + * If any@localhost user exists, it will be taken as a template for basic + * attributes. * - * ¡Atención! Este procedimiento solo debe ser llamado cuando se - * modifiquen los privilegios de MySQL. Si se modifica la jerarquía - * de roles, se debe llamar al procedimiento roleSync() que llama a - * este internamente. + * Warning! This procedure should only be called when MySQL privileges + * are modified. If role hierarchy is modified, you must call the role_sync() + * procedure wich calls this internally. */ + DECLARE vIsMysql BOOL DEFAULT VERSION() NOT LIKE '%MariaDB%'; + DECLARE vVersion INT DEFAULT SUBSTRING_INDEX(VERSION(), '.', 1); DECLARE vTplUser VARCHAR(255) DEFAULT 'any'; DECLARE vTplHost VARCHAR(255) DEFAULT '%'; DECLARE vRoleHost VARCHAR(255) DEFAULT 'localhost'; DECLARE vAllHost VARCHAR(255) DEFAULT '%'; DECLARE vPrefix VARCHAR(2) DEFAULT 'z-'; DECLARE vPrefixedLike VARCHAR(255); - - -- Borra todos los privilegios calculados + DECLARE vPassword VARCHAR(255) DEFAULT ''; + + -- Deletes computed role users SET vPrefixedLike = CONCAT(vPrefix, '%'); @@ -1178,7 +1485,7 @@ BEGIN DELETE FROM mysql.proxies_priv WHERE `Proxied_user` LIKE vPrefixedLike; - -- Tablas temporales + -- Temporary tables DROP TEMPORARY TABLE IF EXISTS tRole; CREATE TEMPORARY TABLE tRole @@ -1202,57 +1509,145 @@ BEGIN JOIN roleRole rr ON rr.role = r.id JOIN role ri ON ri.id = rr.inheritsFrom; - -- Vueve a crear el usuario + -- Recreate role users - INSERT INTO mysql.user ( - `User`, - `Host`, - `Password`, - `ssl_type`, - `ssl_cipher`, - `x509_issuer`, - `x509_subject`, - `max_questions`, - `max_updates`, - `max_connections`, - `max_user_connections` - ) - SELECT - r.prefixedRole, - vTplHost, - IFNULL(t.`Password`, ''), - IFNULL(IF('' != u.`ssl_type`, - u.`ssl_type`, t.`ssl_type`), - ''), - IFNULL(IF('' != u.`ssl_cipher`, - u.`ssl_cipher`, t.`ssl_cipher`), - ''), - IFNULL(IF('' != u.`x509_issuer`, - u.`x509_issuer`, t.`x509_issuer`), - ''), - IFNULL(IF('' != u.`x509_subject`, - u.`x509_subject`, t.`x509_subject`), - ''), - IFNULL(IF(0 != u.`max_questions`, - u.`max_questions`, t.`max_questions`), - 0), - IFNULL(IF(0 != u.`max_updates`, - u.`max_updates`, t.`max_updates`), - 0), - IFNULL(IF(0 != u.`max_connections`, - u.`max_connections`, t.`max_connections`), - 0), - IFNULL(IF(0 != u.`max_user_connections`, - u.`max_user_connections`, t.`max_user_connections`), - 0) - FROM tRole r - LEFT JOIN mysql.user t - ON t.`User` = vTplUser - AND t.`Host` = vRoleHost - LEFT JOIN mysql.user u - ON u.`User` = r.role - AND u.`Host` = vRoleHost; + IF vIsMysql THEN + DROP TEMPORARY TABLE IF EXISTS tUser; + CREATE TEMPORARY TABLE tUser + SELECT + r.prefixedRole `User`, + vTplHost `Host`, + IFNULL(t.`authentication_string`, + '') `authentication_string`, + IFNULL(t.`plugin`, + 'mysql_native_password') `plugin`, + IFNULL(IF('' != u.`ssl_type`, + u.`ssl_type`, t.`ssl_type`), + '') `ssl_type`, + IFNULL(IF('' != u.`ssl_cipher`, + u.`ssl_cipher`, t.`ssl_cipher`), + '') `ssl_cipher`, + IFNULL(IF('' != u.`x509_issuer`, + u.`x509_issuer`, t.`x509_issuer`), + '') `x509_issuer`, + IFNULL(IF('' != u.`x509_subject`, + u.`x509_subject`, t.`x509_subject`), + '') `x509_subject`, + IFNULL(IF(0 != u.`max_questions`, + u.`max_questions`, t.`max_questions`), + 0) `max_questions`, + IFNULL(IF(0 != u.`max_updates`, + u.`max_updates`, t.`max_updates`), + 0) `max_updates`, + IFNULL(IF(0 != u.`max_connections`, + u.`max_connections`, t.`max_connections`), + 0) `max_connections`, + IFNULL(IF(0 != u.`max_user_connections`, + u.`max_user_connections`, t.`max_user_connections`), + 0) `max_user_connections` + FROM tRole r + LEFT JOIN mysql.user t + ON t.`User` = vTplUser + AND t.`Host` = vRoleHost + LEFT JOIN mysql.user u + ON u.`User` = r.role + AND u.`Host` = vRoleHost; + IF vVersion <= 5 THEN + SELECT `Password` INTO vPassword + FROM mysql.user + WHERE `User` = vTplUser + AND `Host` = vRoleHost; + + INSERT INTO mysql.user ( + `User`, + `Host`, + `Password`, + `authentication_string`, + `plugin`, + `ssl_type`, + `ssl_cipher`, + `x509_issuer`, + `x509_subject`, + `max_questions`, + `max_updates`, + `max_connections`, + `max_user_connections` + ) + SELECT + `User`, + `Host`, + vPassword, + `authentication_string`, + `plugin`, + `ssl_type`, + `ssl_cipher`, + `x509_issuer`, + `x509_subject`, + `max_questions`, + `max_updates`, + `max_connections`, + `max_user_connections` + FROM tUser; + ELSE + INSERT INTO mysql.user ( + `User`, + `Host`, + `authentication_string`, + `plugin`, + `ssl_type`, + `ssl_cipher`, + `x509_issuer`, + `x509_subject`, + `max_questions`, + `max_updates`, + `max_connections`, + `max_user_connections` + ) + SELECT + `User`, + `Host`, + `authentication_string`, + `plugin`, + `ssl_type`, + `ssl_cipher`, + `x509_issuer`, + `x509_subject`, + `max_questions`, + `max_updates`, + `max_connections`, + `max_user_connections` + FROM tUser; + END IF; + + DROP TEMPORARY TABLE IF EXISTS tUser; + ELSE + INSERT INTO mysql.global_priv ( + `User`, + `Host`, + `Priv` + ) + SELECT + r.prefixedRole, + vTplHost, + JSON_MERGE_PATCH( + IFNULL(t.`Priv`, '{}'), + IFNULL(u.`Priv`, '{}'), + JSON_OBJECT( + 'mysql_old_password', JSON_VALUE(t.`Priv`, '$.mysql_old_password'), + 'mysql_native_password', JSON_VALUE(t.`Priv`, '$.mysql_native_password'), + 'authentication_string', JSON_VALUE(t.`Priv`, '$.authentication_string') + ) + ) + FROM tRole r + LEFT JOIN mysql.global_priv t + ON t.`User` = vTplUser + AND t.`Host` = vRoleHost + LEFT JOIN mysql.global_priv u + ON u.`User` = r.role + AND u.`Host` = vRoleHost; + END IF; + INSERT INTO mysql.proxies_priv ( `User`, `Host`, @@ -1268,117 +1663,138 @@ BEGIN CONCAT(prefixedRole, '@', vTplHost) FROM tRole; - -- Copia los privilegios globales del usuario + -- Copies global privileges DROP TEMPORARY TABLE IF EXISTS tUserPriv; - CREATE TEMPORARY TABLE tUserPriv - (INDEX (prefixedRole)) - ENGINE = MEMORY - SELECT - r.prefixedRole, - MAX(u.`Select_priv`) `Select_priv`, - MAX(u.`Insert_priv`) `Insert_priv`, - MAX(u.`Update_priv`) `Update_priv`, - MAX(u.`Delete_priv`) `Delete_priv`, - MAX(u.`Create_priv`) `Create_priv`, - MAX(u.`Drop_priv`) `Drop_priv`, - MAX(u.`Reload_priv`) `Reload_priv`, - MAX(u.`Shutdown_priv`) `Shutdown_priv`, - MAX(u.`Process_priv`) `Process_priv`, - MAX(u.`File_priv`) `File_priv`, - MAX(u.`Grant_priv`) `Grant_priv`, - MAX(u.`References_priv`) `References_priv`, - MAX(u.`Index_priv`) `Index_priv`, - MAX(u.`Alter_priv`) `Alter_priv`, - MAX(u.`Show_db_priv`) `Show_db_priv`, - MAX(u.`Super_priv`) `Super_priv`, - MAX(u.`Create_tmp_table_priv`) `Create_tmp_table_priv`, - MAX(u.`Lock_tables_priv`) `Lock_tables_priv`, - MAX(u.`Execute_priv`) `Execute_priv`, - MAX(u.`Repl_slave_priv`) `Repl_slave_priv`, - MAX(u.`Repl_client_priv`) `Repl_client_priv`, - MAX(u.`Create_view_priv`) `Create_view_priv`, - MAX(u.`Show_view_priv`) `Show_view_priv`, - MAX(u.`Create_routine_priv`) `Create_routine_priv`, - MAX(u.`Alter_routine_priv`) `Alter_routine_priv`, - MAX(u.`Create_user_priv`) `Create_user_priv`, - MAX(u.`Event_priv`) `Event_priv`, - MAX(u.`Trigger_priv`) `Trigger_priv`, - MAX(u.`Create_tablespace_priv`) `Create_tablespace_priv` - FROM tRoleInherit r - JOIN mysql.user u - ON u.`User` = r.inheritsFrom - AND u.`Host`= vRoleHost - GROUP BY r.prefixedRole; - UPDATE mysql.user u - JOIN tUserPriv t - ON u.`User` = t.prefixedRole - AND u.`Host` = vTplHost - SET - u.`Select_priv` - = t.`Select_priv`, - u.`Insert_priv` - = t.`Insert_priv`, - u.`Update_priv` - = t.`Update_priv`, - u.`Delete_priv` - = t.`Delete_priv`, - u.`Create_priv` - = t.`Create_priv`, - u.`Drop_priv` - = t.`Drop_priv`, - u.`Reload_priv` - = t.`Reload_priv`, - u.`Shutdown_priv` - = t.`Shutdown_priv`, - u.`Process_priv` - = t.`Process_priv`, - u.`File_priv` - = t.`File_priv`, - u.`Grant_priv` - = t.`Grant_priv`, - u.`References_priv` - = t.`References_priv`, - u.`Index_priv` - = t.`Index_priv`, - u.`Alter_priv` - = t.`Alter_priv`, - u.`Show_db_priv` - = t.`Show_db_priv`, - u.`Super_priv` - = t.`Super_priv`, - u.`Create_tmp_table_priv` - = t.`Create_tmp_table_priv`, - u.`Lock_tables_priv` - = t.`Lock_tables_priv`, - u.`Execute_priv` - = t.`Execute_priv`, - u.`Repl_slave_priv` - = t.`Repl_slave_priv`, - u.`Repl_client_priv` - = t.`Repl_client_priv`, - u.`Create_view_priv` - = t.`Create_view_priv`, - u.`Show_view_priv` - = t.`Show_view_priv`, - u.`Create_routine_priv` - = t.`Create_routine_priv`, - u.`Alter_routine_priv` - = t.`Alter_routine_priv`, - u.`Create_user_priv` - = t.`Create_user_priv`, - u.`Event_priv` - = t.`Event_priv`, - u.`Trigger_priv` - = t.`Trigger_priv`, - u.`Create_tablespace_priv` - = t.`Create_tablespace_priv`; + IF vIsMysql THEN + CREATE TEMPORARY TABLE tUserPriv + (INDEX (prefixedRole)) + ENGINE = MEMORY + SELECT + r.prefixedRole, + MAX(u.`Select_priv`) `Select_priv`, + MAX(u.`Insert_priv`) `Insert_priv`, + MAX(u.`Update_priv`) `Update_priv`, + MAX(u.`Delete_priv`) `Delete_priv`, + MAX(u.`Create_priv`) `Create_priv`, + MAX(u.`Drop_priv`) `Drop_priv`, + MAX(u.`Reload_priv`) `Reload_priv`, + MAX(u.`Shutdown_priv`) `Shutdown_priv`, + MAX(u.`Process_priv`) `Process_priv`, + MAX(u.`File_priv`) `File_priv`, + MAX(u.`Grant_priv`) `Grant_priv`, + MAX(u.`References_priv`) `References_priv`, + MAX(u.`Index_priv`) `Index_priv`, + MAX(u.`Alter_priv`) `Alter_priv`, + MAX(u.`Show_db_priv`) `Show_db_priv`, + MAX(u.`Super_priv`) `Super_priv`, + MAX(u.`Create_tmp_table_priv`) `Create_tmp_table_priv`, + MAX(u.`Lock_tables_priv`) `Lock_tables_priv`, + MAX(u.`Execute_priv`) `Execute_priv`, + MAX(u.`Repl_slave_priv`) `Repl_slave_priv`, + MAX(u.`Repl_client_priv`) `Repl_client_priv`, + MAX(u.`Create_view_priv`) `Create_view_priv`, + MAX(u.`Show_view_priv`) `Show_view_priv`, + MAX(u.`Create_routine_priv`) `Create_routine_priv`, + MAX(u.`Alter_routine_priv`) `Alter_routine_priv`, + MAX(u.`Create_user_priv`) `Create_user_priv`, + MAX(u.`Event_priv`) `Event_priv`, + MAX(u.`Trigger_priv`) `Trigger_priv`, + MAX(u.`Create_tablespace_priv`) `Create_tablespace_priv` + FROM tRoleInherit r + JOIN mysql.user u + ON u.`User` = r.inheritsFrom + AND u.`Host`= vRoleHost + GROUP BY r.prefixedRole; + + UPDATE mysql.user u + JOIN tUserPriv t + ON u.`User` = t.prefixedRole + AND u.`Host` = vTplHost + SET + u.`Select_priv` + = t.`Select_priv`, + u.`Insert_priv` + = t.`Insert_priv`, + u.`Update_priv` + = t.`Update_priv`, + u.`Delete_priv` + = t.`Delete_priv`, + u.`Create_priv` + = t.`Create_priv`, + u.`Drop_priv` + = t.`Drop_priv`, + u.`Reload_priv` + = t.`Reload_priv`, + u.`Shutdown_priv` + = t.`Shutdown_priv`, + u.`Process_priv` + = t.`Process_priv`, + u.`File_priv` + = t.`File_priv`, + u.`Grant_priv` + = t.`Grant_priv`, + u.`References_priv` + = t.`References_priv`, + u.`Index_priv` + = t.`Index_priv`, + u.`Alter_priv` + = t.`Alter_priv`, + u.`Show_db_priv` + = t.`Show_db_priv`, + u.`Super_priv` + = t.`Super_priv`, + u.`Create_tmp_table_priv` + = t.`Create_tmp_table_priv`, + u.`Lock_tables_priv` + = t.`Lock_tables_priv`, + u.`Execute_priv` + = t.`Execute_priv`, + u.`Repl_slave_priv` + = t.`Repl_slave_priv`, + u.`Repl_client_priv` + = t.`Repl_client_priv`, + u.`Create_view_priv` + = t.`Create_view_priv`, + u.`Show_view_priv` + = t.`Show_view_priv`, + u.`Create_routine_priv` + = t.`Create_routine_priv`, + u.`Alter_routine_priv` + = t.`Alter_routine_priv`, + u.`Create_user_priv` + = t.`Create_user_priv`, + u.`Event_priv` + = t.`Event_priv`, + u.`Trigger_priv` + = t.`Trigger_priv`, + u.`Create_tablespace_priv` + = t.`Create_tablespace_priv`; + ELSE + CREATE TEMPORARY TABLE tUserPriv + (INDEX (prefixedRole)) + SELECT + r.prefixedRole, + BIT_OR(JSON_VALUE(p.`Priv`, '$.access')) access + FROM tRoleInherit r + JOIN mysql.global_priv p + ON p.`User` = r.inheritsFrom + AND p.`Host`= vRoleHost + GROUP BY r.prefixedRole; + + UPDATE mysql.global_priv p + JOIN tUserPriv t + ON p.`User` = t.prefixedRole + AND p.`Host` = vTplHost + SET + p.`Priv` = JSON_SET(p.`Priv`, '$.access', t.access); + END IF; DROP TEMPORARY TABLE tUserPriv; - - -- Copia los privilegios a nivel de esquema - + + -- Copy schema level privileges + INSERT INTO mysql.db ( `User`, `Host`, @@ -1431,8 +1847,8 @@ BEGIN ON t.`User` = r.inheritsFrom AND t.`Host`= vRoleHost GROUP BY r.prefixedRole, t.`Db`; - - -- Copia los privilegios a nivel de tabla + + -- Copy table level privileges INSERT INTO mysql.tables_priv ( `User`, @@ -1459,7 +1875,7 @@ BEGIN AND t.`Host`= vRoleHost GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`; - -- Copia los privilegios a nivel de columna + -- Copy column level privileges INSERT INTO mysql.columns_priv ( `User`, @@ -1484,7 +1900,7 @@ BEGIN AND t.`Host`= vRoleHost GROUP BY r.prefixedRole, t.`Db`, t.`Table_name`, t.`Column_name`; - -- Copia los privilegios de los procedimientos + -- Copy routine privileges INSERT IGNORE INTO mysql.procs_priv ( `User`, @@ -1509,8 +1925,8 @@ BEGIN JOIN mysql.procs_priv t ON t.`User` = r.inheritsFrom AND t.`Host`= vRoleHost; - - -- Libera memoria + + -- Free memory DROP TEMPORARY TABLE tRole, @@ -1537,24 +1953,9 @@ CREATE DEFINER=`root`@`%` PROCEDURE `userLogin`(vUserName VARCHAR(255), vPasswor READS SQL DATA BEGIN /** - * Logs in using the user credentials. - * - * @param vUserName The user name - * @param vPassword The user password + * @deprecated Use myUser_login() */ - DECLARE vAuthIsOk BOOLEAN DEFAULT FALSE; - - SELECT COUNT(*) = 1 INTO vAuthIsOk FROM user - WHERE name = vUserName - AND password = MD5(vPassword) - AND active; - - IF vAuthIsOk - THEN - CALL userLoginWithName (vUserName); - ELSE - CALL util.throw ('INVALID_CREDENTIALS'); - END IF; + CALL myUser_login(vUserName, vPassword); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -1575,20 +1976,9 @@ CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithKey`(vUserName VARCHAR(255), v READS SQL DATA BEGIN /** - * Logs in using the user name and MySQL master key. - * - * @param vUserName The user name - * @param vKey The MySQL master key + * @deprecated Use myUser_loginWithKey() */ - DECLARE vLoginKey VARCHAR(255); - - SELECT loginKey INTO vLoginKey FROM userConfig; - - IF vLoginKey = vKey THEN - CALL userLoginWithName(vUserName); - ELSE - CALL util.throw('INVALID_KEY'); - END IF; + CALL myUser_loginWithKey(vUserName, vKey); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -1609,24 +1999,9 @@ CREATE DEFINER=`root`@`%` PROCEDURE `userLoginWithName`(vUserName VARCHAR(255)) READS SQL DATA BEGIN /** - * Logs in using only the user name. This procedure is - * intended to be executed by users with a high level - * of privileges so that normal users should not have - * execute permissions on it - * - * @param vUserName The user name + * @deprecated Use myUser_loginWithName() */ - DECLARE vUserId INT DEFAULT NULL; - DECLARE vKey VARCHAR(255); - - SELECT id INTO vUserId FROM user - WHERE name = vUserName; - - SELECT loginKey INTO vKey FROM userConfig; - - SET @userId = vUserId; - SET @userName = vUserName; - SET @userSignature = util.hmacSha2(256, CONCAT_WS('/', vUserId, vUserName), vKey); + CALL myUser_loginWithName(vUserName); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -1637,36 +2012,61 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `userSetPassword`(vUserName VARCHAR(255), vPassword VARCHAR(255)) BEGIN /** - * Cambia la contraseña del usuario pasado como parámetro. - * Solo los administradores deberian de tener privilegios de - * ejecución sobre el procedimiento ya que no solicita la - * contraseña actual del usuario. - * - * @param vUserName Nombre de usuario - * @param vPassword Nueva contraseña + * @deprecated Use user_setPassword() */ - DECLARE vSelf INT; + DECLARE vUserId INT; - CALL user_checkPassword(vPassword); - - SELECT id INTO vSelf + SELECT id INTO vUserId FROM user WHERE `name` = vUserName; - UPDATE user SET - `password` = MD5(vPassword), - `recoverPass` = FALSE - WHERE id = vSelf; - - CALL user_syncPassword(vSelf, vPassword); + CALL user_setPassword(vUserId, vPassword); +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 `user_changePassword` */; +/*!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 `user_changePassword`(vSelf INT, vOldPassword VARCHAR(255), vPassword VARCHAR(255)) +BEGIN +/** + * Changes the user password. + * + * @param vSelf The user id + * @param vOldPassword The current password + * @param vPassword The new password + */ + DECLARE vPasswordOk BOOL; + DECLARE vUserName VARCHAR(255); + + SELECT `password` = MD5(vOldPassword), `name` + INTO vPasswordOk, vUserName + FROM user WHERE id = vSelf; + + IF NOT vPasswordOk THEN + SIGNAL SQLSTATE '45000' + SET MESSAGE_TEXT = 'Invalid password'; + END IF; + + CALL user_setPassword(vSelf, vPassword); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -1677,20 +2077,19 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `user_checkName`(vUserName VARCHAR(255)) BEGIN /** - * Comprueba que el nombre de usuario reune los requisitos - * de sintaxis necesarios, en caso contrario lanza una - * excepción. - * El nombre de usuario solo debe contener letras minúsculas - * o, a partir del segundo carácter, números o subguiones. + * Checks that username meets the necessary syntax requirements, otherwise it + * throws an exception. + * The user name must only contain lowercase letters or, starting with second + * character, numbers or underscores. */ IF vUserName NOT REGEXP '^[a-z0-9_-]*$' THEN SIGNAL SQLSTATE '45000' @@ -1770,30 +2169,32 @@ 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 `user_syncPassword` */; +/*!50003 DROP PROCEDURE IF EXISTS `user_setPassword` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `user_syncPassword`( - vSelf VARCHAR(255), - vPassword VARCHAR(255) -) +CREATE DEFINER=`root`@`%` PROCEDURE `user_setPassword`(vSelf INT, vPassword VARCHAR(255)) BEGIN /** - * Synchronizes the user password in other schemes. + * Change the password of the passed as a parameter. Only administrators should + * have execute privileges on the procedure since it does not request the user's + * current password. * * @param vSelf The user id - * @param vPassword The user password + * @param vPassword New password */ - CALL pbx.sip_setPassword(vSelf, vPassword); + CALL user_checkPassword(vPassword); - DELETE FROM salix.user WHERE id = vSelf; + UPDATE user SET + `password` = MD5(vPassword), + `recoverPass` = FALSE + WHERE id = vSelf; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -2510,6 +2911,23 @@ CREATE TABLE `salesPersonClient` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Ventas por comercial por cliente'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `v_ventas__` +-- + +DROP TABLE IF EXISTS `v_ventas__`; +/*!50001 DROP VIEW IF EXISTS `v_ventas__`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `v_ventas__` AS SELECT + 1 AS `importe`, + 1 AS `recargo`, + 1 AS `year`, + 1 AS `month`, + 1 AS `week`, + 1 AS `day`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `vendedores` -- @@ -2528,6 +2946,8 @@ CREATE TABLE `vendedores` ( `comisionNuevos` decimal(10,2) DEFAULT NULL, `sustitucionArrendada` decimal(10,2) DEFAULT NULL, `itemTypeBorrowed` decimal(10,2) DEFAULT NULL, + `portfolioWeight` decimal(10,2) DEFAULT NULL COMMENT 'Pero de la cartera del comercial a fecha vendedores.updated', + `updated` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -2569,7 +2989,7 @@ CREATE TABLE `ventas` ( KEY `tip_to_tip_idx` (`tipo_id`), KEY `clientes_bs_ventas_idx` (`Id_Cliente`), KEY `empresa_bs_ventas_idx` (`empresa_id`), - KEY `fecha_bs` (`fecha`), + KEY `fecha_bs` (`fecha`,`Id_Cliente`), CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, @@ -4925,42 +5345,7 @@ BEGIN SELECT wd.workerFk ownerWorkerFk, itemTypeFk, dit.workerFk substituteFk FROM vn.departmentItemType dit JOIN vn.workerDepartment wd ON wd.departmentFk = dit.departmentFk; - - -- itemType Lended, prestado - UPDATE salesPersonClient s - JOIN (SELECT c.salespersonFk, - c.id, - SUM(importe) * vCommissionRate AS amount, - t.`month`, - t.`year` - FROM ventas v - JOIN vn.client c on c.id = v.Id_Cliente - JOIN tmp.workerItemType wit ON wit.ownerWorkerFk = c.salespersonFk AND wit.itemTypeFk = v.tipo_id - JOIN vn.`time` t on t.dated = v.fecha - WHERE t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - GROUP BY c.salespersonFk, - c.id, - t.`month` - ) sub ON sub.salespersonFk = s.salespersonFk AND - sub.id = s.clientFk AND - sub.`month` = s.`month` AND - sub.`year` = s.`year` - SET s.comission = s.comission - sub.amount; - - -- itemType borrowed, tomado prestado - INSERT INTO salesPersonClient (salesPersonFk, clientFk, `year`, `month`, itemTypeBorrowed) - SELECT wit.substituteFk, - c.id, - t.`year`, - t.`month`, - importe * vCommissionRate - FROM ventas v - JOIN vn.client c on v.Id_Cliente = c.id - JOIN tmp.workerItemType wit ON wit.ownerWorkerFk = c.salesPersonFk AND wit.itemTypeFk = v.tipo_id - JOIN vn.`time` t on t.`dated` = v.fecha - WHERE t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter - ON DUPLICATE KEY UPDATE itemTypeBorrowed = itemTypeBorrowed + values(itemTypeBorrowed); - + DROP TEMPORARY TABLE tmp.workerItemType; END ;; @@ -5014,19 +5399,24 @@ DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(intYEAR INT, vQuarter INT) BEGIN - DECLARE vCommissionRate DOUBLE DEFAULT 0.008; - + DECLARE vCommissionRate DOUBLE; + + SELECT rate + INTO vCommissionRate + FROM vn.commissionConfig; + -- vaciar tabla DELETE v.* FROM vendedores v JOIN vn.`time` t ON t.`year` = v.año AND t.`month` = v.mes WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter; - REPLACE vendedores(Id_Trabajador, año, mes, importe, comision) + REPLACE vendedores(Id_Trabajador, año, mes, importe, comision, portfolioWeight) SELECT c.Id_Trabajador , intYEAR , MONTH(v.fecha) intMONTH , sum(v.importe) , sum(v.importe) * vCommissionRate + , sum(v.importe) FROM ventas v JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente JOIN vn.`time` t on t.dated = v.fecha @@ -5035,24 +5425,27 @@ BEGIN GROUP BY c.Id_Trabajador, t.`month`; -- Sustitucion cedidas - lended - INSERT INTO vendedores (Id_Trabajador, mes, año, comision) + INSERT INTO vendedores (Id_Trabajador, mes, año, importe, comision) SELECT c.salesPersonFk , t.`month` , t.`year` - , sum(importe) * vCommissionRate as lended + , - sum(importe) + , - sum(importe) * vCommissionRate as lended FROM ventas v JOIN vn.client c ON c.id = v.Id_Cliente JOIN vn.sharingCartDaily scd on scd.ownerFk = c.salesPersonFk AND scd.dated = v.fecha JOIN vn.`time` t ON t.dated = v.fecha WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter GROUP BY c.salesPersonFk, t.`month` - ON DUPLICATE KEY UPDATE comision = comision - VALUES(comision); + ON DUPLICATE KEY UPDATE comision = comision + VALUES(comision), + importe = importe + VALUES(importe); -- Sustitucion arrendadas - borrowed - INSERT INTO vendedores (Id_Trabajador, mes, año, sustitucionArrendada) + INSERT INTO vendedores (Id_Trabajador, mes, año, importe, comision) SELECT scd.substituteFk , t.`month` , t.`year` + , sum(importe) , sum(importe) * vCommissionRate as borrowed FROM ventas v JOIN vn.`client` c ON c.id = v.Id_Cliente @@ -5060,8 +5453,10 @@ BEGIN JOIN vn.`time` t ON t.dated = v.fecha WHERE t.`year` = intYEAR AND QUARTER(t.dated) = vQuarter GROUP BY scd.substituteFk, t.`month` - ON DUPLICATE KEY UPDATE sustitucionArrendada = VALUES(sustitucionArrendada); + ON DUPLICATE KEY UPDATE comision = comision + VALUES(comision), + importe = importe + VALUES(importe); + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -5381,6 +5776,42 @@ SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_updatePortfolio` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_updatePortfolio`() +BEGIN + /** + * Actualiza el campo portfolioWeight que indica el peso de la cartera del comercial + * + */ + DECLARE vStarted DATE DEFAULT DATE_FORMAT(DATE_ADD(CURDATE(), INTERVAL -17 MONTH), '%Y-%m-01'); + + INSERT INTO vendedores(Id_Trabajador, año, mes, portfolioWeight) + SELECT c.salesPersonFk + , t.`year` + , t.`month` + , SUM(v.importe) + FROM ventas v + JOIN vn.`client` c on c.id = v.Id_Cliente + JOIN vn.`time` t on t.dated = v.fecha + WHERE c.lastSalesPersonFk is not null + AND v.fecha >= vStarted + GROUP BY c.salesPersonFk, t.`month`, t.`year` + ON DUPLICATE KEY UPDATE portfolioWeight = VALUES(portfolioWeight); END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -7996,6 +8427,7 @@ CREATE TABLE `putOrder` ( `EndUserPartyGLN` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The grower can use this reference in his EKT in the NAD (MA) segment.', `OrderStatus` int(11) DEFAULT '0' COMMENT '1 pending\n2 confirmed\n3 canceled', `isOrderProcessed` tinyint(4) DEFAULT NULL, + `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; @@ -8960,14 +9392,15 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8mb4 */ ; -/*!50003 SET character_set_results = utf8mb4 */ ; -/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; CREATE DEFINER=`root`@`%` PROCEDURE `floramondo_offerRefresh`() -BEGIN +proc: BEGIN + DECLARE vLanded DATETIME; DECLARE done INT DEFAULT FALSE; DECLARE vFreeId INT; @@ -8989,6 +9422,13 @@ BEGIN RESIGNAL; END; + -- Campaña Santos 2020 + IF NOW() < '2020-10-19' OR NOW() BETWEEN '2020-10-24' AND '2020-10-26' THEN + + LEAVE proc; + + END IF; + START TRANSACTION; -- select now(),'Antes de borrar'; DELETE itf.* @@ -9052,9 +9492,11 @@ BEGIN AND i.EmbalageCode <=> o.EmbalageCode AND i.quality <=> o.Quality LEFT JOIN deliveryInformation di ON di.supplyResponseID = i.supplyResponseFk + JOIN vn.itemType it ON it.id = i.typeFk SET i.supplyResponseFk = o.srID WHERE iExist.id IS NULL AND (di.LatestOrderDateTime < NOW() OR di.ID IS NULL) + AND it.isInventory ; -- Actualizamos el campo supplyResponseFk para aquellos articulos que ya estan creados y reutilizamos /* UPDATE IGNORE edi.offer o @@ -9252,6 +9694,13 @@ BEGIN WHERE b.entryFk = @myEntry AND o.`srId` IS NULL AND po.id IS NULL; + + UPDATE vn.buy b + JOIN vn.item i ON i.id = b.itemFk + LEFT JOIN edi.offer o ON i.supplyResponseFk = o.`srId` + SET b.quantity = 0 + WHERE b.entryFk = @myEntry + AND o.`srId` IS NULL; -- actualiza la oferta existente UPDATE vn.buy b @@ -13164,6 +13613,7 @@ BEGIN WHERE ticketFk = vTicket AND price = vPrice AND itemFk = vItem + AND discount = 0 LIMIT 1; IF vSale THEN UPDATE vn.sale @@ -16360,6 +16810,3055 @@ CREATE TABLE `workers20190711_FichadasAbril` ( -- Dumping routines for database 'postgresql' -- +-- +-- Current Database: `sage` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `sage` /*!40100 DEFAULT CHARACTER SET utf8 */; + +USE `sage`; + +-- +-- Table structure for table `Municipios` +-- + +DROP TABLE IF EXISTS `Municipios`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Municipios` ( + `Codigo` varchar(7) NOT NULL, + `Municipio` varchar(25) NOT NULL, + `Tipo` tinyint(4) NOT NULL, + `Recargo` decimal(28,10) NOT NULL, + `Deleg.` varchar(5) NOT NULL, + `Provincia` tinyint(4) NOT NULL, + `Autonomia` smallint(6) NOT NULL, + `Nacion` tinyint(4) NOT NULL, + PRIMARY KEY (`Codigo`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Naciones` +-- + +DROP TABLE IF EXISTS `Naciones`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Naciones` ( + `countryFk` mediumint(8) NOT NULL, + `CodigoNacion` smallint(6) NOT NULL DEFAULT '108', + `CodigoNacion347` smallint(6) NOT NULL DEFAULT '108', + `Nacion` varchar(25) COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `SiglaNacion` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'ES', + `TipoCodigo` varchar(1) CHARACTER SET utf8 NOT NULL DEFAULT 'A', + `Longitud1` tinyint(4) NOT NULL DEFAULT '0', + `Longitud2` tinyint(4) NOT NULL DEFAULT '0', + `Longitud3` tinyint(4) NOT NULL DEFAULT '0', + `Longitud4` tinyint(4) NOT NULL DEFAULT '0', + `NacionCEE` smallint(6) NOT NULL DEFAULT '0', + `FechaCEE` datetime DEFAULT NULL, + `NacionISO` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '', + PRIMARY KEY (`countryFk`,`CodigoNacion`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `Provincias` +-- + +DROP TABLE IF EXISTS `Provincias`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `Provincias` ( + `provinceFk` smallint(6) NOT NULL, + `CodigoProvincia` varchar(5) NOT NULL DEFAULT '', + `CodigoMatricula` varchar(2) NOT NULL DEFAULT '', + `Provincia` varchar(20) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL DEFAULT '', + `RecargoProvincial` decimal(28,10) NOT NULL DEFAULT '0.0000000000', + PRIMARY KEY (`CodigoProvincia`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `TiposIva` +-- + +DROP TABLE IF EXISTS `TiposIva`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `TiposIva` ( + `CodigoIva` smallint(6) NOT NULL DEFAULT '0', + `CodigoTerritorio` smallint(6) NOT NULL DEFAULT '0', + `Iva` varchar(30) NOT NULL DEFAULT '', + `BaseCorrectora` decimal(28,10) NOT NULL DEFAULT '0.0000000000', + `PorcentajeIva` decimal(28,10) NOT NULL DEFAULT '0.0000000000', + `RecargoEquivalencia` decimal(28,10) NOT NULL DEFAULT '0.0000000000', + `CuentaIvaSoportado` varchar(15) NOT NULL DEFAULT '', + `CuentaIvaRepercutido` varchar(15) NOT NULL DEFAULT '', + `CuentaRecargo` varchar(15) NOT NULL DEFAULT '', + `CuentaIvaNoDeducible` varchar(15) NOT NULL DEFAULT '', + `CuentaIvaSoportadoANT_` varchar(15) NOT NULL DEFAULT '', + `CuentaIvaRepercutidoANT_` varchar(15) NOT NULL DEFAULT '', + `CuentaRecargoANT_` varchar(15) NOT NULL DEFAULT '', + `CuentaIvaNoDeducibleANT_` varchar(15) NOT NULL DEFAULT '', + `IdTiposIva` varchar(50) NOT NULL DEFAULT '', + `CuentaIvaRepCaja` varchar(15) NOT NULL DEFAULT '', + `CuentaIVARepCajaPu` varchar(15) NOT NULL DEFAULT '', + `CuentaIVARepCajaVen` varchar(15) NOT NULL DEFAULT '', + `CuentaIvaSopCaja` varchar(15) NOT NULL DEFAULT '', + `CuentaIVASopCajaPu` varchar(15) NOT NULL DEFAULT '', + `CuentaIVASopCajaVen` varchar(15) NOT NULL DEFAULT '', + `CuentaIVARecCaja` varchar(15) NOT NULL DEFAULT '', + `CuentaIVARecCajaPu` varchar(15) NOT NULL DEFAULT '', + `CuentaIVARecCajaVen` varchar(15) NOT NULL DEFAULT '', + `IGICImplicito` smallint(6) NOT NULL DEFAULT '0', + `isIntracommunity` tinyint(2) NOT NULL DEFAULT '0', + PRIMARY KEY (`CodigoIva`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `TiposRetencion` +-- + +DROP TABLE IF EXISTS `TiposRetencion`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `TiposRetencion` ( + `CodigoRetencion` smallint(6) NOT NULL DEFAULT '0', + `Retencion` varchar(50) NOT NULL DEFAULT '', + `PorcentajeRetencion` decimal(28,10) NOT NULL DEFAULT '0.0000000000', + `CuentaCargo` varchar(15) DEFAULT NULL, + `CuentaAbono` varchar(15) DEFAULT NULL, + `ClaveIrpf` varchar(2) DEFAULT NULL, + `CuentaCargoANT_` varchar(15) DEFAULT NULL, + `CuentaAbonoANT_` varchar(15) DEFAULT NULL, + `IdTipoRetencion` varchar(45) DEFAULT NULL, + PRIMARY KEY (`CodigoRetencion`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `TiposTransacciones` +-- + +DROP TABLE IF EXISTS `TiposTransacciones`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `TiposTransacciones` ( + `CodigoTransaccion` tinyint(4) NOT NULL DEFAULT '0', + `Transaccion` varchar(50) NOT NULL DEFAULT '', + `TipoFactura` varchar(1) NOT NULL DEFAULT '', + `Autofactura` smallint(6) NOT NULL DEFAULT '0', + `ClaveOperacionDefecto` varchar(1) NOT NULL DEFAULT '', + PRIMARY KEY (`CodigoTransaccion`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `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` ( + `id` int(11) NOT NULL, + `CodigoDivisa` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `BaseIva1` double DEFAULT NULL, + `PorBaseCorrectora1` double DEFAULT NULL, + `PorIva1` double DEFAULT NULL, + `CuotaIva1` double DEFAULT NULL, + `PorRecargoEquivalencia1` double DEFAULT NULL, + `RecargoEquivalencia1` double DEFAULT NULL, + `CodigoTransaccion1` double NOT NULL DEFAULT '0', + `CodigoIva1` smallint(6) NOT NULL, + `BaseIva2` double DEFAULT NULL, + `PorBaseCorrectora2` double DEFAULT NULL, + `PorIva2` double DEFAULT NULL, + `CuotaIva2` double DEFAULT NULL, + `PorRecargoEquivalencia2` double DEFAULT NULL, + `RecargoEquivalencia2` double DEFAULT NULL, + `CodigoTransaccion2` double NOT NULL DEFAULT '0', + `CodigoIva2` smallint(6) NOT NULL, + `BaseIva3` double DEFAULT NULL, + `PorBaseCorrectora3` double DEFAULT NULL, + `PorIva3` double DEFAULT NULL, + `CuotaIva3` double DEFAULT NULL, + `PorRecargoEquivalencia3` double DEFAULT NULL, + `RecargoEquivalencia3` double DEFAULT NULL, + `CodigoTransaccion3` double NOT NULL DEFAULT '0', + `CodigoIva3` smallint(6) NOT NULL, + `BaseIva4` double DEFAULT NULL, + `PorBaseCorrectora4` double DEFAULT NULL, + `PorIva4` double DEFAULT NULL, + `CuotaIva4` double DEFAULT NULL, + `PorRecargoEquivalencia4` double DEFAULT NULL, + `RecargoEquivalencia4` double DEFAULT NULL, + `CodigoTransaccion4` double NOT NULL DEFAULT '0', + `CodigoIva4` smallint(6) NOT NULL, + `Año` int(11) DEFAULT NULL, + `Serie` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + `Factura` int(11) DEFAULT NULL, + `SuFacturaNo` varchar(40) COLLATE utf8_unicode_ci DEFAULT NULL, + `FechaFactura` date DEFAULT NULL, + `ImporteFactura` double DEFAULT NULL, + `TipoFactura` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `CodigoCuentaFactura` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `CifDni` varchar(13) COLLATE utf8_unicode_ci DEFAULT NULL, + `Nombre` varchar(35) COLLATE utf8_unicode_ci DEFAULT NULL, + `CodigoRetencion` int(2) DEFAULT NULL, + `BaseRetencion` double DEFAULT NULL, + `PorRetencion` double DEFAULT NULL, + `ImporteRetencion` double DEFAULT NULL, + `SiglaNacion` varchar(2) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'ES', + `EjercicioFactura` int(2) DEFAULT NULL, + `FechaOperacion` date DEFAULT NULL, + `Exclusion347` int(2) DEFAULT NULL, + `MantenerAsiento` int(2) DEFAULT '-1', + `Metalico347` int(2) DEFAULT NULL, + `ClaveOperacionFactura` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL, + `TipoRectificativa` int(2) DEFAULT NULL, + `FechaFacturaOriginal` date DEFAULT NULL, + `CuotaIvaOriginal` double DEFAULT NULL, + `BaseImponibleOriginal` double DEFAULT NULL, + `ClaseAbonoRectificativas` int(2) DEFAULT NULL, + `RecargoEquivalenciaOriginal` double DEFAULT NULL, + `LibreA1` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL, + `IvaDeducible1` int(2) NOT NULL DEFAULT '-1', + `IvaDeducible2` int(2) NOT NULL DEFAULT '-1', + `IvaDeducible3` int(2) NOT NULL DEFAULT '-1', + `IvaDeducible4` int(2) NOT NULL DEFAULT '-1', + `FechaGrabacion` date DEFAULT NULL, + `Intracomunitaria` tinyint(1) DEFAULT '0', + `moveData` tinyint(1) DEFAULT '1', + PRIMARY KEY (`id`), + CONSTRAINT `XDiario_movConta_IVA_fk1` FOREIGN KEY (`id`) REFERENCES `vn`.`XDiario` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Informa del valor de los campos de IVA para enlazar en la tabla vn.movConta'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientesProveedores` +-- + +DROP TABLE IF EXISTS `clientesProveedores`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientesProveedores` ( + `CodigoEmpresa` smallint(6) NOT NULL, + `ClienteOProveedor` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `CodigoClienteProveedor` int(11) NOT NULL, + `RazonSocial` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `RazonSocial2` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Nombre` varchar(35) COLLATE utf8_unicode_ci NOT NULL, + `Domicilio` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Cargo1` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `Nombre1` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `Cargo2` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `Nombre2` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuenta` varchar(15) CHARACTER SET utf8 NOT NULL, + `CifDni` varchar(13) COLLATE utf8_unicode_ci NOT NULL, + `CifEuropeo` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoSigla` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `ViaPublica` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Numero1` varchar(4) COLLATE utf8_unicode_ci NOT NULL, + `Numero2` varchar(4) COLLATE utf8_unicode_ci NOT NULL, + `Escalera` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `Piso` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `Puerta` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `Letra` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `CodigoPostal` varchar(8) COLLATE utf8_unicode_ci NOT NULL, + `CodigoMunicipio` varchar(7) COLLATE utf8_unicode_ci NOT NULL, + `Municipio` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + `ColaMunicipio` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoProvincia` varchar(5) COLLATE utf8_unicode_ci NOT NULL, + `Provincia` varchar(20) COLLATE utf8_unicode_ci NOT NULL, + `CodigoNacion` smallint(6) NOT NULL, + `Nacion` varchar(25) COLLATE utf8_unicode_ci NOT NULL, + `Telefono` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `Telefono2` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `Telefono3` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `Fax` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoTransaccion` tinyint(4) NOT NULL, + `CodigoRetencion` smallint(6) NOT NULL, + `Deducible` smallint(6) NOT NULL, + `CodigoIva` smallint(6) NOT NULL, + `Mediacion` smallint(6) NOT NULL DEFAULT '0', + `Exclusion347` smallint(6) NOT NULL DEFAULT '0', + `NumeroPlazos` tinyint(4) NOT NULL DEFAULT '1', + `DiasPrimerPlazo` smallint(6) NOT NULL, + `DiasEntrePlazos` smallint(6) NOT NULL, + `DiasFijos1` tinyint(4) NOT NULL, + `DiasFijos2` tinyint(4) NOT NULL, + `DiasFijos3` tinyint(4) NOT NULL, + `InicioNoPago` smallint(6) NOT NULL, + `FinNoPago` smallint(6) NOT NULL, + `ControlarFestivos` smallint(6) NOT NULL, + `DiasRetroceso` tinyint(4) NOT NULL, + `MesesComerciales` smallint(6) NOT NULL, + `RemesaHabitual` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoTipoEfecto` smallint(6) NOT NULL, + `Email1` varchar(250) COLLATE utf8_unicode_ci NOT NULL, + `Email2` varchar(250) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCategoriaCliente_` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'CLI', + `IdDelegacion` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoMotivoBajaClienteLc` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `CodigoDepartamento` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCanal` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoBanco` varchar(6) COLLATE utf8_unicode_ci NOT NULL, + `CodigoAgencia` varchar(6) COLLATE utf8_unicode_ci NOT NULL, + `DC` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `CCC` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `IBAN` varchar(34) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCondiciones` smallint(6) NOT NULL, + `StatusTraspasadoIME` tinyint(4) NOT NULL, + `TipoImportacionIME` tinyint(4) NOT NULL, + `TipoPlanCuentaIME` smallint(6) NOT NULL DEFAULT '2', + `Contrapartida` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuentaImpagado` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuentaEfecto` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `Comentarios` text COLLATE utf8_unicode_ci NOT NULL, + `CodigoTerritorio` smallint(6) NOT NULL, + `CodigoIdioma_` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `TarifaPrecio` smallint(6) NOT NULL, + `%Descuento` decimal(28,10) NOT NULL, + `%Rappel` decimal(28,10) NOT NULL, + `%ProntoPago` decimal(28,10) NOT NULL, + `%Financiacion` decimal(28,10) NOT NULL, + `CodigoComisionista` int(11) NOT NULL, + `TarifaDescuento` smallint(6) NOT NULL, + `SiglaNacion` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `MarcaMenorSinNif` smallint(6) NOT NULL, + `PersonaFisicaJuridica` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `SiglaNacionRepresentante` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `CifDniRepresentante` varchar(13) COLLATE utf8_unicode_ci NOT NULL, + `NombreRepresentante` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `TipoDocumentoPersona` smallint(6) NOT NULL, + `TipoCif` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `MotivoBajaClienteLc` varchar(30) COLLATE utf8_unicode_ci NOT NULL, + `PuntosSR` decimal(28,10) NOT NULL, + `TarjetaSR` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `FechaNacimiento` datetime DEFAULT NULL, + `Domicilio2` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `CuentaProvision` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CodigoTransportista` int(11) NOT NULL, + `FormadePago` varchar(35) COLLATE utf8_unicode_ci NOT NULL, + `ObservacionesCliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `CodigoTipoClienteLc` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `TipoCliente` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoActividadLc` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `Actividad` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `IndicadorIva` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `CodigoRuta_` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `NombreEmpleado` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `PrimerApellidoEmpleado` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `SegundoApellidoEmpleado` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `sysTick` int(11) NOT NULL, + `RiesgoMaximo` decimal(28,10) NOT NULL, + `PlazoMedioPCMA` smallint(6) NOT NULL, + `CriterioIvaIME` smallint(6) NOT NULL DEFAULT '0', + `ReferenciaMandato` varchar(35) COLLATE utf8_unicode_ci NOT NULL, + `%Comision` decimal(28,10) NOT NULL, + `CodigoZona` int(11) NOT NULL, + `BloqueoAlbaran` smallint(6) NOT NULL, + `CodigoSeccion` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoSector_` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoProyecto` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`CodigoEmpresa`,`ClienteOProveedor`,`CodigoClienteProveedor`), + KEY `CodigoCuenta` (`CodigoCuenta`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `invoiceInList` +-- + +DROP TABLE IF EXISTS `invoiceInList`; +/*!50001 DROP VIEW IF EXISTS `invoiceInList`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `invoiceInList` AS SELECT + 1 AS `id`, + 1 AS `supplierRef`, + 1 AS `serial`, + 1 AS `supplierFk`, + 1 AS `issued`, + 1 AS `isVatDeductible`, + 1 AS `serialNumber`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `movConta` +-- + +DROP TABLE IF EXISTS `movConta`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `movConta` ( + `OrdenMovimientos` int(11) NOT NULL AUTO_INCREMENT, + `MovPosicion` varchar(64) COLLATE utf8_unicode_ci NOT NULL, + `Ejercicio` smallint(6) NOT NULL, + `CodigoEmpresa` smallint(6) NOT NULL, + `Asiento` int(11) NOT NULL, + `CargoAbono` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuenta` varchar(15) CHARACTER SET utf8 NOT NULL, + `Contrapartida` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `FechaAsiento` datetime NOT NULL, + `TipoDocumento` varchar(6) COLLATE utf8_unicode_ci NOT NULL, + `DocumentoConta` varchar(9) COLLATE utf8_unicode_ci NOT NULL, + `Comentario` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `ImporteAsiento` decimal(28,10) NOT NULL, + `CodigoDiario` smallint(6) NOT NULL, + `CodigoCanal` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoActividad` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `FechaVencimiento` datetime DEFAULT NULL, + `NumeroPeriodo` smallint(6) NOT NULL, + `CodigoUsuario` smallint(6) NOT NULL, + `FechaGrabacion` datetime NOT NULL, + `TipoEntrada` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `CodigoDepartamento` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoSeccion` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `CodigoDivisa` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `ImporteCambio` decimal(28,10) NOT NULL, + `ImporteDivisa` decimal(28,10) NOT NULL, + `FactorCambio` decimal(28,10) NOT NULL, + `CodigoProyecto` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `LibreN1` int(11) NOT NULL, + `LibreN2` int(11) NOT NULL, + `LibreA1` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `LibreA2` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `IdDelegacion` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `MovCartera` varchar(64) COLLATE utf8_unicode_ci DEFAULT NULL, + `IdProcesoIME` varchar(64) COLLATE utf8_unicode_ci NOT NULL, + `TipoCarteraIME` smallint(6) NOT NULL, + `TipoAnaliticaIME` smallint(6) NOT NULL, + `StatusTraspasadoIME` tinyint(4) NOT NULL, + `TipoImportacionIME` tinyint(4) NOT NULL, + `BaseIva1` decimal(28,10) NOT NULL, + `PorBaseCorrectora1` decimal(28,10) NOT NULL, + `PorIva1` decimal(28,10) NOT NULL, + `CuotaIva1` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia1` decimal(28,10) NOT NULL, + `RecargoEquivalencia1` decimal(28,10) NOT NULL, + `CodigoTransaccion1` tinyint(4) NOT NULL, + `BaseIva2` decimal(28,10) NOT NULL, + `PorBaseCorrectora2` decimal(28,10) NOT NULL, + `PorIva2` decimal(28,10) NOT NULL, + `CuotaIva2` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia2` decimal(28,10) NOT NULL, + `RecargoEquivalencia2` decimal(28,10) NOT NULL, + `CodigoTransaccion2` tinyint(4) NOT NULL, + `BaseIva3` decimal(28,10) NOT NULL, + `PorBaseCorrectora3` decimal(28,10) NOT NULL, + `PorIva3` decimal(28,10) NOT NULL, + `CuotaIva3` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia3` decimal(28,10) NOT NULL, + `RecargoEquivalencia3` decimal(28,10) NOT NULL, + `CodigoTransaccion3` tinyint(4) NOT NULL, + `baseIva4` decimal(28,10) NOT NULL, + `PorBaseCorrectora4` decimal(28,10) NOT NULL, + `PorIva4` decimal(28,10) NOT NULL, + `CuotaIva4` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia4` decimal(28,10) NOT NULL, + `RecargoEquivalencia4` decimal(28,10) NOT NULL, + `CodigoTransaccion4` tinyint(4) NOT NULL, + `Año` smallint(6) NOT NULL, + `Serie` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `Factura` int(11) NOT NULL, + `SuFacturaNo` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `FechaFactura` datetime NOT NULL, + `ImporteFactura` decimal(28,10) NOT NULL, + `TipoFactura` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuentaFactura` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CifDni` varchar(13) COLLATE utf8_unicode_ci NOT NULL, + `Nombre` varchar(35) COLLATE utf8_unicode_ci NOT NULL, + `CodigoRetencion` smallint(6) NOT NULL, + `BaseRetencion` decimal(28,10) NOT NULL, + `PorRetencion` decimal(28,10) NOT NULL, + `ImporteRetencion` decimal(28,10) NOT NULL, + `AbonoIva` smallint(6) NOT NULL, + `CodigoActividadF` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `Intracomunitaria` smallint(6) NOT NULL, + `CodigoTerritorio` smallint(6) NOT NULL, + `SiglaNacion` varchar(2) COLLATE utf8_unicode_ci NOT NULL, + `RetencionInformativa` smallint(6) NOT NULL, + `EjercicioFacturaOriginal` smallint(6) NOT NULL, + `SerieFacturaOriginal` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `NumeroFacturaOriginal` int(11) NOT NULL, + `EjercicioFactura` smallint(6) NOT NULL, + `CobroPagoRetencion` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `FechaOperacion` datetime NOT NULL, + `Exclusion347` smallint(6) NOT NULL, + `MovIdentificadorIME` varchar(64) COLLATE utf8_unicode_ci NOT NULL, + `Previsiones` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `MantenerAsiento` tinyint(4) NOT NULL, + `OrdenMovIME` smallint(6) NOT NULL, + `Metalico347` smallint(6) NOT NULL, + `ClaveOperacionFactura_` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `SerieAgrupacion_` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `NumeroFacturaInicial_` int(11) NOT NULL, + `NumeroFacturaFinal_` int(11) NOT NULL, + `IdAsientoExterno` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `IdDiarioExterno` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExterno` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `IdMovimiento` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `IdCuadre` smallint(6) NOT NULL, + `FechaCuadre` datetime NOT NULL, + `TipoCuadre` varchar(4) COLLATE utf8_unicode_ci NOT NULL, + `AgrupacionCuadre` int(11) NOT NULL, + `StatusSaldo` smallint(6) NOT NULL, + `StatusConciliacion` smallint(6) NOT NULL, + `CodigoConciliacion` int(11) NOT NULL, + `FechaConciliacion` datetime NOT NULL, + `TipoConciliacion` smallint(6) NOT NULL, + `IndicadorContaBanco` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion3` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion4` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion5` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion6` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion7` varchar(40) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion8` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion9` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion2` varchar(250) COLLATE utf8_unicode_ci NOT NULL, + `Descripcion1` varchar(250) COLLATE utf8_unicode_ci NOT NULL, + `Punteo1` smallint(6) NOT NULL, + `Punteo9` smallint(6) NOT NULL, + `Punteo8` smallint(6) NOT NULL, + `Punteo7` smallint(6) NOT NULL, + `Punteo6` smallint(6) NOT NULL, + `Punteo5` smallint(6) NOT NULL, + `Punteo4` smallint(6) NOT NULL, + `Punteo3` smallint(6) NOT NULL, + `Punteo2` smallint(6) NOT NULL, + `CodigoIva1` smallint(6) NOT NULL, + `CodigoIva2` smallint(6) NOT NULL, + `CodigoIva3` smallint(6) NOT NULL, + `CodigoIva4` smallint(6) NOT NULL, + `CriterioIva` tinyint(4) NOT NULL, + `FechaMaxVencimiento` datetime NOT NULL, + `TipoCriterioCaja` tinyint(4) NOT NULL, + `MovFacturaOrigenIME` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExternoFinal` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExternoInicial` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExternoOriginal` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `NumFacturasExternoAgrupacion` int(11) NOT NULL, + `CodigoMedioCobro` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `MedioCobro` varchar(31) COLLATE utf8_unicode_ci NOT NULL, + `IvaDeducible1` smallint(6) NOT NULL DEFAULT '1', + `IvaDeducible2` smallint(6) NOT NULL DEFAULT '1', + `IvaDeducible3` smallint(6) NOT NULL DEFAULT '1', + `IvaDeducible4` smallint(6) NOT NULL DEFAULT '1', + `TipoRectificativa` smallint(6) NOT NULL, + `FechaFacturaOriginal` datetime NOT NULL, + `BaseImponibleOriginal` decimal(28,10) NOT NULL, + `CuotaIvaOriginal` decimal(28,10) NOT NULL, + `ClaseAbonoRectificativas` smallint(6) NOT NULL, + `RecargoEquivalenciaOriginal` decimal(28,10) NOT NULL, + `ObjetoFactura` varchar(500) COLLATE utf8_unicode_ci NOT NULL, + `enlazadoSage` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`OrdenMovimientos`,`LibreN1`), + KEY `ix_movconta` (`enlazadoSage`), + KEY `ix_movconta2` (`IdProcesoIME`), + KEY `CodigoCuenta` (`CodigoCuenta`), + KEY `movConta_Asiento` (`Asiento`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = 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 ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sage`.`movConta_BEFORE_UPDATE` BEFORE UPDATE ON `movConta` FOR EACH ROW +BEGIN + IF NEW.enlazadoSage = TRUE THEN + UPDATE vn.XDiario SET enlazadoSage = TRUE WHERE ASIEN = NEW.Asiento; + END IF; +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `movContaCopia` +-- + +DROP TABLE IF EXISTS `movContaCopia`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `movContaCopia` ( + `OrdenMovimientos` int(11) NOT NULL DEFAULT '0', + `MovPosicion` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Ejercicio` smallint(6) NOT NULL, + `CodigoEmpresa` smallint(6) NOT NULL, + `Asiento` int(11) NOT NULL, + `CargoAbono` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuenta` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Contrapartida` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `FechaAsiento` datetime NOT NULL, + `TipoDocumento` varchar(6) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `DocumentoConta` varchar(9) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Comentario` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `ImporteAsiento` decimal(28,10) NOT NULL, + `CodigoDiario` smallint(6) NOT NULL, + `CodigoCanal` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoActividad` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `FechaVencimiento` datetime NOT NULL, + `NumeroPeriodo` smallint(6) NOT NULL, + `CodigoUsuario` smallint(6) NOT NULL, + `FechaGrabacion` datetime NOT NULL, + `TipoEntrada` varchar(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoDepartamento` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoSeccion` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoDivisa` varchar(3) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `ImporteCambio` decimal(28,10) NOT NULL, + `ImporteDivisa` decimal(28,10) NOT NULL, + `FactorCambio` decimal(28,10) NOT NULL, + `CodigoProyecto` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `LibreN1` int(11) NOT NULL, + `LibreN2` int(11) NOT NULL, + `LibreA1` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `LibreA2` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdDelegacion` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `MovCartera` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL, + `IdProcesoIME` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `TipoCarteraIME` smallint(6) NOT NULL, + `TipoAnaliticaIME` smallint(6) NOT NULL, + `StatusTraspasadoIME` tinyint(4) NOT NULL, + `TipoImportacionIME` tinyint(4) NOT NULL, + `BaseIva1` decimal(28,10) NOT NULL, + `PorBaseCorrectora1` decimal(28,10) NOT NULL, + `PorIva1` decimal(28,10) NOT NULL, + `CuotaIva1` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia1` decimal(28,10) NOT NULL, + `RecargoEquivalencia1` decimal(28,10) NOT NULL, + `CodigoTransaccion1` tinyint(4) NOT NULL, + `BaseIva2` decimal(28,10) NOT NULL, + `PorBaseCorrectora2` decimal(28,10) NOT NULL, + `PorIva2` decimal(28,10) NOT NULL, + `CuotaIva2` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia2` decimal(28,10) NOT NULL, + `RecargoEquivalencia2` decimal(28,10) NOT NULL, + `CodigoTransaccion2` tinyint(4) NOT NULL, + `BaseIva3` decimal(28,10) NOT NULL, + `PorBaseCorrectora3` decimal(28,10) NOT NULL, + `PorIva3` decimal(28,10) NOT NULL, + `CuotaIva3` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia3` decimal(28,10) NOT NULL, + `RecargoEquivalencia3` decimal(28,10) NOT NULL, + `CodigoTransaccion3` tinyint(4) NOT NULL, + `baseIva4` decimal(28,10) NOT NULL, + `PorBaseCorrectora4` decimal(28,10) NOT NULL, + `PorIva4` decimal(28,10) NOT NULL, + `CuotaIva4` decimal(28,10) NOT NULL, + `PorRecargoEquivalencia4` decimal(28,10) NOT NULL, + `RecargoEquivalencia4` decimal(28,10) NOT NULL, + `CodigoTransaccion4` tinyint(4) NOT NULL, + `Año` smallint(6) NOT NULL, + `Serie` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Factura` int(11) NOT NULL, + `SuFacturaNo` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `FechaFactura` datetime NOT NULL, + `ImporteFactura` decimal(28,10) NOT NULL, + `TipoFactura` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoCuentaFactura` varchar(15) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CifDni` varchar(13) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Nombre` varchar(35) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `CodigoRetencion` smallint(6) NOT NULL, + `BaseRetencion` decimal(28,10) NOT NULL, + `PorRetencion` decimal(28,10) NOT NULL, + `ImporteRetencion` decimal(28,10) NOT NULL, + `AbonoIva` smallint(6) NOT NULL, + `CodigoActividadF` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Intracomunitaria` smallint(6) NOT NULL, + `CodigoTerritorio` smallint(6) NOT NULL, + `SiglaNacion` varchar(2) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `RetencionInformativa` smallint(6) NOT NULL, + `EjercicioFacturaOriginal` smallint(6) NOT NULL, + `SerieFacturaOriginal` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `NumeroFacturaOriginal` int(11) NOT NULL, + `EjercicioFactura` smallint(6) NOT NULL, + `CobroPagoRetencion` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `FechaOperacion` datetime NOT NULL, + `Exclusion347` smallint(6) NOT NULL, + `MovIdentificadorIME` varchar(64) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Previsiones` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `MantenerAsiento` tinyint(4) NOT NULL, + `OrdenMovIME` smallint(6) NOT NULL, + `Metalico347` smallint(6) NOT NULL, + `ClaveOperacionFactura_` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `SerieAgrupacion_` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `NumeroFacturaInicial_` int(11) NOT NULL, + `NumeroFacturaFinal_` int(11) NOT NULL, + `IdAsientoExterno` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdDiarioExterno` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExterno` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdMovimiento` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdCuadre` smallint(6) NOT NULL, + `FechaCuadre` datetime NOT NULL, + `TipoCuadre` varchar(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `AgrupacionCuadre` int(11) NOT NULL, + `StatusSaldo` smallint(6) NOT NULL, + `StatusConciliacion` smallint(6) NOT NULL, + `CodigoConciliacion` int(11) NOT NULL, + `FechaConciliacion` datetime NOT NULL, + `TipoConciliacion` smallint(6) NOT NULL, + `IndicadorContaBanco` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion3` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion4` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion5` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion6` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion7` varchar(40) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion8` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion9` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion2` varchar(250) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Descripcion1` varchar(250) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `Punteo1` smallint(6) NOT NULL, + `Punteo9` smallint(6) NOT NULL, + `Punteo8` smallint(6) NOT NULL, + `Punteo7` smallint(6) NOT NULL, + `Punteo6` smallint(6) NOT NULL, + `Punteo5` smallint(6) NOT NULL, + `Punteo4` smallint(6) NOT NULL, + `Punteo3` smallint(6) NOT NULL, + `Punteo2` smallint(6) NOT NULL, + `CodigoIva1` smallint(6) NOT NULL, + `CodigoIva2` smallint(6) NOT NULL, + `CodigoIva3` smallint(6) NOT NULL, + `CodigoIva4` smallint(6) NOT NULL, + `CriterioIva` tinyint(4) NOT NULL, + `FechaMaxVencimiento` datetime NOT NULL, + `TipoCriterioCaja` tinyint(4) NOT NULL, + `MovFacturaOrigenIME` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExternoFinal` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExternoInicial` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IdFacturaExternoOriginal` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `NumFacturasExternoAgrupacion` int(11) NOT NULL, + `CodigoMedioCobro` varchar(1) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `MedioCobro` varchar(31) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `IvaDeducible1` smallint(6) NOT NULL DEFAULT '1', + `IvaDeducible2` smallint(6) NOT NULL DEFAULT '1', + `IvaDeducible3` smallint(6) NOT NULL DEFAULT '1', + `IvaDeducible4` smallint(6) NOT NULL DEFAULT '1', + `TipoRectificativa` smallint(6) NOT NULL, + `FechaFacturaOriginal` datetime NOT NULL, + `BaseImponibleOriginal` decimal(28,10) NOT NULL, + `CuotaIvaOriginal` decimal(28,10) NOT NULL, + `ClaseAbonoRectificativas` smallint(6) NOT NULL, + `RecargoEquivalenciaOriginal` decimal(28,10) NOT NULL, + `ObjetoFactura` varchar(500) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `enlazado` tinyint(1) NOT NULL DEFAULT '0', + PRIMARY KEY (`OrdenMovimientos`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `pgcToSage` +-- + +DROP TABLE IF EXISTS `pgcToSage`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `pgcToSage` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `taxCodeSage` int(11) NOT NULL, + `transactionCode` int(11) NOT NULL, + `accountTaxInput` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + `accountTaxOutput` varchar(10) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COMMENT='Tabla relaciona cuentas pgc con Código de IVA y Código de Transacción en Sage'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `planCuentasPGC` +-- + +DROP TABLE IF EXISTS `planCuentasPGC`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `planCuentasPGC` ( + `CodigoEmpresa` smallint(6) NOT NULL, + `CodigoCuenta` varchar(15) CHARACTER SET utf8 NOT NULL, + `Cuenta` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `ClienteOProveedor` varchar(1) COLLATE utf8_unicode_ci NOT NULL, + `CodigoDivisa` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `IndicadorProrrata` smallint(6) NOT NULL, + `TipoPlanCuentaIME` smallint(6) NOT NULL DEFAULT '2', + `StatusAnalitica` smallint(6) NOT NULL, + `AnaCodigoCuenta` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `StatusTraspasadoIME` tinyint(4) NOT NULL DEFAULT '0', + `TipoImportacionIME` tinyint(4) NOT NULL DEFAULT '0', + `CierrePatrimonio_` smallint(6) NOT NULL DEFAULT '0', + `CuentaPatrimonio_` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `CuentaVarios` smallint(6) NOT NULL DEFAULT '0', + `TodasLasActividades` smallint(6) NOT NULL DEFAULT '0', + `ValorDelegacion` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `ValorDepartamento` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `ValorProyecto` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `ValorCanal` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + `ValorSeccion` varchar(10) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`CodigoEmpresa`,`CodigoCuenta`), + KEY `CodigoCuenta` (`CodigoCuenta`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'sage' +-- + +-- +-- Dumping routines for database 'sage' +-- +/*!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 */ ; +/*!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 `clientesProveedoresAdd`() +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, + CodigoRetencion, + Email1, + iban) + SELECT IF (@@hostname = 'db', c.companyCode, companyCodeTest) CodigoEmpresa, + 'C' ClienteOProveedor, + cl.id CodigoClienteProveedor, + cl.socialName RazonSocial, + cl.name Nombre, + cl.street Domicilio, + cl.accountingAccount CodigoCuenta, + TRIM(IF(co.code = LEFT(cl.fi,2), MID(cl.fi,3, length(cl.fi)-1), cl.fi)) AS CifDni, + TRIM(CONCAT(co.code, IF(co.code = LEFT(cl.fi,2), MID(cl.fi,3, length(cl.fi)-1), cl.fi))) AS CifEuropeo, + cl.postcode CodigoPostal, + cl.city Municipio, + sp.CodigoProvincia CodigoProvincia, + p.name Provincia, + IF (sn.SiglaNacion = "XB",IF(sp.CodigoProvincia IN (51,52), 22, IF (sp.CodigoProvincia IN (35,38), 21, sn.CodigoNacion)), sn.CodigoNacion) CodigoNacion, + IF (sn.SiglaNacion = "XB",IF(sp.CodigoProvincia IN (51,52), "XC",IF (sp.CodigoProvincia IN (35,38), "XB", sn.SiglaNacion)), sn.SiglaNacion) SiglaNacion, + IF((cl.fi REGEXP '^([[:blank:]]|[[:digit:]])'), 'J','F') PersonaFisicaJuridica, + IF((co.id = 1), 1, IF((co.isUeeMember = 1), 2, 4)) TipoDocumentoPersona, + IF(cl.isEqualizated, 'R', IF ((cl.isVies AND cl.countryFk <> 1) OR (NOT co.isUeeMember),'E','I'))AS CodigoIva, + IF(sn.SiglaNacion = "XB", IF(sp.CodigoProvincia IN (51,52), "CEUTA Y MELILLA", IF (sp.CodigoProvincia IN (35,38), "ISLAS CANARIAS",sn.Nacion)) , sn.Nacion) Nacion, + cl.phone Telefono, + cl.mobile Telefono2, + 0 CodigoRetencion, + SUBSTR(cl.email, 1, LOCATE(',', CONCAT(cl.email,','))-1) Email1, + cl.iban iban + FROM vn.client cl + JOIN vn2008.v_xsubclien ON v_xsubclien.Id_Cliente = cl.id + LEFT JOIN vn.country co ON co.id = cl.countryFk + LEFT JOIN sage.Naciones sn ON sn.countryFk = co.id + LEFT JOIN vn.province p ON p.id = cl.provinceFk + LEFT JOIN sage.Provincias sp ON sp.provinceFk = p.id + JOIN vn.company c ON c.id = v_xsubclien.empresa_id + WHERE cl.isRelevant AND c.code = 'VNL' + UNION ALL + SELECT IF (@@hostname = 'db', c.companyCode, companyCodeTest) CodigoEmpresa, + 'P' ClienteOProveedor, + s.id CodigoClienteProveedor, + s.name RazonSocial, + s.name Nombre, + s.street Domicilio, + s.account CodigoCuenta, + TRIM(IF(co.code = LEFT(s.nif,2), MID(s.nif,3, length(s.nif)-1), s.nif)) CifDni, + TRIM(CONCAT(co.code, IF(co.code = LEFT(s.nif,2), MID(s.nif,3, length(s.nif)-1), s.nif))) AS CifEuropeo, + s.postCode CodigoPostal, + s.city Municipio, + sp.CodigoProvincia CodigoProvincia, + p.name Provincia, + sn.CodigoNacion CodigoNacion, + sn.SiglaNacion SiglaNacion, + IF((s.nif REGEXP '^([[:blank:]]|[[:digit:]])'),'J','F') PersonaFisicaJuridica, + IF((co.id = 1),1,IF((co.isUeeMember = 1), 2, 4)) TipoDocumentoPersona, + 'I' CodigoIva, + sn.Nacion Nacion, + con.Telefono Telefono, + con.Movil Telefono2, + CASE + WHEN s.account LIKE '_____4____' THEN 2 + WHEN s.account LIKE '_____3____' THEN 18 + ELSE 0 + END CodigoRetencion, + SUBSTR(con.email,1,(COALESCE(NULLIF(LOCATE(',', con.email), 0), 99) - 1)) Email1, + sa.iban iban + FROM vn.supplier s + JOIN vn2008.v_xsubprov xsp ON xsp.proveedor_id = s.id -- Proveedores activos los últimos 3 meses + LEFT JOIN vn.country co ON co.id = s.countryFk + LEFT JOIN sage.Naciones sn ON sn.countryFk = co.id + LEFT JOIN vn.province p ON p.id = s.provinceFk + LEFT JOIN sage.Provincias sp ON sp.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 = xsp.empresa_id + WHERE + c.code = 'VNL' AND + s.isActive AND + s.nif <> '' +GROUP BY xsp.proveedor_id , xsp.empresa_id; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `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 + */ + + 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) + IFNULL(xmi.CodigoDivisa, cu.code) CodigoDivisa, -- VARCHAR(3) + x.CAMBIO AS ImporteCambio, -- DOBLE(19) + IFNULL(x.DEBEME,x.HABERME) 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 AND xmi.moveData = TRUE + 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 + LEFT JOIN vn.bank b ON b.account = x.SUBCTA + LEFT JOIN vn.currency cu ON cu.id = b.currencyFk + 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 = IF(m.CargoAbono = "H", m.CodigoCuenta-4300000000, m.Contrapartida-4300000000 ) + LEFT JOIN Naciones n ON n.countryFk = c.countryFk + WHERE m.Metalico347 = TRUE AND + m.enlazadoSage = FALSE + ) 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; + + UPDATE sage.movConta m + SET Metalico347 = FALSE, + Contrapartida ="", + m.TipoFactura = "", + m.Metalico347 = FALSE + WHERE CargoAbono = "D"; + +-- 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 ; + + +-- DUAS + + UPDATE movConta m + JOIN vn.XDiario x ON x.ASIEN = m.Asiento AND x.SUBCTA =m.CodigoCuenta + JOIN (SELECT ASIEN + FROM vn.invoiceIn ii + JOIN vn.XDiario x ON x.CLAVE = ii.id + WHERE enlazadoSage = 0 AND + SUBCTA = '4700000999' + )sub ON sub.ASIEN = x.Asien + SET m.BaseIva1 = x.BASEEURO , + m.PorIva1 = x.IVA, + m.CuotaIva1 = (x.IVA/100) * x.BASEEURO , + m.CodigoTransaccion1 = 20 , + m.CodigoIva1 = IF(x.IVA = 10, 22, 90), + m.Serie = x.SERIE, + m.Factura = x.FACTURA, + m.TipoFactura = "R", + m.FechaFacturaOriginal = x.FECHA_EX + -- m.Año m.FechaFactura + WHERE (x.SUBCTA = '4700000999' OR x.CONTRA = "4330002067") AND + x.SERIE IN ('R','D'); + +-- Rectificativas +UPDATE movConta m + JOIN (SELECT x.ASIEN, x.FECHA_RT, x.SERIE_RT, x.FACTU_RT + FROM movConta m + JOIN vn.XDiario x ON x.ASIEN = m.Asiento + WHERE m.TipoRectificativa>0 AND + m.enlazadoSage = FALSE AND + x.FACTU_RT IS NOT NULL + GROUP BY x.ASIEN + ) sub ON sub.ASIEN = m.Asiento + SET m.EjercicioFacturaOriginal = YEAR(sub.FECHA_RT), + m.SerieFacturaOriginal = sub.SERIE_RT, + m.NumeroFacturaOriginal = sub.FACTU_RT + WHERE m.TipoRectificativa>0 AND + m.enlazadoSage = FALSE ; + +/*-- 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 `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 `planCuentasPgcAdd` */; +/*!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 `planCuentasPgcAdd`() +BEGIN + +TRUNCATE TABLE planCuentasPGC; + +REPLACE INTO planCuentasPGC( + CodigoEmpresa, + CodigoCuenta, + Cuenta, + ClienteOProveedor + ) + SELECT codigoEmpresa, CodigoCuenta, Cuenta, ClienteOProveedor + FROM + ( + SELECT + IF (@@hostname = 'db', c.companyCode, companyCodeTest) AS codigoEmpresa, + e.id AS CodigoCuenta, + UCASE(e.name) AS Cuenta, + '' AS ClienteOProveedor + FROM + (vn.expence e + JOIN vn.company c) + WHERE + c.companyCode + GROUP BY e.id + + UNION + SELECT + IF (@@hostname = 'db', c.companyCode, companyCodeTest) AS codigoEmpresa, + b.account AS CodigoCuenta, + UCASE(b.bank) AS Cuenta, + '' AS ClienteOProveedor + FROM + (vn.bank b + JOIN vn.company c) + WHERE (c.companyCode AND b.isActive) + AND b.account + GROUP BY b.account + UNION + SELECT + codigoEmpresa, + CodigoCuenta, + Nombre AS Cuenta, + ClienteOProveedor + FROM clientesProveedores + GROUP BY CodigoCuenta + ) pgc + GROUP BY CodigoCuenta; + +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; + + 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; + + 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 + 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; + 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; + 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, 'C', '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 + FROM vn.XDiario + WHERE BASEEURO <> 0 AND ASIEN = (SELECT ASIEN FROM vn.XDiario WHERE id = vXDiarioId) + )sub + SET xmi.CodigoRetencion = t.CodigoRetencion, + xmi.BaseRetencion = sub.taxableBase, + xmi.PorRetencion = t.PorcentajeRetencion, + xmi.ImporteRetencion = iit.taxableBase + 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_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`() +BEGIN + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vXDiarioFk INT; + DECLARE rs CURSOR FOR + SELECT IFNULL(ii.id,x.FACTURA) invoiceInFk, x.id XDiarioFk + FROM vn2008.XDiario x + LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id + WHERE x.enlazadoSage=0 + AND ((SUBCTA<>"4700000999" AND ii.id IS NOT NULL) + OR (SUBCTA LIKE '472%' AND CONTRA ='4330002067' AND ii.id IS NULL)) ; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + 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 enlazadoSage = 0 AND + SUBCTA = '4700000999' + ) 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.issued >= CONCAT(YEAR(NOW())-1, "-01-01" ) + UNION ALL + SELECT d.id , + d.code , + 'D' , + 442 , + d.issued , + FALSE, + d.id, + c.code + FROM vn.dua d + JOIN vn.awb a ON a.id= d.awbFk + JOIN vn.invoiceIn i ON i.id = a.invoiceInFk + JOIN vn.currency c ON c.id = i.currencyFk; + + 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; + CLOSE rs; + + UPDATE sage.XDiario_movConta_IVA xmi + JOIN ( SELECT sub.invoiceIn invoiceIn, XDiarioFk, SUM(total) total, tipo + FROM (SELECT IFNULL(ii.id,x.FACTURA) invoiceIn, x.id XDiarioFk,tc.type tipo, 1 as total + FROM vn2008.XDiario x + LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id + LEFT JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN vn.taxCode tc ON tc.id = iit.taxCodeFk + WHERE x.enlazadoSage = 0 AND + ((SUBCTA<>"4700000999" AND ii.id IS NOT NULL) OR + (SUBCTA LIKE '472%' AND CONTRA ='4330002067' AND ii.id IS NULL)) AND + serial='R' + GROUP BY invoiceIn, XDiarioFk,tc.type + )sub + GROUP BY sub.invoiceIn, sub.XDiarioFk + HAVING tipo='-' AND total=1 + ) sub2 ON sub2.invoiceIn = xmi.LibreA1 AND sub2.XDiarioFk = xmi.id + SET moveData = FALSE; + +-- Gastos + UPDATE XDiario_movConta_IVA xm + JOIN vn.XDiario x ON x.id = xm.id + JOIN(SELECT x.id,x.ASIEN + FROM vn.XDiario x + JOIN (SELECT DISTINCT(x.ASIEN) id + FROM XDiario_movConta_IVA xm + JOIN vn.XDiario x ON x.id = xm.id + WHERE xm.moveData = FALSE + ) sub ON sub.id = x.ASIEN + WHERE x.FACTURA>0 AND x.CLAVE IS NULL AND x.SERIE = 'R' + )sub2 ON sub2.ASIEN = x.ASIEN + SET xm.id= sub2.id , xm.moveData = TRUE + WHERE xm.moveData = FALSE; + + DROP TEMPORARY TABLE tmp.invoiceDua; + DROP TEMPORARY TABLE tmp.invoiceInList; +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__`() +BEGIN + + DECLARE done BOOL DEFAULT FALSE; + DECLARE vInvoiceFk INT; + DECLARE vXDiarioFk INT; + DECLARE rs CURSOR FOR + SELECT IFNULL(ii.id,x.FACTURA) invoiceInFk, x.id XDiarioFk + FROM vn2008.XDiario x + LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id + WHERE x.enlazadoSage=0 + AND ((SUBCTA<>"4700000999" AND ii.id IS NOT NULL) + OR (SUBCTA LIKE '472%' AND CONTRA ='4330002067' AND ii.id IS NULL)) ; + +/*VALORAR QUITAR LAS FACTURAS CON IVA 0 + FROM vn.invoiceInTax iit + JOIN vn.taxCode tx ON tx.id = iit.taxCodeFk + WHERE iit.rate <> 0 +*/ + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + 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 enlazadoSage=0 AND + SUBCTA = '4700000999' + ) + AND (CONTRA <> "4330002067" OR CONTRA IS NULL); + + 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; + + CLOSE rs; + + DROP TEMPORARY TABLE tmp.invoiceDua; + + DELETE xmi + FROM sage.XDiario_movConta_IVA xmi + JOIN ( SELECT sub.invoiceIn invoiceIn, XDiarioFk, SUM(total) total, tipo + FROM (SELECT IFNULL(ii.id,x.FACTURA) invoiceIn, x.id XDiarioFk,tc.type tipo, 1 as total + FROM vn2008.XDiario x + LEFT JOIN vn.invoiceIn ii ON x.CLAVE = ii.id + LEFT JOIN vn.invoiceInTax iit ON iit.invoiceInFk = ii.id + LEFT JOIN vn.taxCode tc ON tc.id = iit.taxCodeFk + WHERE x.enlazadoSage = 0 AND + ((SUBCTA<>"4700000999" AND ii.id IS NOT NULL) OR + (SUBCTA LIKE '472%' AND CONTRA ='4330002067' AND ii.id IS NULL)) AND + serial='R' + GROUP BY invoiceIn, XDiarioFk,tc.type + )sub + GROUP BY sub.invoiceIn, sub.XDiarioFk + HAVING tipo='-' AND total=1 + ) sub2 ON sub2.invoiceIn = xmi.LibreA1 AND sub2.XDiarioFk = xmi.id ; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `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; + + -- IVA + DECLARE rs CURSOR FOR + SELECT IF (x.EURODEBE<>0, x.BASEEURO, IF (EUROHABER<>0,- x.BASEEURO,x.BASEEURO )) BASEEURO, + IF (x.EURODEBE<>0, x.EURODEBE,- x.EUROHABER) vat, + tc.rate, + tc.transactionCode, + tc.taxCode, + tc.isIntracommunity, + tc.operationCode, + i.id + FROM vn2008.XDiario x + JOIN vn.taxCode tc + ON tc.id = ( SELECT id + FROM vn.taxCode + WHERE `code` = x.SUBCTA + AND dated <= x.FECHA + ORDER BY dated DESC + LIMIT 1 + ) + JOIN vn.taxType tt ON tt.id= tc.taxTypeFk + LEFT JOIN tmp.invoiceDua i ON i.id = vXDiarioId + WHERE x.ASIEN = (SELECT ASIEN FROM vn2008.XDiario WHERE id = vXDiarioId) + AND x.FACTURA > 0 + AND tt.countryFk=1 + AND x.SUBCTA LIKE '472%' + AND x.FECREGCON > 0 + AND x.enlazadoSage = FALSE + ORDER BY tc.transactionCode DESC,tc.rate DESC; + + 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; + + 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 + + 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; + + 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; + END IF; + CLOSE rs; + + -- DUA OTROS CAMPOS RELATIVOS A LAS FACTURAS + UPDATE XDiario_movConta_IVA xmi + JOIN sage.invoiceInList ii ON ii.id = vInvoiceInFk + JOIN vn2008.XDiario x ON x.id = xmi.id + JOIN vn.supplier s ON s.id = ii.supplierFk + JOIN Naciones n ON n.countryFk = s.countryFk + SET + xmi.Año = YEAR(ii.issued), + xmi.Serie = ii.serial, + xmi.Factura = x.FACTURA, + xmi.FechaFactura = ii.issued, + xmi.ImporteFactura = BaseIva1 + CuotaIva1 + BaseIva2 + CuotaIva2 + BaseIva3 + CuotaIva3 + BaseIva4 + CuotaIva4, + xmi.TipoFactura = 'R', + 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; + + -- NO DUA OTROS CAMPOS RELATIVOS A LAS FACTURAS + UPDATE XDiario_movConta_IVA xmi + JOIN sage.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 + 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 + JOIN Naciones n ON n.countryFk = s.countryFk + SET xmi.Año = YEAR(ii.issued), + xmi.Serie = ii.serial, + xmi.Factura = serialNumber, + xmi.FechaFactura = ii.issued, + xmi.ImporteFactura = BaseIva1 + CuotaIva1 + BaseIva2 + CuotaIva2 + BaseIva3 + CuotaIva3 + BaseIva4 + CuotaIva4, + xmi.TipoFactura = IF(id.id, 'C', '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 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____' OR s.account LIKE '_____3____'); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `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; + DECLARE vBase DOUBLE; + DECLARE vVat DOUBLE; + DECLARE vRate DOUBLE; + DECLARE vIs340 DOUBLE; + DECLARE vIs347 DOUBLE; + DECLARE vVatRE DOUBLE; + DECLARE vRateRE DOUBLE; + DECLARE vTransactionCode INT; + DECLARE vCounter INT DEFAULT 0; + DECLARE vInvoiceOutCorrectedFk INT; + DECLARE vTaxCode INT; + DECLARE vIsIntracommunity BOOL DEFAULT FALSE; + DECLARE vOperationCode VARCHAR(1); + + -- IVA + DECLARE rs CURSOR FOR + SELECT oit.taxableBase, + oit.vat, + pgc.rate, + pgc.mod340, + pgc.mod347, + pgcRE.rate as rateRE, + oitRE.vat as vatRE, + tc.transactionCode , + tc.taxCode, + tc.isIntracommunity, + tc.operationcode + FROM vn.invoiceOutTax oit + JOIN vn.pgc ON pgc.code = oit.pgcFk + LEFT JOIN vn.pgcEqu e ON e.vatFk = oit.pgcFk + LEFT JOIN vn.pgcEqu eRE ON eRE.equFk = oit.pgcFk + LEFT JOIN vn.invoiceOutTax oitRE ON oitRE.invoiceOutFk = oit.invoiceOutFk AND oitRE.pgcFk = e.equFk + LEFT JOIN vn.pgc pgcRE ON pgcRE.code = oitRE.pgcFk + LEFT JOIN vn.taxCode tc ON tc.code = pgc.code COLLATE 'utf8_general_ci' + WHERE eRE.equFk Is NULL + AND oit.invoiceOutFk = vInvoiceOutFk + GROUP by pgc.code; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + + DELETE FROM XDiario_movConta_IVA + WHERE id = vXDiarioId; + + INSERT INTO XDiario_movConta_IVA(id) + VALUES (vXDiarioId); + OPEN rs; + FETCH rs INTO vBase, + vVat, + vRate, + vIs340, + vIs347, + vVatRE, + vRateRE, + vTransactionCode, + vTaxCode, + vIsIntracommunity, + vOperationCode; + + WHILE NOT vDone DO + + IF vOperationCode IS NOT NULL THEN + UPDATE XDiario_movConta_IVA + SET ClaveOperacionFactura = vOperationCode + WHERE id = vXDiarioId; + END IF; + + SET vCounter = vCounter + 1; + CASE vCounter + WHEN 1 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva1 = vBase, + PorIva1 = vRate, + CuotaIva1 = vVat, + PorRecargoEquivalencia1 = vVatRE, + RecargoEquivalencia1 = vRateRE, + CodigoTransaccion1 = vTransactionCode, + CodigoIva1 = vTaxCode + WHERE id = vXDiarioId; + WHEN 2 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva2 = vBase, + PorIva2 = vRate, + CuotaIva2 = vVat, + PorRecargoEquivalencia2 = vVatRE, + RecargoEquivalencia2 =vRateRE, + CodigoTransaccion2 = vTransactionCode, + CodigoIva2 = vTaxCode + WHERE id = vXDiarioId; + WHEN 3 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva3 = vBase, + PorIva3 = vRate, + CuotaIva3 = vVat, + PorRecargoEquivalencia3 = vVatRE, + RecargoEquivalencia3 = vRateRE, + CodigoTransaccion3 = vTransactionCode, + CodigoIva3 = vTaxCode + WHERE id = vXDiarioId; + WHEN 4 THEN + UPDATE XDiario_movConta_IVA + SET BaseIva4 = vBase, + PorIva4 = vRate, + CuotaIva4 = vVat, + PorRecargoEquivalencia4 = vVatRE, + RecargoEquivalencia4 = vRateRE, + CodigoTransaccion4 = vTransactionCode, + CodigoIva4 = vTaxCode + WHERE id = vXDiarioId; + END CASE; + + UPDATE XDiario_movConta_IVA + SET Exclusion347 = NOT vIs347 + WHERE id = vXDiarioId; + + IF vIsIntracommunity THEN + UPDATE XDiario_movConta_IVA + SET Intracomunitaria = TRUE + WHERE id = vXDiarioId; + END IF; + + FETCH rs INTO vBase, + vVat, + vRate, + vIs340, + vIs347, + vVatRE, + vRateRE, + vTransactionCode, + vTaxCode, + vIsIntracommunity, + vOperationCode; + END WHILE; + CLOSE rs; + -- OTROS CAMPOS RELATIVOS A LAS FACTURAS + UPDATE XDiario_movConta_IVA xmi + JOIN vn.invoiceOut io ON io.id = vInvoiceOutFk + LEFT JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutFk + LEFT JOIN vn.invoiceOut ioc ON ioc.id = ic.correctingFk + JOIN vn2008.XDiario x ON x.id = xmi.id + JOIN vn.client c ON c.id = io.clientFk + JOIN Naciones n ON n.countryFk = c.countryFk + JOIN vn.invoiceOutSerial ios ON ios.code = io.serial + JOIN vn.taxArea ta ON ta.code = ios.taxAreaFk + JOIN (SELECT SERIE + FROM vn2008.XDiario + WHERE ASIEN = (SELECT ASIEN + FROM vn2008.XDiario + WHERE id = vXDiarioId + ) + AND SERIE IS NOT NULL + ) sub + SET xmi.Año = YEAR(io.issued), + xmi.Serie = sub.SERIE, + xmi.Factura = RIGHT(io.ref, LENGTH(io.ref) -1), + xmi.FechaFactura = io.issued, + xmi.ImporteFactura = io.amount, + xmi.TipoFactura = "E", + xmi.CodigoCuentaFactura = x.SUBCTA, + xmi.CifDni = c.fi, + xmi.Nombre = SUBSTR(c.socialName,1,35), + xmi.SiglaNacion = n.SiglaNacion, + xmi.EjercicioFactura = YEAR(io.issued), + xmi.FechaOperacion = io.issued, + xmi.MantenerAsiento = TRUE, + xmi.FechaFacturaOriginal = x.FECHA_EX + WHERE xmi.id = vXDiarioId; + + -- RECTIFICATIVAS + SELECT correctedFk + INTO vInvoiceOutCorrectedFk + FROM vn.invoiceCorrection + WHERE correctingFk = vInvoiceOutFk; + + IF vInvoiceOutCorrectedFk THEN + UPDATE XDiario_movConta_IVA xmi + JOIN vn.invoiceOut ioc ON ioc.id = vInvoiceOutCorrectedFk + JOIN vn.invoiceCorrection ic ON ic.correctedFk = vInvoiceOutCorrectedFk + JOIN vn.invoiceOut io ON io.id = vInvoiceOutCorrectedFk + JOIN ( + SELECT sum(IF(IFNULL(e.vatFk,1),iot.taxableBase,0)) AS Base, + sum(IF(IFNULL(e.vatFk,1),iot.vat,0)) AS CuotaIva, + sum(IF(IFNULL(e.vatFk,1),0,iot.vat)) as RE + FROM vn.invoiceOutTax iot + LEFT JOIN vn.pgcEqu e ON e.vatFk = iot.pgcFk + WHERE iot.invoiceOutFk = vInvoiceOutCorrectedFk + ) iocTAX + SET xmi.TipoRectificativa = 2, + xmi.ClaseAbonoRectificativas = ic.invoiceCorrectionTypeFk, + xmi.FechaFacturaOriginal = io.issued, + xmi.BaseImponibleOriginal = iocTAX.Base, + xmi.CuotaIvaOriginal = iocTAX.CuotaIva, + xmi.RecargoEquivalenciaOriginal = RE, + xmi.ClaveOperacionFactura = 'D' + WHERE xmi.id = vXDiarioId; + 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 `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 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 + 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; + 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` -- @@ -17965,6 +21464,26 @@ CREATE TABLE `versionUser` ( -- -- Dumping routines for database 'util' -- +/*!50003 DROP FUNCTION IF EXISTS `accountShortToStandard` */; +/*!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 `accountShortToStandard`(vAccount VARCHAR(10)) RETURNS varchar(10) CHARSET utf8 COLLATE utf8_unicode_ci + DETERMINISTIC +BEGIN + RETURN REPLACE(vAccount, '.', REPEAT('0', 11 - LENGTH(vAccount))); +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 `capitalizeFirst` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -18255,6 +21774,26 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; ALTER DATABASE `util` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP FUNCTION IF EXISTS `quarterFirstDay` */; +/*!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 `quarterFirstDay`(vYear INT, vQuarter INT) RETURNS date + DETERMINISTIC +BEGIN + RETURN CONCAT(vYear,"-", ((vQuarter - 1) * 3) + 1, "-01"); +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 `stringXor` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -18775,7 +22314,7 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`jenkins`@`172.16.%.%` PROCEDURE `procNoOverlap`(procName VARCHAR(255)) +CREATE DEFINER=`root`@`%` PROCEDURE `procNoOverlap`(procName VARCHAR(255)) SQL SECURITY INVOKER proc: BEGIN /** @@ -19231,6 +22770,7 @@ CREATE TABLE `address` ( `isEqualizated` tinyint(1) DEFAULT NULL, `customsAgentFk` int(11) DEFAULT NULL, `incotermsFk` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL, + `isVilassarBuyer` tinyint(4) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `Id_Agencia` (`agencyModeFk`), KEY `Id_cliente` (`clientFk`), @@ -20175,6 +23715,23 @@ SET character_set_client = utf8; 1 AS `dated`*/; SET character_set_client = @saved_cs_client; +-- +-- Table structure for table `campaign` +-- + +DROP TABLE IF EXISTS `campaign`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `campaign` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `code` enum('mothersDay','allSaints','valentinesDay') COLLATE utf8_unicode_ci NOT NULL, + `dated` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, + `scopeDays` int(11) NOT NULL DEFAULT '15', + PRIMARY KEY (`id`), + UNIQUE KEY `campaign_dated_uindex` (`dated`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `category` -- @@ -20611,6 +24168,7 @@ CREATE TABLE `client` ( `taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de Iva por defecto asociado al cliente en SAGE', `transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Tipo de transacción por defecto asociado al cliente en SAGE', `transferorFk` int(11) DEFAULT NULL COMMENT 'Cliente que le ha transmitido la titularidad de la empresa', + `lastSalesPersonFk` int(11) DEFAULT NULL COMMENT 'ultimo comercial que tuvo, para el calculo del peso en los rankings de equipo', PRIMARY KEY (`id`), UNIQUE KEY `IF` (`fi`), KEY `Id_Trabajador` (`salesPersonFk`), @@ -20659,6 +24217,8 @@ BEGIN CALL pbx.phone_isValid(NEW.fax); SET NEW.accountingAccount = 4300000000 + NEW.id; + + SET NEW.lastSalesPersonFk = NEW.salesPersonFk; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -20732,6 +24292,9 @@ BEGIN SET datEND = CURDATE() WHERE Id_Cliente = NEW.id; END IF; + + SET NEW.lastSalesPersonFk = IFNULL(NEW.salesPersonFk, OLD.salesPersonFk); + END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -21072,16 +24635,27 @@ DROP TABLE IF EXISTS `cmr`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `cmr` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `ticketFk` int(11) NOT NULL, + `ticketFk` int(11) DEFAULT NULL, `truckPlate` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL, `observations` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `senderInstruccions` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'Flowers 4º C. Plants 14º C', `paymentInstruccions` varchar(255) COLLATE utf8_unicode_ci DEFAULT 'Carriage paid', `specialAgreements` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP, + `companyFk` smallint(5) unsigned DEFAULT NULL, + `addressToFk` int(11) DEFAULT NULL, + `addressFromFk` int(11) DEFAULT NULL, + `supplierFk` int(11) DEFAULT NULL, + `packagesList` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), KEY `cmr_fk1_idx` (`ticketFk`), - CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE + KEY `cmr_fk2_idx` (`companyFk`), + KEY `cmr_fk3_idx` (`addressToFk`), + KEY `cm_fk4_idx` (`supplierFk`), + CONSTRAINT `cm_fk4` FOREIGN KEY (`supplierFk`) REFERENCES `supplier` (`id`) ON UPDATE CASCADE, + CONSTRAINT `cmr_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `ticket` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `cmr_fk2` FOREIGN KEY (`companyFk`) REFERENCES `company` (`id`) ON DELETE SET NULL ON UPDATE CASCADE, + CONSTRAINT `cmr_fk3` FOREIGN KEY (`addressToFk`) REFERENCES `address` (`id`) ON DELETE SET NULL ON UPDATE CASCADE ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; @@ -21142,8 +24716,7 @@ SET character_set_client = utf8; 1 AS `paymentInstruccions`, 1 AS `specialAgreements`, 1 AS `created`, - 1 AS `addressFk`, - 1 AS `shipped`, + 1 AS `packagesList`, 1 AS `clientName`, 1 AS `clientPostalCode`, 1 AS `clientStreet`, @@ -21156,6 +24729,7 @@ SET character_set_client = utf8; 1 AS `companyCity`, 1 AS `companyCountry`, 1 AS `warehouseAddress`, + 1 AS `shipped`, 1 AS `clientOficialName`, 1 AS `carrierName`, 1 AS `carrierStreet`, @@ -21163,7 +24737,8 @@ SET character_set_client = utf8; 1 AS `carrierCity`, 1 AS `carrierCountry`, 1 AS `phone`, - 1 AS `mobile`*/; + 1 AS `mobile`, + 1 AS `addressFk`*/; SET character_set_client = @saved_cs_client; -- @@ -21222,6 +24797,26 @@ CREATE TABLE `collectionVolumetry` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `commissionConfig` +-- + +DROP TABLE IF EXISTS `commissionConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `commissionConfig` ( + `rate` decimal(5,4) NOT NULL DEFAULT '0.0000', + `plusTeamAmount` int(11) DEFAULT NULL, + `plusNewBornAmount` int(11) DEFAULT NULL, + `plusSalesAmount` int(11) DEFAULT NULL, + `minimumSalesByQuarter` int(11) DEFAULT NULL, + `plusTeamRange` int(11) DEFAULT NULL, + `plusNewBornRange` int(11) DEFAULT NULL, + `rankingSalesRange` int(11) DEFAULT NULL, + PRIMARY KEY (`rate`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `company` -- @@ -21484,6 +25079,31 @@ CREATE TABLE `contactChannel` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Canal por el que nos ha conocido un cliente y se ha dado de'; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `contratos_subvencion_270619` +-- + +DROP TABLE IF EXISTS `contratos_subvencion_270619`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `contratos_subvencion_270619` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `workerFk` int(11) NOT NULL, + `cod_centroFk` int(11) NOT NULL, + `CodContratoFk` int(11) NOT NULL, + `journey` decimal(5,2) NOT NULL DEFAULT '8.00', + `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `nif` varchar(12) COLLATE utf8_unicode_ci NOT NULL, + PRIMARY KEY (`id`), + KEY `contratos_subvencion_270619_fk2_idx` (`cod_centroFk`), + KEY `contratos_subvencion_270619_fk3_idx` (`CodContratoFk`), + KEY `contratos_subvencion_270619_fk1_idx` (`workerFk`), + CONSTRAINT `contratos_subvencion_270619_fk1` FOREIGN KEY (`workerFk`) REFERENCES `worker` (`id`) ON UPDATE CASCADE, + CONSTRAINT `contratos_subvencion_270619_fk2` FOREIGN KEY (`cod_centroFk`) REFERENCES `vn2008`.`payroll_centros` (`cod_centro`) ON UPDATE CASCADE, + CONSTRAINT `contratos_subvencion_270619_fk3` FOREIGN KEY (`CodContratoFk`) REFERENCES `vn2008`.`payroll_contratos` (`CodContrato`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Segun los informes de vida laboral aportados por la SS'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `conveyor` -- @@ -22079,6 +25699,7 @@ CREATE TABLE `department` ( `path` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `chatName` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, `isTeleworking` tinyint(1) DEFAULT '0', + `notificationEmail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `fk_department_Trabajadores1_idx` (`workerFk`), @@ -22924,6 +26545,11 @@ CREATE TABLE `entryLog` ( `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL, `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP, `description` text CHARACTER SET utf8, + `changedModel` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, + `oldInstance` text COLLATE utf8_unicode_ci, + `newInstance` text COLLATE utf8_unicode_ci, + `changedModelId` int(11) DEFAULT NULL, + `changedModelValue` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), KEY `logEntry_ibfk_1` (`originFk`), KEY `entryLog_ibfk_2` (`userFk`), @@ -22932,6 +26558,25 @@ CREATE TABLE `entryLog` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `entryShelving` +-- + +DROP TABLE IF EXISTS `entryShelving`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `entryShelving` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `entryFk` int(11) NOT NULL DEFAULT '204088', + `shelvingFk` varchar(10) CHARACTER SET utf8 NOT NULL, + PRIMARY KEY (`id`), + KEY `entryShelving_fk1_idx` (`entryFk`), + KEY `entryShelving_fk2_idx` (`shelvingFk`), + CONSTRAINT `entryShelving_fk1` FOREIGN KEY (`entryFk`) REFERENCES `entry` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `entryShelving_fk2` FOREIGN KEY (`shelvingFk`) REFERENCES `shelving` (`code`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='relaciona matriculas con entradas'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `entrySplit` -- @@ -23289,7 +26934,8 @@ SET character_set_client = utf8; 1 AS `scanFk`, 1 AS `expeditionFk`, 1 AS `expeditionTruckFk`, - 1 AS `warehouseFk`*/; + 1 AS `warehouseFk`, + 1 AS `lastPacked`*/; SET character_set_client = @saved_cs_client; -- @@ -23355,6 +27001,21 @@ SET character_set_client = utf8; 1 AS `warehouseFk`*/; SET character_set_client = @saved_cs_client; +-- +-- Temporary table structure for view `expeditionRoute_Monitor` +-- + +DROP TABLE IF EXISTS `expeditionRoute_Monitor`; +/*!50001 DROP VIEW IF EXISTS `expeditionRoute_Monitor`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `expeditionRoute_Monitor` AS SELECT + 1 AS `routeFk`, + 1 AS `expeditions`, + 1 AS `scanned`, + 1 AS `lastPacked`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `expeditionScan` -- @@ -23508,7 +27169,8 @@ SET character_set_client = utf8; 1 AS `routes`, 1 AS `scans`, 1 AS `expeditions`, - 1 AS `fallos`*/; + 1 AS `fallos`, + 1 AS `lastPacked`*/; SET character_set_client = @saved_cs_client; -- @@ -23527,7 +27189,8 @@ SET character_set_client = utf8; 1 AS `routes`, 1 AS `scans`, 1 AS `destinos`, - 1 AS `fallos`*/; + 1 AS `fallos`, + 1 AS `lastPacked`*/; SET character_set_client = @saved_cs_client; -- @@ -23547,65 +27210,8 @@ SET character_set_client = utf8; 1 AS `scans`, 1 AS `destinos`, 1 AS `fallos`, - 1 AS `expeditionTruckFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control_Detail_Pallet__` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control_Detail_Pallet__`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet__`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control_Detail_Pallet__` AS SELECT - 1 AS `id`, - 1 AS `ETD`, - 1 AS `destino`, - 1 AS `pallet`, - 1 AS `route`, - 1 AS `scans`, - 1 AS `destinos`, - 1 AS `fallos`, - 1 AS `expeditionTruckFk`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control_Detail__` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control_Detail__`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail__`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control_Detail__` AS SELECT - 1 AS `id`, - 1 AS `ETD`, - 1 AS `destino`, - 1 AS `pallet`, - 1 AS `routes`, - 1 AS `scans`, - 1 AS `destinos`, - 1 AS `fallos`*/; -SET character_set_client = @saved_cs_client; - --- --- Temporary table structure for view `expeditionTruck_Control__` --- - -DROP TABLE IF EXISTS `expeditionTruck_Control__`; -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control__`*/; -SET @saved_cs_client = @@character_set_client; -SET character_set_client = utf8; -/*!50001 CREATE VIEW `expeditionTruck_Control__` AS SELECT - 1 AS `id`, - 1 AS `ETD`, - 1 AS `description`, - 1 AS `pallets`, - 1 AS `routes`, - 1 AS `scans`, - 1 AS `expeditions`, - 1 AS `fallos`*/; + 1 AS `expeditionTruckFk`, + 1 AS `lastPacked`*/; SET character_set_client = @saved_cs_client; -- @@ -26061,6 +29667,44 @@ CREATE TABLE `messageInbox` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `mistake` +-- + +DROP TABLE IF EXISTS `mistake`; +/*!50001 DROP VIEW IF EXISTS `mistake`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `mistake` AS SELECT + 1 AS `revisador`, + 1 AS `concept`, + 1 AS `sacador`, + 1 AS `firstName`, + 1 AS `lastName`, + 1 AS `description`, + 1 AS `created`, + 1 AS `workerFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `mistakeRatio` +-- + +DROP TABLE IF EXISTS `mistakeRatio`; +/*!50001 DROP VIEW IF EXISTS `mistakeRatio`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `mistakeRatio` AS SELECT + 1 AS `revisador`, + 1 AS `sacador`, + 1 AS `firstName`, + 1 AS `lastName`, + 1 AS `description`, + 1 AS `created`, + 1 AS `workerFk`, + 1 AS `saleFk`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `mistakeType` -- @@ -26104,9 +29748,24 @@ CREATE TABLE `mrw` ( `shipped` date DEFAULT NULL, `price` decimal(10,2) DEFAULT NULL, PRIMARY KEY (`id`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `newBornSales` +-- + +DROP TABLE IF EXISTS `newBornSales`; +/*!50001 DROP VIEW IF EXISTS `newBornSales`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `newBornSales` AS SELECT + 1 AS `amount`, + 1 AS `userFk`, + 1 AS `dated`, + 1 AS `firstShipped`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `noticeCategory` -- @@ -26154,6 +29813,7 @@ DROP TABLE IF EXISTS `observationType`; CREATE TABLE `observationType` ( `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT, `description` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `code` varchar(45) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; @@ -26347,13 +30007,12 @@ DROP TABLE IF EXISTS `parking`; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `parking` ( `id` int(11) NOT NULL AUTO_INCREMENT, - `column` varchar(5) CHARACTER SET utf8 NOT NULL DEFAULT '--', - `row` varchar(5) CHARACTER SET utf8 NOT NULL DEFAULT '--', + `column` varchar(5) CHARACTER SET utf8 DEFAULT '--', + `row` varchar(5) CHARACTER SET utf8 DEFAULT '--', `sectorFk` int(11) NOT NULL DEFAULT '2', `code` varchar(8) CHARACTER SET utf8 DEFAULT NULL, `pickingOrder` int(11) DEFAULT NULL, PRIMARY KEY (`id`), - UNIQUE KEY `column_UNIQUE` (`column`,`row`,`sectorFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `parking_fk1_idx` (`sectorFk`), CONSTRAINT `parking_fk1` FOREIGN KEY (`sectorFk`) REFERENCES `sector` (`id`) ON DELETE CASCADE ON UPDATE CASCADE @@ -26994,6 +30653,7 @@ CREATE TABLE `printServerQueue` ( `param2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, `param3` text COLLATE utf8_unicode_ci, `error` text COLLATE utf8_unicode_ci, + `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `Id_Impresora_2` (`printerFk`,`priorityFk`,`reportFk`,`statusFk`,`param1`,`workerFk`,`param2`), KEY `Id_estado` (`statusFk`), @@ -27286,6 +30946,36 @@ CREATE TABLE `queuePriority` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Temporary table structure for view `rankingNewBornByQuarter__` +-- + +DROP TABLE IF EXISTS `rankingNewBornByQuarter__`; +/*!50001 DROP VIEW IF EXISTS `rankingNewBornByQuarter__`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `rankingNewBornByQuarter__` AS SELECT + 1 AS `total`, + 1 AS `name`, + 1 AS `time_sec`, + 1 AS `userFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `rankingSellingByQuarter__` +-- + +DROP TABLE IF EXISTS `rankingSellingByQuarter__`; +/*!50001 DROP VIEW IF EXISTS `rankingSellingByQuarter__`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `rankingSellingByQuarter__` AS SELECT + 1 AS `importe`, + 1 AS `name`, + 1 AS `userFk`, + 1 AS `time_sec`*/; +SET character_set_client = @saved_cs_client; + -- -- Table structure for table `rateConfig` -- @@ -28310,6 +32000,7 @@ CREATE TABLE `sector` ( `isPackagingArea` tinyint(1) NOT NULL DEFAULT '0', `labelReport` int(11) DEFAULT NULL, `sonFk` int(11) DEFAULT NULL, + `isMain` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`,`warehouseFk`), UNIQUE KEY `code_UNIQUE` (`code`), KEY `sector_fk1_idx` (`warehouseFk`), @@ -28829,6 +32520,7 @@ CREATE TABLE `supplier` ( `taxTypeSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipo de IVA SAGE', `withholdingSageFk` smallint(6) DEFAULT NULL COMMENT 'Tipos de retención SAGE', `transactionTypeSageFk` tinyint(4) DEFAULT NULL COMMENT 'Ti po de transacción SAGE', + `isTrucker` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), UNIQUE KEY `cuenta` (`account`), UNIQUE KEY `NIF` (`nif`), @@ -29249,6 +32941,16 @@ BEGIN VALUES(NEW.clientFk, IFNULL(vTransferorFirstShipped, CURDATE()), CURDATE()) ON DUPLICATE KEY UPDATE lastShipped = CURDATE(); END IF; + + IF NEW.clientFk = 2067 THEN + -- Fallo que se insertan no se sabe como tickets en este cliente + INSERT INTO vn.mail SET + `sender` = 'jgallego@verdnatura.es', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Creado ticket al cliente 2067', + `body` = CONCAT(account.myUserGetName(), ' ha creado el ticket ', + NEW.id); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29332,6 +33034,15 @@ BEGIN WHERE a.id = NEW.addressFk AND ot.description = 'Repartidor'; END IF; + IF NEW.clientFk = 2067 AND !(NEW.clientFk <=> OLD.clientFk) THEN + -- Fallo que se insertan no se sabe como tickets en este cliente + INSERT INTO vn.mail SET + `sender` = 'jgallego@verdnatura.es', + `replyTo` = 'jgallego@verdnatura.es', + `subject` = 'Modificado ticket al cliente 2067', + `body` = CONCAT(account.myUserGetName(), ' ha modificado el ticket ', + NEW.id); + END IF; END */;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -29979,6 +33690,23 @@ CREATE TABLE `ticketWeekly` ( ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; /*!40101 SET character_set_client = @saved_cs_client */; +-- +-- Table structure for table `ticket_print` +-- + +DROP TABLE IF EXISTS `ticket_print`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ticket_print` ( + `ticketFk` int(11) NOT NULL, + `isPrinted` tinyint(1) NOT NULL DEFAULT '0', + `counter` int(11) NOT NULL DEFAULT '0', + `workerFk` int(11) DEFAULT NULL, + `id` int(11) NOT NULL AUTO_INCREMENT, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Tabla para la campaña de Santos 2020'; +/*!40101 SET character_set_client = @saved_cs_client */; + -- -- Table structure for table `till` -- @@ -30643,6 +34371,7 @@ CREATE TABLE `warehouse` ( `isBuyerToBeEmailed` tinyint(2) NOT NULL DEFAULT '0', `aliasFk` smallint(5) unsigned DEFAULT NULL, `labelReport` int(11) DEFAULT NULL, + `hasUbications` tinyint(1) NOT NULL DEFAULT '1', PRIMARY KEY (`id`), UNIQUE KEY `name_UNIQUE` (`name`), KEY `Id_Paises` (`countryFk`), @@ -35625,6 +39354,64 @@ 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 `ticket_getWithParameters` */; +/*!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 `ticket_getWithParameters`(vClientFk INT, vWarehouseFk INT, vShipped DATE, vAddressFk INT, vCompanyFk INT, vAgencyModeFk INT) RETURNS int(11) + DETERMINISTIC +BEGIN +/** + * Devuelve un ticket con los parametros, en caso de no existir lo crea + * + * @param vClientFk Cliente + * @param vWarehouseFk almacen + * @param vShipped Fecha de preparacion + * @param vAddressFk Consignatario + * @param vCompanyFk Empresa + * @param vAgencyModeFk agencia + */ + + DECLARE vTicket INT; + + SELECT t.id INTO vTicket + FROM vn.ticket t + WHERE (t.clientFk <=> vClientFk OR vClientFk IS NULL) + AND (t.warehouseFk <=> vWarehouseFk OR vWarehouseFk IS NULL) + AND (t.shipped <=> vShipped OR vShipped IS NULL) + AND (t.addressFk <=> vAddressFk OR vAddressFk IS NULL) + AND (t.companyFk <=> vCompanyFk OR vCompanyFk IS NULL) + AND (t.agencyModeFk <=> vAgencyModeFk OR vAgencyModeFk IS NULL) + LIMIT 1; + + IF vTicket IS NULL THEN + CALL vn.ticketCreateWithUser( + vClientFk, + IFNULL(vShipped, CURDATE()), + vWarehouseFk, + vCompanyFk, + vAddressFk, + vAgencyModeFk, + NULL, + vShipped, + `account`.`myUserGetId`(), + vTicket + ); + END IF; + + RETURN vTicket; +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 `till_new` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -37446,6 +41233,161 @@ proc: BEGIN DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Establece los almacenes y las fechas que van a entrar al disponible + + CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; + CREATE TEMPORARY TABLE tmp.ticketLot( + `warehouseFk` smallint(5) unsigned NOT NULL, + `itemFk` int(11) NOT NULL, + `available` double DEFAULT NULL, + `buyFk` int(11) DEFAULT NULL, + `fix` tinyint(3) unsigned DEFAULT '0', + `zoneFk` int(11) NOT NULL, + KEY `itemFk` (`itemFk`), + KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH + ) ENGINE=MEMORY DEFAULT CHARSET=utf8; + + CALL catalog_componentPrepare(); + + DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; + CREATE TEMPORARY TABLE tmp.ticketCalculateItem( + itemFk INT(11) NOT NULL, + available INT(11), + producer VARCHAR(50), + item VARCHAR(50), + size INT(10) UNSIGNED, + stems INT(11), + category VARCHAR(3), + inkFk VARCHAR(3), + image VARCHAR(50), + origin VARCHAR(3), + price DECIMAL(10,2), + priceKg DECIMAL(10,2), + PRIMARY KEY `itemFk` (`itemFk`) + ) ENGINE = MEMORY DEFAULT CHARSET=utf8; + + OPEN cTravelTree; + + l: LOOP + SET vDone = FALSE; + FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; + + IF vDone THEN + LEAVE l; + END IF; + + CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); + CALL buyUltimate (vWarehouseFk, vShipped); + + INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk, zoneFk) + SELECT vWarehouseFk, + i.item_id, + IFNULL(i.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; + + DROP TEMPORARY TABLE tmp.buyUltimate; + + CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped, vWarehouseFk); + + INSERT INTO tmp.ticketCalculateItem ( + itemFk, + available, + producer, + item, + size, + stems, + category, + inkFk, + image, + origin, + price, + priceKg) + SELECT + tl.itemFk, + SUM(tl.available) available, + p.name producer, + i.name item, + i.size size, + i.stems, + i.category, + i.inkFk, + i.image, + o.code origin, + bl.price, + bl.priceKg + FROM tmp.ticketLot tl + JOIN item i ON tl.itemFk = i.id + LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible + JOIN origin o ON o.id = i.originFk + JOIN ( + SELECT MAX(price) price, itemFk, priceKg + FROM tmp.ticketComponentPrice + WHERE warehouseFk = vWarehouseFk + GROUP BY itemFk + ) bl ON bl.itemFk = tl.itemFk + WHERE tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk + GROUP BY tl.itemFk + ON DUPLICATE KEY UPDATE available = available + VALUES(available); + + END LOOP; + + CLOSE cTravelTree; + +END ;; +DELIMITER ; +/*!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 `catalog_calculate__` */; +/*!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 `catalog_calculate__`( + vLanded DATE, + vAddressFk INT, + vAgencyModeFk INT) +proc: BEGIN +/** + * Calcula los articulos disponibles y sus precios + * + * @table tmp.item(itemFk) Listado de artículos a calcular + * @param vLanded Fecha de recepcion de mercancia + * @param vAddressFk Id del consignatario + * @param vAgencyModeFk Id de la agencia + * @return tmp.ticketCalculateItem(itemFk, available, producer, + * item, size, stems, category, inkFk, image, origin, price) + * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) + * @return tmp.ticketComponent + * @return tmp.ticketComponentPrice + * @return tmp.zoneGetShipped + */ + + DECLARE vAvailableCalc INT; + DECLARE vShipped DATE; + DECLARE vWarehouseFk SMALLINT; + DECLARE vZoneFk INT; + DECLARE vDone BOOL; + DECLARE cTravelTree CURSOR FOR + SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; + -- Establece los almacenes y las fechas que van a entrar al disponible CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); @@ -37561,7 +41503,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 `catalog_calculate__` */; +/*!50003 DROP PROCEDURE IF EXISTS `catalog_componentCalculate` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -37571,132 +41513,6 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`root`@`%` PROCEDURE `catalog_calculate__`( - vLanded DATE, - vAddressFk INT, - vAgencyModeFk INT) -proc: BEGIN -/** - * Calcula los articulos disponibles y sus precios - * - * @table tmp.item(itemFk) Listado de artículos a calcular - * @param vLanded Fecha de recepcion de mercancia - * @param vAddressFk Id del consignatario - * @param vAgencyModeFk Id de la agencia - * @return tmp.ticketCalculateItem(itemFk, available, producer, - * item, size, stems, category, inkFk, image, origin, price) - * @return tmp.ticketLot(warehouseFk, itemFk, available, buyFk) - * @return tmp.ticketComponent - * @return tmp.ticketComponentPrice - * @return tmp.zoneGetShipped - - **/ - - DECLARE vAvailableCalc INT; - DECLARE vShipped DATE; - DECLARE vClient INT; - DECLARE vWarehouseFk SMALLINT; - DECLARE vZoneFk INT; - DECLARE vDone BOOL; - DECLARE cTravelTree CURSOR FOR - SELECT zoneFk, warehouseFk, shipped FROM tmp.zoneGetShipped; - - DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE; - - -- Establece los almacenes y las fechas que van a entrar al disponible - - SELECT clientFk INTO vClient - FROM address WHERE id = vAddressFk; - - CALL vn.zone_getShipped (vLanded, vAddressFk, vAgencyModeFk, FALSE); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketLot; - CREATE TEMPORARY TABLE tmp.ticketLot( - `warehouseFk` smallint(5) unsigned NOT NULL, - `itemFk` int(11) NOT NULL, - `available` double DEFAULT NULL, - `buyFk` int(11) DEFAULT NULL, - `fix` tinyint(3) unsigned DEFAULT '0', - KEY `itemFk` (`itemFk`), - KEY `item_warehouse` (`itemFk`,`warehouseFk`) USING HASH - ) ENGINE=MEMORY DEFAULT CHARSET=utf8; - - OPEN cTravelTree; - - l: LOOP - SET vDone = FALSE; - FETCH cTravelTree INTO vZoneFk, vWarehouseFk, vShipped; - - IF vDone THEN - LEAVE l; - END IF; - - CALL `cache`.available_refresh (vAvailableCalc, FALSE, vWarehouseFk, vShipped); - CALL buyUltimate (vWarehouseFk, vShipped); - - INSERT INTO tmp.ticketLot (warehouseFk, itemFk, available, buyFk) - SELECT vWarehouseFk, - i.item_id, - IFNULL(i.available, 0), - bu.buyFk - FROM `cache`.available i - JOIN tmp.item br ON br.itemFk = i.item_id - LEFT JOIN item it ON it.id = i.item_id - LEFT JOIN tmp.buyUltimate bu ON bu.itemFk = i.item_id - WHERE i.calc_id = vAvailableCalc - AND it.id != 100 - AND i.available > 0; - - DROP TEMPORARY TABLE tmp.buyUltimate; - END LOOP; - - CLOSE cTravelTree; - - CALL vn.catalog_componentCalculate(vZoneFk, vAddressFk, vShipped); - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketCalculateItem; - CREATE TEMPORARY TABLE tmp.ticketCalculateItem - ENGINE = MEMORY - SELECT - b.itemFk, - SUM(b.available) available, - p.name producer, - i.name item, - i.size size, - i.stems, - i.category, - i.inkFk, - i.image, - o.code origin, - bl.price, - bl.priceKg - FROM tmp.ticketLot b - JOIN item i ON b.itemFk = i.id - LEFT JOIN producer p ON p.id = i.producerFk AND p.isVisible - JOIN origin o ON o.id = i.originFk - JOIN ( - SELECT MIN(price) price, itemFk, priceKg - FROM tmp.ticketComponentPrice - GROUP BY itemFk - ) bl ON bl.itemFk = b.itemFk - GROUP BY b.itemFk; - -END ;; -DELIMITER ; -/*!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 `catalog_componentCalculate` */; -/*!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 `catalog_componentCalculate`( vZoneFk INT, vAddressFk INT, @@ -37751,7 +41567,7 @@ proc: BEGIN IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, @minPrice := IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, IFNULL(@minPrice, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, + IFNULL(pf.packing, GREATEST(b.grouping, b.packing)) packing, IFNULL(pf.`grouping`, b.`grouping`) `grouping`, ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, tl.buyFk, @@ -37959,275 +41775,6 @@ proc: BEGIN tmp.ticketComponentRate, tmp.ticketComponentCopy; -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 `catalog_componentCalculate__` */; -/*!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 `catalog_componentCalculate__`( - vZoneFk INT, - vAddressFk INT, - vShipped DATE, - vWarehouseFk INT) -proc: BEGIN -/** - * Calcula los componentes de los articulos de tmp.ticketLot - * - * @param vZoneFk para calcular el transporte - * @param vAddressFk Consignatario - * @param vShipped dia de salida del pedido - * @param tmp.ticketLot (warehouseFk, available, itemFk, buyFk, zoneFk) - * - * @return tmp.ticketComponent(itemFk, warehouseFk, available, rate2, rate3, minPrice, - * packing, grouping, groupingMode, buyFk, typeFk) - * @return tmp.ticketComponentPrice (warehouseFk, itemFk, rate, grouping, price) - */ - DECLARE vClientFk INT; - DECLARE vGeneralInflationCoefficient INT DEFAULT 1; - DECLARE vMinimumDensityWeight INT DEFAULT 167; - DECLARE vBoxVolume BIGINT; -- DEFAULT 138000; - DECLARE vSpecialPriceComponent INT DEFAULT 10; - DECLARE vDeliveryComponent INT DEFAULT 15; - DECLARE vRecoveryComponent INT DEFAULT 17; - DECLARE vSellByPacketComponent INT DEFAULT 22; - DECLARE vBuyValueComponent INT DEFAULT 28; - DECLARE vMarginComponent INT DEFAULT 29; - DECLARE vDiscountLastItemComponent INT DEFAULT 32; - DECLARE vExtraBaggedComponent INT DEFAULT 38; - DECLARE vManaAutoComponent INT DEFAULT 39; - - SELECT volume INTO vBoxVolume - FROM vn.packaging - WHERE id = '94'; - - SELECT clientFk INTO vClientFK - FROM address - WHERE id = vAddressFk; - - SET @rate2 := 0; - SET @rate3 := 0; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCalculate; - CREATE TEMPORARY TABLE tmp.ticketComponentCalculate - (PRIMARY KEY (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT - tl.itemFk, tl.warehouseFk, tl.available, - IF((@rate2 := IFNULL(pf.rate2, b.price2)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate2) * 1.0 rate2, - IF((@rate3 := IFNULL(pf.rate3, b.price3)) < i.minPrice AND i.hasMinPrice, i.minPrice, @rate3) * 1.0 rate3, - IFNULL(pf.rate3, 0) AS minPrice, - IFNULL(pf.packing, b.packing) packing, - IFNULL(pf.`grouping`, b.`grouping`) `grouping`, - ABS(IFNULL(pf.box, b.groupingMode)) groupingMode, - tl.buyFk, - i.typeFk, - IF(i.hasKgPrice, b.weight / b.packing, NULL) weightGrouping - FROM tmp.ticketLot tl - JOIN buy b ON b.id = tl.buyFk - JOIN item i ON i.id = tl.itemFk - JOIN itemType it ON it.id = i.typeFk - LEFT JOIN itemCategory ic ON ic.id = it.categoryFk - LEFT JOIN specialPrice sp ON sp.itemFk = i.id AND sp.clientFk = vClientFk - LEFT JOIN ( - SELECT * FROM ( - SELECT pf.itemFk, pf.`grouping`, pf.packing, pf.box, pf.rate2, pf.rate3, zw.warehouseFk - FROM priceFixed pf - JOIN zoneWarehouse zw ON zw.zoneFk = vZoneFk AND (zw.warehouseFk = pf.warehouseFk OR pf.warehouseFk = 0) - WHERE vShipped BETWEEN pf.started AND pf.ended ORDER BY pf.itemFk, pf.warehouseFk DESC - ) tpf - GROUP BY tpf.itemFk, tpf.warehouseFk - ) pf ON pf.itemFk = tl.itemFk AND pf.warehouseFk = tl.warehouseFk - WHERE b.buyingValue + b.freightValue + b.packageValue + b.comissionValue > 0.01 AND ic.display <> 0 - AND tl.zoneFk = vZoneFk AND tl.warehouseFk = vWarehouseFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vBuyValueComponent, - b.buyingValue + b.freightValue + b.packageValue + b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - INSERT INTO tmp.ticketComponent (warehouseFk, itemFk, componentFk, cost) - SELECT - tcc.warehouseFk, - tcc.itemFk, - vMarginComponent, - tcc.rate3 - b.buyingValue - b.freightValue - b.packageValue - b.comissionValue - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentBase; - CREATE TEMPORARY TABLE tmp.ticketComponentBase ENGINE = MEMORY - SELECT tc.itemFk, ROUND(SUM(tc.cost), 4) AS base, tc.warehouseFk - FROM tmp.ticketComponent tc - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tc.itemFk AND tcc.warehouseFk = tc.warehouseFk - GROUP BY tc.itemFk, warehouseFk; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vRecoveryComponent, ROUND(tcb.base * LEAST(cr.priceIncreasing, 0.25), 3) - FROM tmp.ticketComponentBase tcb - JOIN claimRatio cr ON cr.clientFk = vClientFk - WHERE cr.priceIncreasing > 0.009; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, tcb.itemFk, vManaAutoComponent, ROUND(base * (0.01 + wm.pricesModifierRate), 3) as manaAuto - FROM tmp.ticketComponentBase tcb - JOIN `client` c on c.id = vClientFk - JOIN workerMana wm ON c.salesPersonFk = wm.workerFk - WHERE wm.isPricesModifierActivated - HAVING manaAuto <> 0; - - INSERT INTO tmp.ticketComponent - SELECT tcb.warehouseFk, - tcb.itemFk, - c.id, - GREATEST(IFNULL(ROUND(tcb.base * c.tax, 4), 0), tcc.minPrice - tcc.rate3) - FROM tmp.ticketComponentBase tcb - JOIN component c - JOIN tmp.ticketComponentCalculate tcc ON tcc.itemFk = tcb.itemFk AND tcc.warehouseFk = tcb.warehouseFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE c.id = vDiscountLastItemComponent AND c.tax <> 0 AND tcc.minPrice < tcc.rate3 AND sp.value IS NULL; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, tcc.itemFk, vSellByPacketComponent, tcc.rate2 - tcc.rate3 - FROM tmp.ticketComponentCalculate tcc - JOIN buy b ON b.id = tcc.buyFk - LEFT JOIN specialPrice sp ON sp.clientFk = vClientFk AND sp.itemFk = tcc.itemFk - WHERE sp.value IS NULL; - - DROP TEMPORARY TABLE IF EXISTS tmp.zone; - CREATE TEMPORARY TABLE IF NOT EXISTS tmp.zone (INDEX (id)) - ENGINE = MEMORY - SELECT vZoneFk id; - - CALL zone_getOptionsForShipment(vShipped, TRUE); - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFK, - tcc.itemFk, - vDeliveryComponent, - vGeneralInflationCoefficient - * ROUND(( - i.compression - * ic.cm3 - * IF(am.deliveryMethodFk = 1, (GREATEST(i.density, vMinimumDensityWeight) / vMinimumDensityWeight), 1) - * IFNULL((zo.price - zo.bonus) - * 1/*amz.inflation*/ , 50)) / vBoxVolume, 4 - ) cost - FROM tmp.ticketComponentCalculate tcc - JOIN item i ON i.id = tcc.itemFk - JOIN tmp.zoneOption zo ON zo.zoneFk = vZoneFk - JOIN zone z ON z.id = vZoneFk - JOIN agencyMode am ON am.id = z.agencyModeFk - LEFT JOIN itemCost ic ON ic.warehouseFk = tcc.warehouseFk - AND ic.itemFk = tcc.itemFk - HAVING cost <> 0; - - DROP TEMPORARY TABLE tmp.zoneOption; - - IF (SELECT COUNT(*) FROM vn.addressForPackaging WHERE addressFk = vAddressFk) THEN - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, b.itemFk, vExtraBaggedComponent, ap.packagingValue cost - FROM tmp.ticketComponentCalculate tcc - JOIN vn.addressForPackaging ap - WHERE ap.addressFk = vAddressFk; - END IF; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentCopy; - CREATE TEMPORARY TABLE tmp.ticketComponentCopy ENGINE = MEMORY - SELECT * FROM tmp.ticketComponent; - - INSERT INTO tmp.ticketComponent - SELECT tcc.warehouseFk, - tcc.itemFk, - vSpecialPriceComponent, - sp.value - SUM(tcc.cost) sumCost - FROM tmp.ticketComponentCopy tcc - JOIN component c ON c.id = tcc.componentFk - JOIN specialPrice sp ON sp.clientFk = vClientFK AND sp.itemFk = tcc.itemFk - WHERE c.classRate IS NULL - GROUP BY tcc.itemFk, tcc.warehouseFk - HAVING ABS(sumCost) > 0.001; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentSum; - CREATE TEMPORARY TABLE tmp.ticketComponentSum - (INDEX (itemFk, warehouseFk)) - ENGINE = MEMORY - SELECT SUM(cost) sumCost, tc.itemFk, tc.warehouseFk, c.classRate - FROM tmp.ticketComponent tc - JOIN component c ON c.id = tc.componentFk - GROUP BY tc.itemFk, tc.warehouseFk, c.classRate; - - DROP TEMPORARY TABLE IF EXISTS tmp.ticketComponentRate; - CREATE TEMPORARY TABLE tmp.ticketComponentRate ENGINE = MEMORY - SELECT tcc.warehouseFk, - tcc.itemFk, - 1 rate, - IF(tcc.groupingMode = 1, tcc.`grouping`, 1) `grouping`, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) price, - CAST(SUM(tcs.sumCost) AS DECIMAL(10,2)) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 1) = 1 - AND tcc.groupingMode < 2 AND (tcc.packing > tcc.`grouping` or tcc.groupingMode = 0) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 2 rate, - tcc.packing `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE tcc.available IS NULL OR (IFNULL(tcs.classRate, 2) = 2 - AND tcc.packing > 0 AND tcc.available >= tcc.packing) - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentRate (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT - tcc.warehouseFk, - tcc.itemFk, - 3 rate, - tcc.available `grouping`, - SUM(tcs.sumCost) price, - SUM(tcs.sumCost) / weightGrouping priceKg - FROM tmp.ticketComponentCalculate tcc - JOIN tmp.ticketComponentSum tcs ON tcs.itemFk = tcc.itemFk - AND tcs.warehouseFk = tcc.warehouseFk - WHERE IFNULL(tcs.classRate, 3) = 3 - GROUP BY tcs.warehouseFk, tcs.itemFk; - - INSERT INTO tmp.ticketComponentPrice (warehouseFk, itemFk, rate, `grouping`, price, priceKg) - SELECT * FROM ( - SELECT * FROM tmp.ticketComponentRate ORDER BY price - ) t - GROUP BY itemFk, warehouseFk, `grouping`; - - DROP TEMPORARY TABLE - tmp.ticketComponentCalculate, - tmp.ticketComponentSum, - tmp.ticketComponentBase, - tmp.ticketComponentRate, - tmp.ticketComponentCopy; - END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -38314,6 +41861,7 @@ BEGIN DECLARE v18Month DATE; DECLARE v26Month DATE; DECLARE v3Month DATE; + DECLARE vTrashId varchar(15); SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE()); SET vOneYearAgo = TIMESTAMPADD(YEAR,-1,CURDATE()); @@ -38379,6 +41927,47 @@ BEGIN FROM vn.expeditionTruck WHERE ETD < v3Month; + -- borrar travels sin entradas + DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete; + CREATE TEMPORARY TABLE tmp.thermographToDelete + SELECT th.id,th.dmsFk + FROM vn.travel t + LEFT JOIN vn.entry e ON e.travelFk = t.id + JOIN vn.travelThermograph th ON th.travelFk = t.id + WHERE t.shipped < TIMESTAMPADD(MONTH, -3, CURDATE()) AND e.travelFk IS NULL; + + SELECT dt.id into vTrashId + FROM vn.dmsType dt + WHERE dt.code = 'trash'; + + UPDATE tmp.thermographToDelete th + JOIN vn.dms d ON d.id = th.dmsFk + SET d.dmsTypeFk = vTrashId; + + DELETE th + FROM tmp.thermographToDelete tmp + JOIN vn.travelThermograph th ON th.id = tmp.id; + + DELETE t + FROM vn.travel t + LEFT JOIN vn.entry e ON e.travelFk = t.id + WHERE t.shipped < TIMESTAMPADD(MONTH, -3, CURDATE()) AND e.travelFk IS NULL; + + -- borrar entradas sin compras + DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; + CREATE TEMPORARY TABLE tmp.entryToDelete + SELECT e.* + FROM vn.entry e + LEFT JOIN vn.buy b ON b.entryFk = e.id + WHERE e.dated < TIMESTAMPADD(MONTH, -3, CURDATE()) AND b.entryFK IS NULL; + + DELETE e + FROM vn.entry e + JOIN tmp.entryToDelete tmp ON tmp.id = e.id; + + DROP TEMPORARY TABLE IF EXISTS tmp.thermographToDelete; + DROP TEMPORARY TABLE IF EXISTS tmp.entryToDelete; + CALL shelving_clean; CALL ticketPackagingRecovery; END ;; @@ -39396,6 +42985,78 @@ BEGIN ON DUPLICATE KEY UPDATE amount = amount + VALUES(amount); 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 `client_RandomList` */; +/*!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=`z-developer`@`%` PROCEDURE `client_RandomList`(vNumber INT) +BEGIN + + DECLARE i INT DEFAULT 0; + DECLARE c INT DEFAULT 0; + DECLARE maxClientFk INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.client; + + CREATE TEMPORARY TABLE tmp.`client` + (id INT AUTO_INCREMENT, + clientFk INT, + isSelected TINYINT(1) NOT NULL DEFAULT 0, + PRIMARY KEY(id), + UNIQUE KEY clientFk (clientFk)) + ENGINE = MEMORY; + + INSERT INTO tmp.client(clientFk) + SELECT DISTINCT clientFk + FROM vn.invoiceOut + WHERE issued > TIMESTAMPADD(MONTH, -2, CURDATE()); + + SELECT max(id) INTO maxClientFk + FROM tmp.client; + + + WHILE i < vNumber DO + + SET i = i + 1; + + WHILE c = 0 DO + + SELECT id INTO c + FROM tmp.client + WHERE id = floor(RAND() * maxClientFk) + 1 + AND isSelected = FALSE + LIMIT 1; + + END WHILE; + + -- SELECT i, maxClientFk, c; + + UPDATE tmp.client + SET isSelected = TRUE + WHERE id = c; + + SET c = 0; + + END WHILE; + + SELECT c.id, c.name FROM tmp.client tc + JOIN vn.client c ON c.id = tc.clientFk + WHERE isSelected + ORDER BY clientFk; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -39545,6 +43206,44 @@ 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 `cmr_new` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`z-developer`@`%` PROCEDURE `cmr_new`(vTicketFk INT) +BEGIN + + IF vTicketFk THEN + + INSERT INTO vn.cmr(ticketFk, companyFk, addressFromFk, addressToFk, agencyFk) + SELECT vTicketFk, t.companyFk, a.id, t.addressFk, am.agencyFk + FROM vn.ticket t + JOIN vn.agencyMode am ON am.id = t.agencyModeFk + JOIN vn.company cm ON cm.id = t.companyFk + JOIN vn.client c ON c.id = cm.clientFk + JOIN vn.address a ON a.clientFk = c.id AND a.isDefaultAddress + WHERE t.id = vTicketFk; + + ELSE + + INSERT INTO vn.cmr(created) VALUES(NOW()); + + END IF; + + SELECT LAST_INSERT_ID(); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; /*!50003 DROP PROCEDURE IF EXISTS `collectionPlacement_get` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -39958,7 +43657,11 @@ BEGIN o.code AS origin, t.clientFk, s.originalQuantity, - TRIM(CONCAT(LPAD(i.longName,30,' '), ' ',RPAD(IFNULL(i.size,''),5,' '))) as line1, + TRIM(CONCAT( + LPAD(s.concept,30,' '), ' ', + RPAD(IFNULL(i.size,''),5,' ') + ) + ) as line1, TRIM(CONCAT(LPAD(IFNULL(ip.productor,''),30,' '), ' ',LPAD(IFNULL(o.code,''),4,' '))) as line2, TRIM(CONCAT(ic.color, IF(MAX(IF(st.semaphore <=> 1, TRUE, FALSE)) AND t.id != t.showTicketFk, CONCAT(' [ TICKET ',t.id,' ] '),''), IFNULL(LPAD(st.parkingCode,40,' '),''))) as line3, s.isAdded, @@ -39987,7 +43690,7 @@ BEGIN AND s.semaphore = 1 GROUP BY st.saleFk) st ON st.saleFk = s.id GROUP BY s.id - HAVING quantity > 0 OR workerFk != vn.getUser() + /*HAVING quantity > 0 OR workerFk != vn.getUser()*/ ; @@ -40776,7 +44479,7 @@ proc:BEGIN END IF; - IF /*vSectorFk = 18*/ FALSE THEN + IF /*vSectorFk = 37*/ FALSE THEN CALL vn.collectionTrain_new(9,3); @@ -40838,16 +44541,354 @@ proc:BEGIN SELECT s2.id, pb.Id_Ticket, vn.getUser() FROM tmp.production_buffer pb JOIN vn.agency a ON a.id = pb.agency_id + JOIN vn.warehouse w ON w.id = pb.warehouse_id JOIN vn.state s ON s.id = pb.state JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' LEFT JOIN vn.route r ON r.id = pb.Id_Ruta WHERE pb.Fecha = CURDATE() AND NOT pb.problems AND a.name != 'REC_SILLA' - AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE) + -- AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND (r.id IS NOT NULL OR a.isOwn = FALSE OR a.name = 'REC_ALGEMESI') AND s.isPrintable AND (pb.m3 > 0.05 OR s.isOK) - ORDER BY (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , + ORDER BY IF(pb.ubicacion IS NOT NULL, 1, 2), + (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , + s.order DESC, + Hora, + minuto, + IFNULL(r.priority,99999), + IFNULL(r.id,999999), + pb.m3 DESC + LIMIT vMaxTicketPrinted; + + END IF; + + -- SELECT vMaxTicketPrinted; + -- Se seleccionan los primeros tickets, asignando colección para dejarlos bloqueados a otros sacadores. + + INSERT IGNORE INTO vn.ticketCollection(ticketFk, collectionFk) + SELECT pb.Id_Ticket, + vCollectionFk + FROM tmp.production_buffer pb + JOIN vn.ticketStateToday tst ON tst.ticket = pb.Id_Ticket + JOIN vn.state s ON s.id = tst.state + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + WHERE pb.collectionFk IS NULL + AND ( + (s.isPreparable AND NOT myUserIsSalesPersonRole AND pb.Agencia != 'REC_SILLA') + OR + (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) + ) + ORDER BY (s.code = 'PICKER_DESIGNED' AND pb.CodigoTrabajador = vWorkerCode) DESC, + pb.Hora, + pb.Minuto, + IF(IFNULL(r.priority,0) = 0, 999, r.priority), + IFNULL(r.id,99999), + pb.m3 DESC + LIMIT vMaxTickets; + + + -- Creamos una tabla temporal con los datos que necesitamos para depurar la colección + DROP TEMPORARY TABLE IF EXISTS tmp.ticket; + CREATE TEMPORARY TABLE tmp.ticket + SELECT pb.Id_Ticket ticketFk, + pb.lines, + pb.m3 * 1000 liters, + 0 as height, + 0 as shelve + FROM tmp.production_buffer pb + JOIN vn.ticketCollection tc ON tc.ticketFk = pb.Id_Ticket + WHERE tc.collectionFk = vCollectionFk; + + SELECT ticketFk + INTO vFirstTicketFk + FROM tmp.ticket + LIMIT 1; + + IF (SELECT pb.Agencia FROM tmp.production_buffer pb WHERE Id_Ticket = vFirstTicketFk) = 'REC_SILLA' THEN + + DELETE FROM tmp.ticket WHERE ticketFk != vFirstTicketFk; + + UPDATE tmp.ticket SET shelve = 1; + -- Como sólo hay un ticket, se le asigna el nivel 1 y acabamos + + ELSE + + -- Eliminamos los de recogida, puesto que el primero sabemos que no es de rec_silla + DELETE t.* + FROM tmp.ticket t + JOIN tmp.production_buffer pb ON pb.Id_Ticket = t.ticketFk + WHERE pb.Agencia = 'REC_SILLA'; + + -- Establece altura máxima por pedido, porque las plantas no se pueden recostar. + UPDATE tmp.ticket t + JOIN + ( SELECT MAX(i.size) maxHeigth, + tc.ticketFk + FROM vn.ticketCollection tc + JOIN vn.sale s ON s.ticketFk = tc.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN vn.itemCategory ic ON ic.id = it.categoryFk + WHERE ic.isReclining = FALSE + AND tc.collectionFk = vCollectionFk + GROUP BY tc.ticketFk) sub ON sub.ticketFk = t.ticketFk + SET t.height = sub.maxHeigth; + + -- Vamos a generar una tabla con todas las posibilidades de asignacion de pedido + DROP TEMPORARY TABLE IF EXISTS tmp.ticketShelve; + CREATE TEMPORARY TABLE tmp.ticketShelve + SELECT ticketFk, shelve, linesDif, LitersDif, heightDif + FROM ( + SELECT t.ticketFk, + cv.`level` shelve, + CAST(cv.lines AS SIGNED) - t.lines as linesDif, + CAST(cv.liters AS SIGNED) - t.liters as litersDif, + CAST(cv.height AS SIGNED) - t.height as heightDif + FROM vn.collectionVolumetry cv + JOIN tmp.ticket t + ORDER BY (t.ticketFk = vFirstTicketFk) DESC, linesDif + ) sub + WHERE linesDif >= 0 + AND litersDif >= 0 + AND heightDif >= 0 + ORDER BY linesDif; + + -- Asignamos la primera balda util al primer pedido + SELECT IFNULL(shelve,0) INTO vShelve + FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + ORDER BY heightDif, litersDif, linesDif + LIMIT 1; + + IF vShelve THEN + + UPDATE tmp.ticket + SET shelve = vShelve + WHERE ticketFk = vFirstTicketFk; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vFirstTicketFk + OR shelve = vShelve; + + WHILE (SELECT COUNT(*) FROM tmp.ticketShelve) DO + + SELECT ticketFk, shelve + INTO vTicket, vShelve + FROM tmp.ticketShelve + LIMIT 1; + + UPDATE tmp.ticket + SET shelve = vShelve + WHERE ticketFk = vTicket; + + DELETE FROM tmp.ticketShelve + WHERE ticketFk = vTicket + OR shelve = vShelve; + + END WHILE; + + ELSE + + UPDATE tmp.ticket + SET shelve = 1 + WHERE ticketFk = vFirstTicketFk; + + END IF; + + END IF; + + -- Eliminamos los que se han quedado sin balda + DELETE FROM tmp.ticket WHERE shelve = 0 ; + + -- Elimina los tickets bloqueados que no se van a preparar + DELETE tc.* + FROM vn.ticketCollection tc + LEFT JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + WHERE tc.collectionFk = vCollectionFk + AND t.ticketFk IS NULL; + + -- Actualiza el estado de la colección + UPDATE vn.collection c + JOIN vn.state st ON st.code = 'ON_PREPARATION' + SET c.stateFk = st.id + WHERE c.id = vCollectionFk; + + -- Asigna las bandejas + UPDATE vn.ticketCollection tc + JOIN tmp.ticket t ON t.ticketFk = tc.ticketFk + SET tc.level = t.shelve; + + -- Actualiza el estado de los tickets + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT vStateFk, ticketFk, account.myUserGetId() + FROM vn.ticketCollection tc + WHERE tc.collectionFk = vCollectionFk + UNION ALL + SELECT vStateFk, sw.id, account.myUserGetId() + FROM vn.stowaway sw + JOIN vn.ticketCollection tc ON tc.ticketFk = sw.shipFk + WHERE tc.collectionFk = vCollectionFk; + + -- Avisa los preparados previos que hay que bajar del altillo imprimiendo etiqueta + INSERT IGNORE INTO vn.ticketDown(ticketFk) + SELECT DISTINCT tc.ticketFk + FROM vn.ticketCollection tc + JOIN vncontrol.inter vi ON vi.Id_Ticket = tc.ticketFk + JOIN vn.state st ON st.id = vi.state_id + JOIN vn.ticket t ON t.id = tc.ticketFk + JOIN vn.warehouse w ON w.id = t.warehouseFk + WHERE tc.collectionFk = vCollectionFk + AND w.name = 'Silla FV' + AND st.code = 'PREVIOUS_PREPARATION'; + + IF (SELECT COUNT(*) FROM vn.ticketCollection WHERE collectionFk = vCollectionFk) THEN + + CALL vn.salesMerge_byCollection(vCollectionFk); + + SELECT vCollectionFk; + + ELSE + + DELETE FROM vn.collection WHERE id = vCollectionFk; + SELECT 0; + + END IF; + + 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 `collection_new_Basic` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `collection_new_Basic`(vSectorFk INT) +proc:BEGIN + + DECLARE vIsPreviousPrepared BOOLEAN; + DECLARE vCollectionFk INT; + DECLARE vWarehouseFk INT; + DECLARE vMaxTickets INT DEFAULT 4; + DECLARE vStateFk INT; + DECLARE vFirstTicketFk INT; + DECLARE vWorkerCode VARCHAR(3); + DECLARE vShelve INT; + DECLARE vTicket INT; + DECLARE myUserIsSalesPersonRole BOOLEAN; + DECLARE vPrintedTickets INT; + DECLARE vMaxTicketPrinted INT DEFAULT 10; + + -- Se comprueba si existe coleccion pendiente, en cuyo caso se devuelve esa colección + SELECT collectionFk INTO vCollectionFk + FROM + ( + SELECT tc.collectionFk, COUNT(*) as lineas, sum(IF(st.id,0,1)) as libres + FROM vn.collection c + JOIN vn.ticketCollection tc ON tc.collectionFk = c.id + JOIN vn.ticket t ON t.id = tc.ticketFk + JOIN vn.sale s ON s.ticketFk = t.id + LEFT JOIN vn.saleTracking st ON st.saleFk = s.id + WHERE c.workerFk = vn.getUser() + AND s.quantity + AND c.created > CURDATE() + GROUP BY c.id + HAVING libres = lineas) sub + LIMIT 1; + + IF vCollectionFk THEN + + SELECT vCollectionFk; + + LEAVE proc; + + END IF; + + IF /*vSectorFk = 37*/ FALSE THEN + + CALL vn.collectionTrain_new(9,3); + + ELSE + + -- Establecemos el almacén y si es un sector de preparación previa, así como el estado para los tickets que se vayan preparando + SELECT isPreviousPrepared, warehouseFk + INTO vIsPreviousPrepared, vWarehouseFk + FROM vn.sector + WHERE id = vSectorFk; + + IF vIsPreviousPrepared THEN + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'PREVIOUS_PREPARATION'; + ELSE + + SELECT id INTO vStateFk + FROM vn.state + WHERE `code` = 'ON_PREPARATION'; + + END IF; + + -- Averiguamos si es comercial el usuario + SELECT FALSE -- (r.name = 'salesPerson') + INTO myUserIsSalesPersonRole + FROM account.user u + JOIN account.role r ON r.id = u.role + WHERE u.id = vn.getUser(); + + -- Obtenemos el código del usuario + SELECT w.code + INTO vWorkerCode + FROM vn.worker w + WHERE w.id = account.myUserGetId(); + + -- Se obtiene nº de colección y el buffer con los pedidos preparables + INSERT INTO vn.collection + SET workerFk = account.myUserGetId(); + + SELECT LAST_INSERT_ID() INTO vCollectionFk; + + CALL vn2008.production_control_source(vWarehouseFk, 0); + + SELECT COUNT(*) INTO vPrintedTickets + FROM tmp.production_buffer pb + JOIN vn.state s ON s.id = pb.state + WHERE pb.Fecha = CURDATE() + AND s.isPreparable; + + SET vMaxTicketPrinted = vMaxTicketPrinted - vPrintedTickets; + + -- AutoPRINT + + IF vMaxTicketPrinted > 0 THEN + + INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador) + SELECT s2.id, pb.Id_Ticket, vn.getUser() + FROM tmp.production_buffer pb + JOIN vn.agency a ON a.id = pb.agency_id + JOIN vn.warehouse w ON w.id = pb.warehouse_id + JOIN vn.state s ON s.id = pb.state + JOIN vn.state s2 ON s2.code = 'PRINTED_AUTO' + LEFT JOIN vn.route r ON r.id = pb.Id_Ruta + WHERE pb.Fecha = CURDATE() + AND NOT pb.problems + AND a.name != 'REC_SILLA' + AND (pb.ubicacion IS NOT NULL OR a.isOwn = FALSE ) + AND s.isPrintable + AND (pb.m3 > 0.05 OR s.isOK) + ORDER BY + (Hora - 1) * 60 + minuto > hour(now()) * 60 + minute(now()) , s.order DESC, Hora, minuto, @@ -43702,6 +47743,120 @@ BEGIN AND t.warehouseFk = vWarehouseFk AND s.itemFk = vItemFk; +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 `fv_pca` */; +/*!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 `fv_pca`() +BEGIN + +DECLARE done INT DEFAULT FALSE; + +DECLARE vTicketFk INT; +DECLARE vSaleFk INT; +DECLARE vClonTicket INT DEFAULT 0; + +DECLARE cur1 CURSOR FOR +SELECT s.ticketFk, s.id + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + WHERE t.shipped BETWEEN '2020-10-18' AND '2020-10-31' + AND it.code IN ('ANT','ANS','ORQ','TRO') + and t.warehouseFk = 1; + +DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + +OPEN cur1; + +FETCH cur1 INTO vTicketFk, vSaleFk; + + WHILE done = 0 DO + + SELECT t.id INTO vClonTicket + FROM vn.ticket t + JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) + WHERE t.warehouseFk = 44 + LIMIT 1; + + SELECT vTicketFk, vClonTicket; + + IF vClonTicket = 0 THEN + + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk + ) + SELECT + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + 44, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk + + FROM ticket + WHERE id = vTicketFk; + + SET vClonTicket = LAST_INSERT_ID(); + + SELECT 'lstID', vClonTicket; + /* + INSERT INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vTicketFk, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN ticket t ON t.addressFk = ao.addressFk + WHERE t.id = vClonTicket; +*/ + INSERT INTO ticketLog + SET originFk = vTicketFk, userFk = account.myUserGetId(), `action` = 'insert', + description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); + + END IF; + + UPDATE vn.sale + SET ticketFk = vClonTicket + WHERE id = vSaleFk; + + SET vClonTicket = 0; + + SET done = 0; + FETCH cur1 INTO vTicketFk, vSaleFk; + + END WHILE; + + CLOSE cur1; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -43866,7 +48021,7 @@ BEGIN UPDATE vn2008.intrastat_data id JOIN ( SELECT i.intrastatFk, - sum(r.cm3 * b.quantity) * IF(i.density, i.density, it.density) / 1000000 as neto + LEAST(sum(b.quantity) * IFNULL(it.gramsMax,100000) / 1000 ,sum(r.cm3 * b.quantity) * IF(i.density, i.density, it.density) / 1000000) as neto FROM vn.entry e JOIN vn.travel tr ON tr.id = e.travelFk JOIN vn.buy b ON b.entryFk = e.id @@ -43877,6 +48032,7 @@ UPDATE vn2008.intrastat_data id GROUP BY i.intrastatFk) sub ON sub.intrastatFk = id.intrastat_id SET id.neto = ROUND(sub.neto,1) WHERE id.recibida_id = vInvoiceInFk; + END ;; DELIMITER ; @@ -44855,7 +49011,7 @@ BEGIN n.bookEntried FECHA, tc.code SUBCTA, s.supplierAccount CONTRA, - SUM(ROUND(tc.rate/100 * it.taxableBase/* + 0.0001*/, 2)) EURODEBE, + SUM(ROUND(tc.rate * it.taxableBase / 100 /* + 0.0001*/, 2)) EURODEBE, SUM(it.taxableBase) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -44931,7 +49087,7 @@ BEGIN n.bookEntried FECHA, tcLink.code SUBCTA, s.supplierAccount CONTRA, - SUM(ROUND(tcLink.rate/100*it.taxableBase + 0.0001,2)) EUROHABER, + SUM(ROUND(tcLink.rate * it.taxableBase / 100,2)) EUROHABER, ROUND(SUM(it.taxableBase),2) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -45057,10 +49213,10 @@ BEGIN ) SELECT vBookNumber ASIEN, n.bookEntried FECHA, - IF(e.isWithheld,LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk),iit.expenceFk) SUBCTA, + IF(e.isWithheld , LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk),iit.expenceFk) SUBCTA, s.supplierAccount CONTRA, - IF(e.isWithheld,NULL,ABS(ROUND(SUM(iit.taxableBase),2))) EURODEBE, - IF(e.isWithheld,ABS(ROUND(SUM(iit.taxableBase),2)),NULL) EUROHABER, + IF(e.isWithheld AND iit.taxableBase < 0, NULL, ROUND(SUM(iit.taxableBase),2)) EURODEBE, + IF(e.isWithheld AND iit.taxableBase < 0,ROUND(SUM(-iit.taxableBase),2),NULL) EUROHABER, n.conceptWithSupplier CONCEPTO, vRate, IF(e.isWithheld,NULL,ABS(ROUND(SUM(iit.foreignValue),2))) DEBEME, @@ -45075,7 +49231,6 @@ BEGIN WHERE iit.expenceFk != 5660000002 GROUP BY iit.expenceFk; - -- -------------------------------------------------------------------- -- ------- Lineas de IVA --------------- -- -------------------------------------------------------------------- @@ -45113,7 +49268,7 @@ BEGIN n.bookEntried FECHA, tc.code SUBCTA, s.supplierAccount CONTRA, - ROUND(tc.rate/100 * SUM(it.taxableBase) + 0.0001, 2) EURODEBE, + SUM(ROUND(tc.rate/100 * it.taxableBase/* + 0.0001*/, 2)) EURODEBE, SUM(it.taxableBase) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -45152,7 +49307,7 @@ BEGIN ) eWithheld ON TRUE WHERE tc.type != '-' AND tc.isActive - GROUP BY tc.rate; + GROUP BY tc.rate, e.id; -- Linea iva inversor sujeto pasivo @@ -45189,7 +49344,7 @@ BEGIN n.bookEntried FECHA, tcLink.code SUBCTA, s.supplierAccount CONTRA, - ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER, + SUM(ROUND(tcLink.rate/100*it.taxableBase + 0.0001,2)) EUROHABER, ROUND(SUM(it.taxableBase),2) BASEEURO, GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO, vSerialNumber FACTURA, @@ -47060,15 +51215,14 @@ BEGIN alt.reserva, sale.venta, IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as compra, - IFNULL(v.amount,0) - reserva + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as saldo + IFNULL(v.amount,0) + IFNULL(sale.venta,0) + IFNULL(buy.compra,0) + IFNULL(mov.traslado,0) as saldo FROM vn.item i JOIN ( SELECT ish.itemFk, CAST(SUM(ish.visible) AS DECIMAL(10,0)) AS reserva FROM vn.itemShelving ish - LEFT JOIN vn.shelving sh ON sh.code = ish.shelvingFk - LEFT JOIN vn.parking p ON p.id = sh.parkingFk - WHERE (ish.shelvingFk = 'FUE' - OR p.code = 'FUE-PI') + JOIN vn.shelving sh ON sh.code = ish.shelvingFk + JOIN vn.parking p ON p.id = sh.parkingFk + WHERE p.sectorFk = 37 GROUP BY ish.itemFk ) alt ON alt.itemFk = i.id LEFT JOIN cache.stock v ON i.id = v.item_id AND v.warehouse_id = 1 @@ -47690,9 +51844,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -47707,19 +51861,41 @@ BEGIN */ DECLARE vTicketFk INT; DECLARE vItemFk INT; + DECLARE vWarehouseFk SMALLINT; + DECLARE vDate DATE; + DECLARE vGrouping INT; + DECLARE vBox INT; + DECLARE vPacking INT; + DECLARE vRoundQuantity INT; - SELECT ticketFk, LEAST(quantity, vQuantity), itemFk - INTO vTicketFk, vQuantity, vItemFk - FROM vn.sale - WHERE id = vSaleFk; + SELECT s.ticketFk, LEAST(s.quantity, vQuantity), s.itemFk,t.shipped,t.warehouseFk + INTO vTicketFk, vQuantity, vItemFk,vDate,vWarehouseFk + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + WHERE s.id = vSaleFk; UPDATE vn.sale - SET quantity = quantity - vQuantity + SET quantity = quantity - vQuantity WHERE id = vSaleFk; - INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept) - SELECT vTicketFk, vMateFk, vQuantity, CONCAT('+ ',i.longName) - FROM vn.item i + CALL vn.buyUltimate(vWarehouseFk, vDate); + + SELECT `grouping`, groupingMode, packing + INTO vGrouping,vBox,vPacking + FROM buy b + JOIN tmp.buyUltimate tmp ON b.id = tmp.buyFk + WHERE tmp.itemFk = vMateFk AND tmp.WarehouseFk = vWarehouseFk; + + IF vBox = 2 AND vPacking > 0 THEN + SET vRoundQuantity = vPacking; + END IF; + IF vBox = 1 AND vGrouping > 0 THEN + SET vRoundQuantity = vGrouping; + END IF; + + INSERT INTO vn.sale(ticketFk, itemFk, quantity, concept) + SELECT vTicketFk, vMateFk, CEIL(vQuantity / vRoundQuantity) * vRoundQuantity, CONCAT('+ ',i.longName) + FROM vn.item i WHERE id = vMateFk; SELECT LAST_INSERT_ID() INTO vSaleFk; @@ -48474,7 +52650,12 @@ BEGIN FROM vn.worker w JOIN vn.sector s ON s.code = w.code WHERE s.id = vSectorFk; - + + SELECT s.id INTO vSectorFk + FROM vn.sector s + WHERE s.warehouseFk = vWarehouseFk + AND s.isMain; + /* IF vWarehouseFk = 1 THEN SET vSectorFk = 9; @@ -48484,7 +52665,7 @@ BEGIN SET vSectorFk = 6; END IF; - + */ SELECT COUNT(*) INTO hasFatherSector FROM vn.sector WHERE sonFk = vSectorFk; @@ -48499,10 +52680,11 @@ BEGIN DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; IF hasFatherSector THEN - + CREATE TEMPORARY TABLE tmp.itemShelvingRadar (PRIMARY KEY (itemFk)) ENGINE = MEMORY + SELECT * FROM ( SELECT iss.itemFk, i.longName, i.size, @@ -48541,7 +52723,218 @@ BEGIN LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk WHERE v.calc_id = vCalcVisibleFk AND iss.itemFk IS NULL - AND it.isInventory; + AND it.isInventory + ) sub GROUP BY itemFk; + + SELECT ishr.*, + CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, + CAST(downstairs - IFNULL(notPickedYed,0) AS DECIMAL(10,0)) as pendiente + FROM tmp.itemShelvingRadar ishr + JOIN vn.item i ON i.id = ishr.itemFk + LEFT JOIN (SELECT s.itemFk, sum(s.quantity) as notPickedYed + FROM vn.ticket t + JOIN vn.ticketStateToday tst ON tst.ticket = t.id + JOIN vn.sale s ON s.ticketFk = t.id + WHERE t.warehouseFk = vWarehouseFk + AND tst.alertLevel = 0 + GROUP BY s.itemFk + ) sub ON sub.itemFk = ishr.itemFk + ORDER BY i.typeFk, i.longName + ; + + + ELSE + + CREATE TEMPORARY TABLE tmp.itemShelvingRadar + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT iss.itemFk, + 0 `hour`, + 0 `minute`, + IFNULL(ip.`code`,'--') itemPlacementCode, + i.longName, + i.size, + i.subName producer, + i.upToDown, + IFNULL(a.available,0) available, + IFNULL(v.visible - iss.visible,0) dayEndVisible, + IFNULL(v.visible - iss.visible,0) firstNegative, + IFNULL(v.visible - iss.visible,0) itemPlacementVisible, + IFNULL(i.minimum * b.packing,0) itemPlacementSize, + ips.onTheWay, + iss.visible itemShelvingStock, + IFNULL(v.visible,0) visible, + b.isPickedOff, + iss.sectorFk + FROM vn.itemShelvingStock iss + JOIN vn.item i on i.id = iss.itemFk + LEFT JOIN vn.itemPlacement ip ON ip.itemFk = iss.itemFk AND ip.warehouseFk = vWarehouseFk + LEFT JOIN cache.last_buy lb ON lb.item_id = iss.itemFk AND lb.warehouse_id = vWarehouseFk + LEFT JOIN vn.buy b ON b.id = lb.buy_id + LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + LEFT JOIN (SELECT itemFk, sum(saldo) as onTheWay + FROM vn.itemPlacementSupplyList + WHERE saldo > 0 + GROUP BY itemFk + ) ips ON ips.itemFk = i.id + WHERE IFNULL(iss.sectorFk,0) IN (0, vSectorFk) + OR iss.sectorFk = vSectorFk; + /* + UPDATE tmp.itemShelvingRadar isr + JOIN vn.itemShelvingStock iss ON iss.itemFk = isr.itemFk + SET isr.dayEndVisible = isr.dayEndVisible + iss.visible, + isr.firstNegative = isr.firstNegative + iss.visible, + isr.itemPlacementVisible = isr.itemPlacementVisible + iss.visible + WHERE iss.sectorFk = vSonSectorFk; + */ + DROP TEMPORARY TABLE IF EXISTS tmp.itemOutTime; + CREATE TEMPORARY TABLE tmp.itemOutTime + SELECT *,SUM(amount) quantity + FROM + (SELECT item_id itemFk, + amount, + IF(HOUR(t.shipped), HOUR(t.shipped), HOUR(z.`hour`)) as hours, + IF(MINUTE(t.shipped), MINUTE(t.shipped), MINUTE(z.`hour`)) as minutes + FROM vn2008.item_out io + JOIN tmp.itemShelvingRadar isr ON isr.itemFk = io.item_id + JOIN vn.ticket t on t.id= io.ticketFk + JOIN vn.ticketState ts on ts.ticketFk = io.ticketFk + JOIN vn.state s ON s.id = ts.stateFk + LEFT JOIN vn.zone z ON z.id = t.zoneFk + LEFT JOIN (SELECT DISTINCT saleFk + FROM vn.saleTracking st + WHERE st.created > CURDATE() + AND st.isChecked + ) stPrevious ON `stPrevious`.`saleFk` = io.saleFk + WHERE t.warehouseFk = vWarehouseFk + AND s.isPicked = 0 + AND NOT io.Reservado + AND stPrevious.saleFk IS NULL + AND io.dat >= CURDATE() + AND io.dat < CURDATE()+1 + ) sub + GROUP BY itemFk, hours, minutes; + + INSERT INTO tmp.itemShelvingRadar (itemFk) + SELECT itemFk FROM tmp.itemOutTime + ON DUPLICATE KEY UPDATE dayEndVisible = dayEndVisible + quantity, + firstNegative = if (firstNegative < 0, firstNegative, firstNegative + quantity), + `hour` = ifnull(if (firstNegative > 0 , `hour`, hours),0), + `minute` = ifnull(if (firstNegative > 0, `minute`, minutes),0); +/* + UPDATE tmp.itemShelvingRadar + SET itemPlacementVisible = 0, + dayEndVisible = 0, + firstNegative = 0 + WHERE itemPlacementVisible = - itemShelvingStock; + */ + SELECT * FROM tmp.itemShelvingRadar; + + END IF; + + DROP TEMPORARY TABLE tmp.itemShelvingRadar; + +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 `itemShelvingRadar_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 `itemShelvingRadar_beta`(vSectorFk INT) +BEGIN + + DECLARE vCalcVisibleFk INT; + DECLARE vCalcAvailableFk INT; + DECLARE hasFatherSector BOOLEAN; + DECLARE vBuyerFk INT DEFAULT 0; + DECLARE vWarehouseFk INT DEFAULT 0; + DECLARE vSonSectorFk INT; + + SELECT w.id, s.warehouseFk INTO vBuyerFk, vWarehouseFk + FROM vn.worker w + JOIN vn.sector s ON s.code = w.code + WHERE s.id = vSectorFk; + + IF vWarehouseFk = 1 THEN + + SET vSectorFk = 9; + + ELSEIF vWarehouseFk = 44 THEN + + SET vSectorFk = 6; + + END IF; + + SELECT COUNT(*) INTO hasFatherSector + FROM vn.sector + WHERE sonFk = vSectorFk; + + SELECT warehouseFk, sonFk INTO vWarehouseFk, vSonSectorFk + FROM vn.sector + WHERE id = vSectorFk; + + CALL cache.visible_refresh(vCalcVisibleFk, TRUE, vWarehouseFk); + CALL cache.available_refresh(vCalcAvailableFk, FALSE, vWarehouseFk, CURDATE()); + + DROP TEMPORARY TABLE IF EXISTS tmp.itemShelvingRadar; + + IF hasFatherSector THEN + + CREATE TEMPORARY TABLE tmp.itemShelvingRadar + (PRIMARY KEY (itemFk)) + ENGINE = MEMORY + SELECT * FROM ( + SELECT iss.itemFk, + i.longName, + i.size, + i.subName producer, + a.available, + SUM(IF(s.sonFk = vSectorFk, iss.visible, 0)) upstairs, + SUM(IF(iss.sectorFk = vSectorFk, iss.visible, 0)) downstairs, + IF(it.isPackaging, NULL, IFNULL(v.visible,0)) as visible, + vSectorFk as sectorFk + + FROM vn.itemShelvingStock iss + JOIN vn.sector s ON s.id = iss.sectorFk + JOIN vn.item i on i.id = iss.itemFk + JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) + LEFT JOIN cache.available a ON a.item_id = iss.itemFk AND a.calc_id = vCalcAvailableFk + LEFT JOIN cache.visible v ON v.item_id = iss.itemFk AND v.calc_id = vCalcVisibleFk + WHERE vSectorFk IN (iss.sectorFk, s.sonFk) + + GROUP BY iss.itemFk + + UNION ALL + + SELECT v.item_id, + i.longName, + i.size, + i.subName producer, + IFNULL(a.available,0) as available, + 0 upstairs, + 0 downstairs, + IF(it.isPackaging, NULL, v.visible) visible, + vSectorFk as sectorFk + FROM cache.visible v + JOIN vn.item i on i.id = v.item_id + JOIN vn.itemType it ON it.id = i.typeFk AND vBuyerFk IN (0,it.workerFk) + LEFT JOIN vn.itemShelvingStock iss ON iss.itemFk = v.item_id AND iss.warehouseFk = vWarehouseFk + LEFT JOIN cache.available a ON a.item_id = v.item_id AND a.calc_id = vCalcAvailableFk + WHERE v.calc_id = vCalcVisibleFk + AND iss.itemFk IS NULL + AND it.isInventory + ) sub GROUP BY itemFk; SELECT ishr.*, CAST(visible - upstairs - downstairs AS DECIMAL(10,0)) AS nicho, @@ -50349,7 +54742,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 `kk` */; +/*!50003 DROP PROCEDURE IF EXISTS `kk_` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; @@ -50359,129 +54752,111 @@ DELIMITER ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; -CREATE DEFINER=`z-sysadmin`@`%` PROCEDURE `kk`(IN vItemId INT, IN vWarehouse INT) +CREATE DEFINER=`z-developer`@`%` PROCEDURE `kk_`() BEGIN - DECLARE vDateInventory DATETIME; - DECLARE vCurdate DATE DEFAULT CURDATE(); - DECLARE vDayEnd DATETIME DEFAULT util.dayEnd(vCurdate); + + DECLARE i INT DEFAULT 1; + DECLARE vPasillos VARCHAR(4) DEFAULT 'ABCD'; + DECLARE vPasilloLetra VARCHAR(1); + DECLARE vPasillo INT DEFAULT 0; + DECLARE vEstanteria INT DEFAULT 0; + DECLARE vEstanteriaMax INT DEFAULT 54; - SELECT inventoried INTO vDateInventory FROM config; - SET @a = 0; - SET @currentLineFk = 0; + WHILE i < 100 DO - SELECT @shipped:= shipped, - alertLevel, - stateName, - origin, - reference, - clientFk, - name, - `in`, - `out`, - @a := @a + IFNULL(`in`,0) - IFNULL(`out`,0) as balance, - @currentLineFk := IF (@shipped < CURDATE() - OR (@shipped =CURDATE() AND isPicked), - lineFk,@currentLineFk) isPicked, - isTicket, - lineFk - FROM - ( SELECT tr.landed as shipped, - b.quantity as `in`, - NULL as `out`, - IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, - st.name AS stateName, - s.name as name, - e.ref as reference, - e.id as origin, - s.id as clientFk, - TRUE isPicked, - FALSE AS isTicket, - b.id lineFk, - NULL `order` - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.alertLevel = - CASE - WHEN tr.isReceived != FALSE THEN 3 - WHEN tr.isDelivered THEN 1 - ELSE 0 - END - JOIN state st ON st.code = al.code - WHERE tr.landed >= vDateInventory - AND vWarehouse = tr.warehouseInFk - AND b.itemFk = vItemId - AND e.isInventory = 0 - AND e.isRaid = 0 - UNION ALL - - SELECT tr.shipped, - NULL as `in`, - b.quantity as `out`, - IF(tr.isReceived != FALSE,3, IF(tr.isDelivered,1,0)) as alertLevel, - st.name AS stateName, - s.name as name, - e.ref as reference, - e.id as origin, - s.id as clientFk, - TRUE isPicked, - FALSE AS isTicket, - b.id, - NULL `order` - FROM buy b - JOIN entry e ON e.id = b.entryFk - JOIN travel tr ON tr.id = e.travelFk - JOIN warehouse w ON w.id = tr.warehouseOutFk - JOIN supplier s ON s.id = e.supplierFk - JOIN alertLevel al ON al.alertLevel = - CASE - WHEN tr.isReceived != FALSE THEN 3 - WHEN tr.isDelivered THEN 1 - ELSE 0 - END - JOIN state st ON st.code = al.code - WHERE tr.shipped >= vDateInventory - AND vWarehouse =tr.warehouseOutFk - AND s.id <> 4 - AND b.itemFk = vItemId - AND e.isInventory = 0 - AND w.isFeedStock = 0 - AND e.isRaid = 0 - UNION ALL - - SELECT DATE(t.shipped), - NULL as `in`, - s.quantity as `out`, - al.alertLevel as alertLevel, - st.name AS stateName, - t.nickname as name, - t.refFk as reference, - t.id as origin, - t.clientFk, - stk.id as isPicked, - TRUE as isTicket, - s.id, - st.`order` - FROM sale s - JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN ticketState ts ON ts.ticket = t.id - LEFT JOIN state st ON st.code = ts.code - JOIN client c ON c.id = t.clientFk - JOIN alertLevel al ON al.alertLevel = - CASE - WHEN t.shipped < curdate() THEN 3 - WHEN t.shipped > util.dayEnd(curdate()) THEN 0 - ELSE IFNULL(ts.alertLevel, 0) - END - LEFT JOIN state stPrep ON stPrep.`code` = 'PREPARED' - LEFT JOIN saleTracking stk ON stk.saleFk = s.id AND stk.stateFk = stPrep.id - WHERE t.shipped >= vDateInventory - AND s.itemFk = vItemId - AND vWarehouse =t.warehouseFk - ORDER BY shipped, isTicket, alertLevel DESC, `order` DESC, isPicked DESC, `in` DESC, `out` DESC - ) AS itemDiary; + INSERT INTO vn.parking(code, sectorFk, pickingOrder, `column`, `row`) + VALUES(CONCAT('A-',RIGHT(CONCAT('0',i),2)),37,i, 0, i); + + SET i = i + 1; + + END WHILE; + + SET i = 0; + + WHILE vPasillo < LENGTH(vPasillos) DO + + SET vPasillo = vPasillo + 1; + + SET vPasilloLetra = MID(vPasillos,vPasillo,1); + WHILE vEstanteria < vEstanteriaMax DO + + SET vEstanteria = vEstanteria + 1; + + WHILE i < 4 DO + + SET i = i + 1; + + INSERT INTO vn.parking(code, sectorFk) + VALUES(CONCAT(vPasilloLetra,'-',RIGHT(CONCAT('0',vEstanteria),2),'-',i),37); + + END WHILE; + + SET i = 0; + + END WHILE; + + SET vEstanteria = 0; + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ledger_doCompensation` */; +/*!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 `ledger_doCompensation`(vDated DATE, vCompensationAccount VARCHAR(10) , vBankFk VARCHAR(10), vConcept VARCHAR(255), vAmount DECIMAL(10,2), vCompanyFk INT, vOriginalAccount VARCHAR(10)) +BEGIN +/** + * Compensa un pago o un recibo insertando en contabilidad + * + * @param vDated fecha en la cual se anota + * @param vCompensationAccount cuenta contablo contra la que se contabiliza + * @param vBankFk banco de la compensacion + * @param vConcept descripcion + * @param vAmount cantidad que se compensa + * @param vCompany empresa + */ + + DECLARE vNewBookEntry INT; + DECLARE vClientCompensation INT; + DECLARE vSupplierCompensation INT; + DECLARE vPayMethodCompensation INT; + + CALL vn.ledger_next(vNewBookEntry); + + INSERT INTO XDiario (ASIEN, FECHA, SUBCTA, CONTRA, CONCEPTO, EURODEBE, EUROHABER, empresa_id) + VALUES (vNewBookEntry, vDated, vOriginalAccount, vCompensationAccount, vConcept, vAmount, 0, vCompanyFk), + (vNewBookEntry, vDated, vCompensationAccount, vOriginalAccount, vConcept, 0, vAmount, vCompanyFk); + + SELECT id INTO vClientCompensation FROM vn.`client` WHERE accountingAccount LIKE vCompensationAccount COLLATE utf8_general_ci; + SELECT id INTO vSupplierCompensation FROM vn.supplier WHERE `account` LIKE vCompensationAccount COLLATE utf8_general_ci; + + IF MID(vCompensationAccount, 1, 2) = MID(vOriginalAccount, 1, 2) THEN + SET vAmount = -vAmount; + END IF; + + IF vClientCompensation THEN + INSERT INTO receipt(invoiceFk, amountPaid, payed, bankFk, companyFk, clientFk, isConciliate) + VALUES (vConcept, vAmount, vDated, vBankFk, vCompanyFk, vClientCompensation, TRUE); + END IF; + + IF vSupplierCompensation THEN + SELECT id INTO vPayMethodCompensation FROM payMethod WHERE `code` = 'compensation'; + INSERT INTO vn2008.pago (fecha, dueDated, id_proveedor, importe, id_banco, pay_met_id, concepte, empresa_id, conciliado) + VALUES(vDated, vDated, vSupplierCompensation, vAmount, vBankFk, vPayMethodCompensation, vConcept, vCompanyFk, TRUE); + END IF; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -52114,6 +56489,87 @@ 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 `rankingTeamByQuarter` */; +/*!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 `rankingTeamByQuarter`(vYear INT, vQuarter INT) +BEGIN + + DECLARE vMinimumSalesByQuarter INT; + + SELECT minimumSalesByQuarter INTO vMinimumSalesByQuarter + FROM commissionConfig; + + DROP TEMPORARY TABLE IF EXISTS tmp.rankingTeam; + CREATE TEMPORARY TABLE tmp.rankingTeam + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + SELECT + (sub1.importe - sub2.importe) / IF ((sub1.importe - sub2.importe) > 0,sub3.countPeople,1) AS diferencia, + CONCAT(sub1.name, + '(', + sub1.peopleMinSale, + '/', + sub3.countPeople, + ')') AS teamPeople, + sub1.departmentFk AS departmentFk + FROM + (((SELECT + SUM(sub.importe) AS importe, + sub.name AS name, + sub.año AS año, + sub.departmentFk AS departmentFk, + COUNT(*) peopleMinSale + FROM + (SELECT + SUM(v.portfolioWeight) AS importe, + d.`name`, + v.año, + wd.departmentFk + FROM (((bs.vendedores v + JOIN `account`.`user` u ON (u.id = v.Id_Trabajador)) + JOIN vn.workerDepartment wd ON (wd.workerFk = u.id)) + JOIN vn.department d ON (d.id = wd.departmentFk)) + WHERE v.año = vYear + AND d.name LIKE 'EQUIPO%' + AND CEIL(v.mes / 3) = vQuarter + GROUP BY v.Id_Trabajador + HAVING importe >= vMinimumSalesByQuarter) sub + GROUP BY sub.departmentFk) sub1 + JOIN (SELECT + SUM(v.portfolioWeight) AS importe, + d.name, + wd.departmentFk + FROM (((bs.vendedores v + JOIN account.user u ON (u.id = v.Id_Trabajador)) + JOIN vn.workerDepartment wd ON (wd.workerFk = u.id)) + JOIN vn.department d ON (d.id = wd.departmentFk)) + WHERE v.año = vYear - 1 + AND d.name LIKE 'EQUIPO%' + AND CEIL(v.mes / 3) = vQuarter + GROUP BY wd.departmentFk + ORDER BY SUM(v.importe) DESC) sub2 ON (sub1.name = sub2.name)) + JOIN (SELECT COUNT(0) AS countPeople, + wd.departmentFk AS departmentFk + FROM + (vn.salesPersonSince sps + JOIN vn.workerDepartment wd ON (sps.workerFk = wd.workerFk)) + WHERE + CONCAT(YEAR(sps.started), QUARTER(sps.started)) <= CONCAT(vYear - 1, vQuarter) + GROUP BY wd.departmentFk) sub3 ON (sub3.departmentFk = sub1.departmentFk)) + ORDER BY (sub1.importe - sub2.importe) / sub3.countPeople 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 `rate_getPrices` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -54149,7 +58605,7 @@ proc: BEGIN LEAVE proc; END IF; - + /* IF vParkingCode = 'POL-IZON' THEN CALL vn.stowaway_launchShip(vShelvingFk); @@ -54157,7 +58613,7 @@ proc: BEGIN LEAVE proc; END IF; - + */ SELECT id INTO vParkingFk FROM vn.parking WHERE `code` = vParkingCode COLLATE utf8_unicode_ci; @@ -54166,15 +58622,11 @@ proc: BEGIN REPLACE vn.ticketParking(ticketFk,parkingFk) VALUES (vShelvingFk, vParkingFk); - -- deprecated: eliminar despues de campaña PAK 2019-10-08 - -- REPLACE vn.shelving(code, parkingFk, isPrinted, parked) - -- VALUES(vShelvingFk, vParkingFk, TRUE, NOW()); - -- fin deprecated + CALL vn.ticketStatePrevious(vShelvingFk); ELSE - - + UPDATE vn.shelving SET parkingFk = vParkingFk, parked = NOW(), isPrinted = 1 WHERE `code` = vShelvingFk COLLATE utf8_unicode_ci; @@ -54282,6 +58734,131 @@ BEGIN sh.parked < TIMESTAMPADD(MONTH,-1,CURDATE()) ); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `silla_algemesi` */; +/*!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 `silla_algemesi`(vDate DATE) +BEGIN + +DECLARE done INT DEFAULT FALSE; +DECLARE vWarehouseFk INT DEFAULT 60; +DECLARE vTicketFk INT; +DECLARE vSaleFk INT; +DECLARE vClonTicket INT DEFAULT 0; + +DECLARE cur1 CURSOR FOR + select distinct s.ticketFk, s.id + from vn.sale s + join vn.ticket t ON t.id = s.ticketFk + join vn.itemShelving ish ON ish.itemFk = s.itemFk + join vn.shelving sh ON sh.code = ish.shelvingFk + join vn.parking p ON p.id = sh.parkingFk + where t.shipped between vDate and util.dayend(vDate) + and p.sectorFk = 37 + and left(t.nickname,1) != '-' + and t.warehouseFk = 1 + and s.quantity mod ish.packing = 0 + and ( + ( s.itemFk NOT IN (1, 130, 15021, 12697, 52334, 60001, 60130, 38661) and s.quantity >= ish.packing) OR + ( s.itemFk IN ( 12697, 52334) and s.quantity >= ish.packing * 2) + ) + -- limit 1 + ; + + +DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + +OPEN cur1; + +FETCH cur1 INTO vTicketFk, vSaleFk; + + WHILE done = 0 DO + + SELECT t.id INTO vClonTicket + FROM vn.ticket t + JOIN (SELECT addressFk, shipped FROM vn.ticket WHERE id = vTicketFk) sub USING(addressFk, shipped) + WHERE t.warehouseFk = vWarehouseFk + LIMIT 1; + + -- SELECT vTicketFk, vClonTicket; + + IF vClonTicket = 0 THEN + + INSERT INTO ticket ( + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + warehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk + ) + SELECT + clientFk, + shipped, + addressFk, + agencyModeFk, + nickname, + vWarehouseFk, + companyFk, + landed, + zoneFk, + zonePrice, + zoneBonus, + routeFk + + FROM ticket + WHERE id = vTicketFk; + + SET vClonTicket = LAST_INSERT_ID(); + + -- SELECT 'lstID', vClonTicket; + + INSERT IGNORE INTO ticketObservation(ticketFk, observationTypeFk, description) + SELECT vClonTicket, ao.observationTypeFk, ao.description + FROM addressObservation ao + JOIN ticket t ON t.addressFk = ao.addressFk + WHERE t.id = vTicketFk; + + INSERT IGNORE INTO ticketLog + SET originFk = vClonTicket, userFk = account.myUserGetId(), `action` = 'insert', + description = CONCAT('Ha creado el ticket:', ' ', vClonTicket, ' clonando el ', vTicketFk); + + END IF; + + UPDATE vn.sale + SET ticketFk = vClonTicket + WHERE id = vSaleFk; + -- SELECT vTicketFk, vClonTicket; + + SET vClonTicket = 0; + + SET done = 0; + FETCH cur1 INTO vTicketFk, vSaleFk; + + END WHILE; + + CLOSE cur1; + + END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -57353,17 +61930,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 `ticketListCreate` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketListCreate__` */; /*!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 `ticketListCreate`( +CREATE DEFINER=`root`@`%` PROCEDURE `ticketListCreate__`( vClientId INT ,vShipped DATE ,vWarehouseId INT @@ -57384,17 +61961,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 `ticketListVolume` */; +/*!50003 DROP PROCEDURE IF EXISTS `ticketListVolume__` */; /*!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 `ticketListVolume`(IN vTicketId INT) +CREATE DEFINER=`root`@`%` PROCEDURE `ticketListVolume__`(IN vTicketId INT) BEGIN DECLARE vWarehouseId INTEGER; @@ -58737,9 +63314,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -58799,7 +63376,7 @@ BEGIN SELECT zoneFk, price, bonus INTO vZoneFk, vPrice, vBonus FROM tmp.zoneGetShipped - WHERE shipped = vShipped AND warehouseFk = vWarehouseFk LIMIT 1; + WHERE shipped BETWEEN DATE(vShipped) AND util.dayEnd(vShipped) AND warehouseFk = vWarehouseFk LIMIT 1; UPDATE ticket t SET @@ -59464,9 +64041,9 @@ DELIMITER ; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; /*!50003 SET @saved_col_connection = @@collation_connection */ ; -/*!50003 SET character_set_client = utf8 */ ; -/*!50003 SET character_set_results = utf8 */ ; -/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; /*!50003 SET @saved_sql_mode = @@sql_mode */ ; /*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; DELIMITER ;; @@ -59500,8 +64077,8 @@ BEGIN FROM sale s JOIN item i ON i.id = s.itemFk JOIN ticket t ON t.id = s.ticketFk - LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk - AND tc.warehouseFk = t.warehouseFk + LEFT JOIN tmp.ticketComponentPreview tc ON tc.itemFk = s.itemFk + AND tc.warehouseFk = vWarehouseFk LEFT JOIN saleComponent sc ON sc.saleFk = s.id AND sc.componentFk = tc.componentFk LEFT JOIN `component` c ON c.id = tc.componentFk @@ -62151,7 +66728,7 @@ proc: BEGIN END IF; -- VERIFICAR DEPARTAMENTO - IF vTabletFk IS NOT NULL THEN + /* IF vTabletFk IS NOT NULL THEN SELECT wtcu.departmentFk INTO vDepartmentFk FROM workerTimeControlUserInfo wtcu WHERE wtcu.userFk = vUserFk; @@ -62165,7 +66742,7 @@ proc: BEGIN CALL mail_insert(vTo,vTo,'error al fichar',vBody); LEAVE proc; END IF; - END IF; + END IF;*/ END ;; DELIMITER ; @@ -62227,8 +66804,9 @@ BEGIN WHERE userFk = vUserFk AND direction = 'out'; + SELECT email INTO vTo - FROM vn.worker w + FROM account.user w WHERE w.id = (SELECT bossFk FROM vn.worker WHERE id = vUserFk); SELECT CONCAT(firstName,' ',lastName) INTO vUserName @@ -62252,7 +66830,7 @@ BEGIN END IF; -- VERIFICAR DEPARTAMENTO - IF vTabletFk IS NOT NULL THEN + /*IF vTabletFk IS NOT NULL THEN IF ( SELECT COUNT(*) FROM vn.tabletDepartment td JOIN vn.workerTimeControlUserInfo wtcu ON wtcu.departmentFk = td.departmentFk @@ -62263,7 +66841,7 @@ BEGIN CALL vn.mail_insert(vTo,vTo,'error al fichar',vBody); CALL util.throw("No perteneces a este departamento."); END IF; - END IF; + END IF;*/ SELECT IFNULL(dayBreak, vDayBreak) INTO vDayBreak FROM postgresql.business b @@ -62364,6 +66942,194 @@ 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 `workerTimeControl_check__` */; +/*!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 `workerTimeControl_check__`(vUserFk INT, vDated DATE,vTabletFk VARCHAR(100)) +proc: BEGIN +/** + * Verifica si el empleado puede fichar en el momento actual, si puede fichar llama a workerTimeControlAdd + * + * @param vUserFk Identificador del trabajador + * @return Retorna si encuentra un problema 'odd','maxTimeWork','breakDay','breakWeek' ; + * En caso de tener algun problema retorna el primero que encuentra + */ + DECLARE vLastIn DATETIME ; + DECLARE vLastOut DATETIME ; + DECLARE vDayWorkMax INT; + DECLARE vDayBreak INT; + DECLARE vWeekBreak INT ; + DECLARE vWeekScope INT; + DECLARE vDayStayMax INT; + DECLARE vProblem VARCHAR(20) DEFAULT NULL; + DECLARE vTimedWorked INT; + DECLARE vCalendarStateType VARCHAR(20) DEFAULT NULL; + DECLARE vDepartmentFk INT; + DECLARE vTo VARCHAR(50) DEFAULT NULL; + DECLARE vUserName VARCHAR(50) DEFAULT NULL; + DECLARE vBody VARCHAR(255) DEFAULT NULL; + + SELECT dayBreak, weekBreak, weekScope, dayWorkMax, dayStayMax + INTO vDayBreak, vWeekBreak, vWeekScope, vDayWorkMax, vDayStayMax + FROM workerTimeControlParams; + + SELECT MAX(timed) INTO vLastIn + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'in'; + + SELECT MAX(timed) INTO vLastOut + FROM workerTimeControl + WHERE userFk = vUserFk + AND direction = 'out'; + + SELECT CONCAT(u.name,'@verdnatura.es') INTO vTo + FROM account.user u + WHERE u.id = (SELECT bossFk FROM worker WHERE id = vUserFk); + + SELECT CONCAT(firstName,' ',lastName) INTO vUserName + FROM worker w + WHERE w.id = vUserFk; + + + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastIn) > vDayStayMax THEN -- NUEVA JORNADA + + -- VERIFICAR DESCANSO DIARIO + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vDayBreak THEN + SELECT "Descansos 12 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 12 h") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + END IF; + + -- VERIFICAR FICHADAS IMPARES DEL ÚLTIMO DÍA QUE SE FICHÓ + IF (SELECT MOD(COUNT(*),2) -- <>0 + FROM workerTimeControl + WHERE userFk = vUserFk + AND timed >= vLastIn + ) THEN + SELECT "Dias con fichadas impares" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Dias con fichadas impares") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + END IF; + + -- VERIFICAR VACACIONES + SELECT cs.type INTO vCalendarStateType + FROM postgresql.calendar_employee ce + JOIN postgresql.business b USING(business_id) + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN postgresql.calendar_state cs USING(calendar_state_id) + JOIN worker w ON w.id = p.id_trabajador + WHERE ce.date = CURDATE() + AND cs.isAllowedToWork = FALSE + AND w.userFk = vUserFk + LIMIT 1; + + IF(LENGTH(vCalendarStateType)) THEN + SELECT vCalendarStateType AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Vacaciones") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + + END IF; + + + -- VERIFICAR CONTRATO EN VIGOR + IF (SELECT COUNT(*) + FROM postgresql.business b + JOIN postgresql.profile pr ON pr.profile_id = b.client_id + JOIN postgresql.person p ON p.person_id = pr.person_id + JOIN worker w ON w.id = p.id_trabajador + WHERE w.userFk = vUserFk + AND b.date_start <= vDated + AND IFNULL(b.date_end,vDated) >= vDated + ) = 0 THEN + SELECT "No hay un contrato en vigor" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No hay un contrato en vigor") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + + END IF; + + -- VERIFICAR DESCANSO SEMANAL + SET @vHasBreakWeek:= FALSE; + SET @vLastTimed:= UNIX_TIMESTAMP((NOW() - INTERVAL vWeekScope SECOND)); + + DROP TEMPORARY TABLE IF EXISTS tmp.trash; + CREATE TEMPORARY TABLE tmp.trash + SELECT IF(vWeekBreak-(UNIX_TIMESTAMP(timed)-@vLastTimed) <= 0, @vHasBreakWeek:=TRUE, TRUE) alias, + @vLastTimed:= UNIX_TIMESTAMP(timed) + FROM workerTimeControl + WHERE timed>= (NOW() - INTERVAL vWeekScope SECOND) + AND userFk= vUserFk + AND direction IN ('in','out') + ORDER BY timed ASC; + + IF UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(vLastOut) < vWeekBreak AND @vHasBreakWeek = FALSE THEN -- REVISA SI EL DESCANSO SE HA REALIZADO DESPUÉS DE LA ÚLTIMA FICHADA + SELECT "Descansos 36 h" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Descansos 36 h") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + END IF; + + DROP TEMPORARY TABLE tmp.trash; + + ELSE -- DIA ACTUAL + + -- VERIFICA QUE EL TIEMPO EFECTIVO NO SUPERE EL MÁXIMO + SELECT IFNULL(SUM(if( mod(wtc.order,2)=1, -UNIX_TIMESTAMP(timed), UNIX_TIMESTAMP(timed))),0) - IF( MOD(COUNT(*),2), UNIX_TIMESTAMP(NOW()), 0) INTO vTimedWorked + FROM workerTimeControl wtc + WHERE userFk = vUserFk + AND timed >= vLastIn + ORDER BY timed; + + IF vTimedWorked > vDayWorkMax THEN + SELECT "Jornadas" AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"Jornadas") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + END IF; + + END IF; + + -- VERIFICAR DEPARTAMENTO + IF vTabletFk IS NOT NULL THEN + SELECT wtcu.departmentFk INTO vDepartmentFk + FROM workerTimeControlUserInfo wtcu + WHERE wtcu.userFk = vUserFk; + IF (SELECT COUNT(td.tabletFk) + FROM tabletDepartment td + WHERE td.tabletFk = vTabletFk AND td.departmentFk = vDepartmentFk + ) = 0 THEN + SELECT "No perteneces a este departamento." AS problem; + -- ENVIAMOS CORREO AL BOSSFK + SELECT CONCAT(vUserName,' No a podido fichar por el siguiente problema: ',"No perteneces a este departamento.") INTO vBody; + CALL mail_insert(vTo,vTo,'error al fichar',vBody); + LEAVE proc; + END IF; + 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 `workerTimeControl_remove` */; /*!50003 SET @saved_cs_client = @@character_set_client */ ; /*!50003 SET @saved_cs_results = @@character_set_results */ ; @@ -62993,6 +67759,280 @@ SELECT 7_dias_antes,6_dias_antes,5_dias_antes,4_dias_antes,3_dias_antes,2_dias_a DROP TEMPORARY TABLE tmp.workerWeekTiming; DROP TEMPORARY TABLE tmp.workerWeekTiming_Aux; +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 `worker_calculateCommission` */; +/*!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 `worker_calculateCommission`(vYear INT, vQuarter INT) +BEGIN + + DECLARE vPlusTeamAmount INT; + DECLARE vPlusNewBornAmount INT; + DECLARE vPlusSalesAmount INT; + DECLARE vMinimumSalesByQuarter INT; + DECLARE vPlusTeamRange INT; + DECLARE vPlusNewBornRange INT; + DECLARE vRankingSalesRange INT; + +/* + -- Jerarquia + DROP TEMPORARY TABLE IF EXISTS rankingHierarchy; + CREATE TEMPORARY TABLE rankingHierarchy + SELECT COUNT(*) - 1 teamMembers, wb.bossFk + FROM vn.worker ww + JOIN vn.worker wb ON ww.id = wb.bossFk + GROUP BY wb.bossFk; + */ + + SELECT plusTeamAmount, plusNewBornAmount, plusSalesAmount, minimumSalesByQuarter, plusTeamRange, plusNewBornRange, rankingSalesRange + INTO vPlusTeamAmount, vPlusNewBornAmount, vPlusSalesAmount, vMinimumSalesByQuarter, vPlusTeamRange, vPlusNewBornRange, vRankingSalesRange + FROM commissionConfig; + -- Ventas + DROP TEMPORARY TABLE IF EXISTS rankingSale; + CREATE TEMPORARY TABLE rankingSale + (PRIMARY KEY(workerFk)) ENGINE = MEMORY + SELECT IF(SUM(v.importe) > vMinimumSalesByQuarter, + SUM(IFNULL(v.comision,0)), + 0) as commission, + SUM(v.importe) sales, + v.Id_Trabajador workerFk + FROM bs.vendedores v + WHERE v.año = vYear AND CEIL(mes/3) = vQuarter + GROUP BY v.Id_Trabajador; + + -- Ranking ventas + SET @position:= 0; + DROP TEMPORARY TABLE IF EXISTS rankingSelling; + CREATE TEMPORARY TABLE rankingSelling + (PRIMARY KEY(userFk)) ENGINE = MEMORY + SELECT userFk, @position:= @position + 1 position + FROM ( + SELECT SUM(`v`.`importe`) AS `importe`, + `u`.`name` AS `name`, + `u`.`id` AS `userFk` + FROM + (`bs`.`vendedores` `v` + JOIN `account`.`user` `u` ON (`u`.`id` = `v`.`Id_Trabajador`)) + WHERE + `v`.`año` = vYear + AND CEIL(`v`.`mes` / 3) = vQuarter + AND `u`.`name` NOT IN ('ismaelalcolea' , 'ruben') + GROUP BY `v`.`Id_Trabajador` + ORDER BY SUM(`v`.`importe`) DESC + LIMIT vRankingSalesRange + ) t; + + CALL rankingTeamByQuarter(vYear, vQuarter); + + -- comerciales que computan / total integrantes + DROP TEMPORARY TABLE IF EXISTS teamNames; + CREATE TEMPORARY TABLE teamNames + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + SELECT DISTINCT departmentFk, teamPeople + FROM tmp.rankingTeam; + + -- Ranking por equipos + DROP TEMPORARY TABLE IF EXISTS rankingTeam; + CREATE TEMPORARY TABLE rankingTeam + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + SELECT DISTINCT departmentFk + FROM teamNames + LIMIT vPlusTeamRange; + + -- Ranking por nuevos clientes + SET @position:= 0; + DROP TEMPORARY TABLE IF EXISTS rankingNewBorn; + CREATE TEMPORARY TABLE rankingNewBorn + (PRIMARY KEY(userFk)) ENGINE = MEMORY + SELECT userFk, @position:= @position + 1 position + FROM ( + SELECT SUM(amount) AS total, + n.userFk + FROM newBornSales n + WHERE n.dated >= util.quarterFirstDay(vYear, vQuarter) + AND n.firstShipped >= util.quarterFirstDay(vYear -1, vQuarter) + GROUP BY userFk + ORDER BY SUM(amount) DESC + LIMIT vPlusNewBornRange + ) t; + + -- Sumatorio de ventas + SELECT uBoss.`name` as team, + u.`name`, + r.commission, + -- IF(rh.bossFk, 200 + (teamMembers * 30), 0) plusResponsibility, + @plusRankingSellers := ((vRankingSalesRange + 1) - rs.position) * 40 plusRankingSellers, + @plusRankingTeam := IF(rt.departmentFk, vPlusTeamAmount, 0) plusRankingTeam, + @plusRankingNewBorn := ((vPlusNewBornRange + 1) - rnb.position) * vPlusNewBornAmount plusRankingNewBorn, + IFNULL(r.commission,0) + IFNULL(@plusRankingSellers,0) + @plusRankingTeam + IFNULL(@plusRankingNewBorn, 0) total, + sales, rs.position, teamPeople, + vYear year, + vQuarter quarter + FROM rankingSale r + -- LEFT JOIN rankingHierarchy rh ON rh.bossFk = r.workerFk + JOIN account.user u ON u.id = r.workerFk + JOIN vn2008.jerarquia j ON j.worker_id = r.workerFk + LEFT JOIN `account`.`user` uBoss ON uBoss.id = j.boss_id + LEFT JOIN rankingSelling rs ON rs.userFk = r.workerFk + LEFT JOIN workerDepartment wd ON wd.workerFk = r.workerFk + LEFT JOIN rankingTeam rt ON rt.departmentFk = wd.departmentFk AND r.commission + LEFT JOIN teamNames tn ON tn.departmentFk = wd.departmentFk + LEFT JOIN vn.rankingNewBorn rnb ON rnb.userFk = r.workerFk; + + DROP TEMPORARY TABLE tmp.rankingTeam; + DROP TEMPORARY TABLE + rankingSelling, + rankingTeam, + teamNames, + rankingNewBorn, + rankingSale; +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 `worker_calculateCommission__` */; +/*!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 `worker_calculateCommission__`(vYear INT, vQuarter INT) +BEGIN + + DECLARE vQuarterFirstDayLastYear DATE; + DECLARE vQuarterFirstDay DATE; +/* + -- Jerarquia + DROP TEMPORARY TABLE IF EXISTS rankingHierarchy; + CREATE TEMPORARY TABLE rankingHierarchy + SELECT COUNT(*) - 1 teamMembers, wb.bossFk + FROM vn.worker ww + JOIN vn.worker wb ON ww.id = wb.bossFk + GROUP BY wb.bossFk; + */ + + -- Ranking ventas + SELECT MIN(dated) INTO vQuarterFirstDay + FROM `time` t + WHERE QUARTER(dated) = vQuarter AND t.`year` = vYear; + + SET vQuarterFirstDayLastYear = DATE_ADD(vQuarterFirstDay, INTERVAL -1 YEAR); + + SET @position:= 0; + DROP TEMPORARY TABLE IF EXISTS rankingSelling; + CREATE TEMPORARY TABLE rankingSelling + (PRIMARY KEY(userFk)) ENGINE = MEMORY + SELECT userFk, @position:= @position + 1 position + FROM ( + SELECT SUM(`v`.`importe`) AS `importe`, + `u`.`name` AS `name`, + `u`.`id` AS `userFk` + FROM + (`bs`.`vendedores` `v` + JOIN `account`.`user` `u` ON (`u`.`id` = `v`.`Id_Trabajador`)) + WHERE + `v`.`año` = vYear + AND CEIL(`v`.`mes` / 3) = vQuarter + AND `u`.`name` NOT IN ('ismaelalcolea' , 'ruben') + GROUP BY `v`.`Id_Trabajador` + ORDER BY SUM(`v`.`importe`) DESC + LIMIT 10 + ) t; + + CALL rankingTeamByQuarter(vYear, vQuarter); + + -- comerciales que computan / total integrantes + DROP TEMPORARY TABLE IF EXISTS teamNames; + CREATE TEMPORARY TABLE teamNames + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + SELECT DISTINCT departmentFk, teamPeople + FROM tmp.rankingTeam; + + -- Ranking por equipos + DROP TEMPORARY TABLE IF EXISTS rankingTeam; + CREATE TEMPORARY TABLE rankingTeam + (PRIMARY KEY(departmentFk)) ENGINE = MEMORY + SELECT DISTINCT departmentFk + FROM teamNames + LIMIT 3; + + -- Ranking por nuevos clientes + SET @position:= 0; + DROP TEMPORARY TABLE IF EXISTS rankingNewBorn; + CREATE TEMPORARY TABLE rankingNewBorn + (PRIMARY KEY(userFk)) ENGINE = MEMORY + SELECT userFk, @position:= @position + 1 position + FROM ( + SELECT SUM(amount) AS total, + n.userFk + FROM newBornSales n + WHERE n.dated >= vQuarterFirstDay + AND n.firstShipped >= vQuarterFirstDayLastYear + GROUP BY userFk + ORDER BY SUM(amount) DESC + LIMIT 10 + ) t; + + -- Ventas + DROP TEMPORARY TABLE IF EXISTS rankingSale; + CREATE TEMPORARY TABLE rankingSale + (PRIMARY KEY(workerFk)) ENGINE = MEMORY + SELECT IF(SUM(v.importe) > 120000, + SUM(IFNULL(v.comision,0)),0) as commission, + SUM(v.importe) sales, + v.Id_Trabajador workerFk + FROM bs.vendedores v + WHERE v.año = vYear AND CEIL(mes/3) = vQuarter + GROUP BY v.Id_Trabajador; + + -- Sumatorio de ventas + SELECT uBoss.`name` as team, + u.`name`, + r.commission, + -- IF(rh.bossFk, 200 + (teamMembers * 30), 0) plusResponsibility, + @plusRankingSellers := (11 - rs.position) * 40 plusRankingSellers, + @plusRankingTeam := IF(rt.departmentFk, 800, 0) plusRankingTeam, + @plusRankingNewBorn := (11 - rnb.position) * 40 plusRankingNewBorn, + IFNULL(r.commission,0) + IFNULL(@plusRankingSellers,0) + @plusRankingTeam + IFNULL(@plusRankingNewBorn, 0) total, + sales, rs.position, teamPeople, + vYear year, + vQuarter quarter + FROM rankingSale r + -- LEFT JOIN rankingHierarchy rh ON rh.bossFk = r.workerFk + JOIN account.user u ON u.id = r.workerFk + JOIN vn2008.jerarquia j ON j.worker_id = r.workerFk + LEFT JOIN `account`.`user` uBoss ON uBoss.id = j.boss_id + LEFT JOIN rankingSelling rs ON rs.userFk = r.workerFk + LEFT JOIN workerDepartment wd ON wd.workerFk = r.workerFk + LEFT JOIN rankingTeam rt ON rt.departmentFk = wd.departmentFk AND r.commission + LEFT JOIN teamNames tn ON tn.departmentFk = wd.departmentFk + LEFT JOIN vn.rankingNewBorn rnb ON rnb.userFk = r.workerFk; + + DROP TEMPORARY TABLE tmp.rankingTeam; + DROP TEMPORARY TABLE + rankingSelling, + rankingTeam, + teamNames, + rankingNewBorn, + rankingSale; END ;; DELIMITER ; /*!50003 SET sql_mode = @saved_sql_mode */ ; @@ -65681,6 +70721,24 @@ USE `bs`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `v_ventas__` +-- + +/*!50001 DROP VIEW IF EXISTS `v_ventas__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `v_ventas__` AS select (`bs`.`ventas`.`importe` * `Movimientos`.`Cantidad`) AS `importe`,`bs`.`ventas`.`recargo` AS `recargo`,`time`.`year` AS `year`,`time`.`month` AS `month`,`time`.`week` AS `week`,`time`.`day` AS `day` from ((`bs`.`ventas` join `vn2008`.`time` on((`time`.`date` = `bs`.`ventas`.`fecha`))) join `vn2008`.`Movimientos` on((`bs`.`ventas`.`Id_Movimiento` = `Movimientos`.`Id_Movimiento`))) group by `time`.`date` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `workerMana` -- @@ -66209,6 +71267,30 @@ USE `postgresql`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Current Database: `sage` +-- + +USE `sage`; + +-- +-- Final view structure for view `invoiceInList` +-- + +/*!50001 DROP VIEW IF EXISTS `invoiceInList`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `invoiceInList` AS select `invoiceIn`.`id` AS `id`,`invoiceIn`.`supplierRef` AS `supplierRef`,`invoiceIn`.`serial` AS `serial`,`invoiceIn`.`supplierFk` AS `supplierFk`,`invoiceIn`.`issued` AS `issued`,`invoiceIn`.`isVatDeductible` AS `isVatDeductible`,`invoiceIn`.`serialNumber` AS `serialNumber` from `vn`.`invoiceIn` where (`invoiceIn`.`issued` >= (date_format(curdate(),'%Y-01-01') + interval -(1) year)) union all select `vn`.`dua`.`id` AS `id`,`vn`.`dua`.`code` AS `code`,'D' AS `D`,442 AS `442`,`vn`.`dua`.`issued` AS `issued`,0 AS `FALSE`,`vn`.`dua`.`id` AS `serialNumber` from `vn`.`dua` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Current Database: `salix` -- @@ -66462,7 +71544,7 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`t`.`addressFk` AS `addressFk`,`t`.`shipped` AS `shipped`,`a`.`nickname` AS `clientName`,`a`.`postalCode` AS `clientPostalCode`,`a`.`street` AS `clientStreet`,`a`.`city` AS `clientCity`,`p`.`name` AS `clientProvince`,`co`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode` AS `companyPostCode`,`su`.`city` AS `companyCity`,`sc`.`country` AS `companyCountry`,`w`.`addressName` AS `warehouseAddress`,`c`.`name` AS `clientOficialName`,ifnull(`ags`.`name`,`agm`.`name`) AS `carrierName`,`ags`.`street` AS `carrierStreet`,`ags`.`postCode` AS `carrierPostCode`,`ags`.`city` AS `carrierCity`,`sco`.`country` AS `carrierCountry`,ifnull(`a`.`phone`,`c`.`phone`) AS `phone`,ifnull(`a`.`mobile`,`c`.`mobile`) AS `mobile` from ((((((((((((`cmr` join `ticket` `t` on((`t`.`id` = `cmr`.`ticketFk`))) join `address` `a` on((`a`.`id` = `t`.`addressFk`))) join `province` `p` on((`p`.`id` = `a`.`provinceFk`))) join `country` `co` on((`co`.`id` = `p`.`countryFk`))) join `warehouse` `w` on((`w`.`id` = `t`.`warehouseFk`))) join `supplier` `su` on((`su`.`id` = `t`.`companyFk`))) join `country` `sc` on((`sc`.`id` = `su`.`countryFk`))) join `client` `c` on((`c`.`id` = `t`.`clientFk`))) join `agencyMode` `agm` on((`agm`.`id` = `t`.`agencyModeFk`))) join `agency` `ag` on((`ag`.`id` = `agm`.`agencyFk`))) left join `supplier` `ags` on((`ags`.`id` = `ag`.`supplierFk`))) left join `country` `sco` on((`sco`.`id` = `ags`.`countryFk`))) */; +/*!50001 VIEW `cmr_list` AS select `cmr`.`id` AS `cmrFk`,`cmr`.`ticketFk` AS `ticketFk`,`cmr`.`truckPlate` AS `truckPlate`,`cmr`.`observations` AS `observations`,`cmr`.`senderInstruccions` AS `senderInstruccions`,`cmr`.`paymentInstruccions` AS `paymentInstruccions`,`cmr`.`specialAgreements` AS `specialAgreements`,`cmr`.`created` AS `created`,`cmr`.`packagesList` AS `packagesList`,`aTo`.`nickname` AS `clientName`,`aTo`.`postalCode` AS `clientPostalCode`,`aTo`.`street` AS `clientStreet`,`aTo`.`city` AS `clientCity`,`pTo`.`name` AS `clientProvince`,`cTo`.`country` AS `clientCountry`,`su`.`name` AS `companyName`,`su`.`street` AS `companyStreet`,`su`.`postCode` AS `companyPostCode`,`su`.`city` AS `companyCity`,`cSu`.`country` AS `companyCountry`,concat(`aFrom`.`street`,' ',`aFrom`.`postalCode`,' ',`aFrom`.`city`,' (',`cFrom`.`country`,')') AS `warehouseAddress`,`cmr`.`created` AS `shipped`,`client`.`socialName` AS `clientOficialName`,`aSu`.`name` AS `carrierName`,`aSu`.`street` AS `carrierStreet`,`aSu`.`postCode` AS `carrierPostCode`,`aSu`.`city` AS `carrierCity`,`cAs`.`country` AS `carrierCountry`,ifnull(`aTo`.`phone`,`client`.`phone`) AS `phone`,ifnull(`aTo`.`mobile`,`client`.`mobile`) AS `mobile`,`aTo`.`id` AS `addressFk` from (((((((((((`cmr` join `address` `aTo` on((`aTo`.`id` = `cmr`.`addressToFk`))) join `province` `pTo` on((`pTo`.`id` = `aTo`.`provinceFk`))) join `country` `cTo` on((`cTo`.`id` = `pTo`.`countryFk`))) join `client` on((`client`.`id` = `aTo`.`clientFk`))) join `supplier` `su` on((`su`.`id` = `cmr`.`companyFk`))) join `country` `cSu` on((`cSu`.`id` = `su`.`countryFk`))) join `address` `aFrom` on((`aFrom`.`id` = `cmr`.`addressFromFk`))) join `province` `pFrom` on((`pFrom`.`id` = `aFrom`.`provinceFk`))) join `country` `cFrom` on((`cFrom`.`id` = `pFrom`.`countryFk`))) join `supplier` `aSu` on((`aSu`.`id` = `cmr`.`supplierFk`))) join `country` `cAs` on((`cAs`.`id` = `aSu`.`countryFk`))) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -66727,12 +71809,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionCommon` AS select `et`.`id` AS `truckFk`,`et`.`ETD` AS `etd`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk` from (((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on((`t`.`id` = `e`.`ticketFk`))) left join `vn`.`expeditionScan` `es` on((`e`.`id` = `es`.`expeditionFk`))) left join `vn`.`expeditionPallet` `ep` on((`es`.`palletFk` = `ep`.`id`))) left join `vn`.`expeditionTruck` `et` on((`ep`.`truckFk` = `et`.`id`))) left join `vn`.`routesMonitor` `r` on((`r`.`routeFk` = `t`.`routeFk`))) where ((`t`.`shipped` >= curdate()) and (`t`.`routeFk` <> 0)) */; +/*!50001 VIEW `expeditionCommon` AS select `et`.`id` AS `truckFk`,`et`.`ETD` AS `etd`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `description`,`es`.`palletFk` AS `palletFk`,`t`.`routeFk` AS `routeFk`,`es`.`id` AS `scanFk`,`e`.`id` AS `expeditionFk`,`r`.`expeditionTruckFk` AS `expeditionTruckFk`,`t`.`warehouseFk` AS `warehouseFk`,`e`.`created` AS `lastPacked` from (((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on((`t`.`id` = `e`.`ticketFk`))) left join `vn`.`expeditionScan` `es` on((`e`.`id` = `es`.`expeditionFk`))) left join `vn`.`expeditionPallet` `ep` on((`es`.`palletFk` = `ep`.`id`))) left join `vn`.`routesMonitor` `r` on((`r`.`routeFk` = `t`.`routeFk`))) left join `vn`.`expeditionTruck` `et` on((`et`.`id` = `r`.`expeditionTruckFk`))) where ((`t`.`shipped` >= curdate()) and (`t`.`routeFk` <> 0)) */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -66750,7 +71832,25 @@ USE `vn`; /*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionPallet_Print` AS select `et2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,(`et`.`id` <=> `rm`.`expeditionTruckFk`) AS `isMatch`,min(`t`.`warehouseFk`) AS `warehouseFk` from (((((((`vn`.`expeditionTruck` `et` join `vn`.`expeditionPallet` `ep` on((`ep`.`truckFk` = `et`.`id`))) join `vn`.`expeditionScan` `es` on((`es`.`palletFk` = `ep`.`id`))) join `vn`.`expedition` `e` on((`e`.`id` = `es`.`expeditionFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `e`.`ticketFk`))) join `vn`.`route` `r` on((`r`.`id` = `t`.`routeFk`))) join `vn2008`.`Rutas_monitor` `rm` on((`rm`.`Id_Ruta` = `r`.`id`))) join `vn`.`expeditionTruck` `et2` on((`et2`.`id` = `rm`.`expeditionTruckFk`))) where (`ep`.`isPrint` = 0) group by `ep`.`id`,`t`.`routeFk` */; +/*!50001 VIEW `expeditionPallet_Print` AS select `et2`.`description` AS `truck`,`t`.`routeFk` AS `routeFk`,`r`.`description` AS `zone`,count(`es`.`id`) AS `eti`,`ep`.`id` AS `palletFk`,(`et`.`id` <=> `rm`.`expeditionTruckFk`) AS `isMatch`,37 AS `warehouseFk` from (((((((`vn`.`expeditionTruck` `et` join `vn`.`expeditionPallet` `ep` on((`ep`.`truckFk` = `et`.`id`))) join `vn`.`expeditionScan` `es` on((`es`.`palletFk` = `ep`.`id`))) join `vn`.`expedition` `e` on((`e`.`id` = `es`.`expeditionFk`))) join `vn`.`ticket` `t` on((`t`.`id` = `e`.`ticketFk`))) join `vn`.`route` `r` on((`r`.`id` = `t`.`routeFk`))) left join `vn2008`.`Rutas_monitor` `rm` on((`rm`.`Id_Ruta` = `r`.`id`))) left join `vn`.`expeditionTruck` `et2` on((`et2`.`id` = `rm`.`expeditionTruckFk`))) where (`ep`.`isPrint` = 0) group by `ep`.`id`,`t`.`routeFk` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `expeditionRoute_Monitor` +-- + +/*!50001 DROP VIEW IF EXISTS `expeditionRoute_Monitor`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `expeditionRoute_Monitor` AS select `r`.`id` AS `routeFk`,count(distinct `e`.`id`) AS `expeditions`,count(distinct `es`.`id`) AS `scanned`,max(`e`.`created`) AS `lastPacked` from (((((`vn`.`route` `r` join `vn`.`routesMonitor` `rm` on((`r`.`id` = `rm`.`routeFk`))) join `vn`.`expeditionTruck` `et` on((`et`.`id` = `rm`.`expeditionTruckFk`))) join `vn`.`ticket` `t` on((`t`.`routeFk` = `r`.`id`))) left join `vn`.`expedition` `e` on((`e`.`ticketFk` = `t`.`id`))) left join `vn`.`expeditionScan` `es` on((`es`.`expeditionFk` = `e`.`id`))) where (`et`.`ETD` >= curdate()) group by `r`.`id` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -66799,12 +71899,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control` AS select `e`.`truckFk` AS `id`,`e`.`etd` AS `ETD`,`e`.`description` AS `description`,count(distinct `e`.`palletFk`) AS `pallets`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionFk`) AS `expeditions`,sum((`e`.`truckFk` <> `e`.`expeditionTruckFk`)) AS `fallos` from `vn`.`expeditionCommon` `e` group by `e`.`truckFk` order by `fallos` desc,`e`.`etd` */; +/*!50001 VIEW `expeditionTruck_Control` AS select `e`.`truckFk` AS `id`,`e`.`etd` AS `ETD`,`e`.`description` AS `description`,count(distinct `e`.`palletFk`) AS `pallets`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionFk`) AS `expeditions`,sum((`e`.`truckFk` <> `e`.`expeditionTruckFk`)) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `vn`.`expeditionCommon` `e` group by `e`.`truckFk` order by `fallos` desc,`e`.`etd` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -66817,12 +71917,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail` AS select `e`.`truckFk` AS `id`,`e`.`etd` AS `ETD`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionTruckFk`) AS `destinos`,sum((`e`.`truckFk` <> `e`.`expeditionTruckFk`)) AS `fallos` from `vn`.`expeditionCommon` `e` group by `e`.`truckFk`,`e`.`palletFk` order by `fallos` desc,`e`.`etd`,`e`.`truckFk` */; +/*!50001 VIEW `expeditionTruck_Control_Detail` AS select `e`.`truckFk` AS `id`,`e`.`etd` AS `ETD`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,count(distinct `e`.`routeFk`) AS `routes`,count(distinct `e`.`scanFk`) AS `scans`,count(distinct `e`.`expeditionTruckFk`) AS `destinos`,sum((`e`.`truckFk` <> `e`.`expeditionTruckFk`)) AS `fallos`,max(`e`.`lastPacked`) AS `lastPacked` from `vn`.`expeditionCommon` `e` group by `e`.`truckFk`,`e`.`palletFk` order by `fallos` desc,`e`.`etd`,`e`.`truckFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -66835,66 +71935,12 @@ USE `vn`; /*!50001 SET @saved_cs_client = @@character_set_client */; /*!50001 SET @saved_cs_results = @@character_set_results */; /*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; /*!50001 CREATE ALGORITHM=UNDEFINED */ /*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`etd` AS `ETD`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`et`.`description` AS `destinos`,sum((`e`.`truckFk` <> `e`.`expeditionTruckFk`)) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk` from (`vn`.`expeditionCommon` `e` left join `vn`.`expeditionTruck` `et` on((`et`.`id` = `e`.`expeditionTruckFk`))) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by `fallos` desc,`e`.`palletFk` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control_Detail_Pallet__` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail_Pallet__`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet__` AS select `et`.`id` AS `id`,`et`.`ETD` AS `ETD`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `destino`,`ep`.`id` AS `pallet`,`t`.`routeFk` AS `route`,count(distinct `es`.`id`) AS `scans`,`et2`.`description` AS `destinos`,sum((`et`.`id` <> `rm`.`expeditionTruckFk`)) AS `fallos`,`rm`.`expeditionTruckFk` AS `expeditionTruckFk` from ((((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on((`t`.`id` = `e`.`ticketFk`))) left join `vn`.`expeditionScan` `es` on((`e`.`id` = `es`.`expeditionFk`))) left join `vn`.`expeditionPallet` `ep` on((`es`.`palletFk` = `ep`.`id`))) left join `vn`.`expeditionTruck` `et` on((`ep`.`truckFk` = `et`.`id`))) left join `vn2008`.`Rutas_monitor` `rm` on((`rm`.`Id_Ruta` = `t`.`routeFk`))) left join `vn`.`expeditionTruck` `et2` on((`et2`.`id` = `rm`.`expeditionTruckFk`))) where ((`t`.`shipped` >= curdate()) and `t`.`routeFk`) group by `et`.`id`,`ep`.`id`,`t`.`routeFk` order by `fallos` desc,`ep`.`id` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control_Detail__` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control_Detail__`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control_Detail__` AS select `et`.`id` AS `id`,`et`.`ETD` AS `ETD`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `destino`,`ep`.`id` AS `pallet`,count(distinct `t`.`routeFk`) AS `routes`,count(distinct `es`.`id`) AS `scans`,count(distinct `rm`.`expeditionTruckFk`) AS `destinos`,sum((`et`.`id` <> `rm`.`expeditionTruckFk`)) AS `fallos` from (((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on((`t`.`id` = `e`.`ticketFk`))) left join `vn`.`expeditionScan` `es` on((`e`.`id` = `es`.`expeditionFk`))) left join `vn`.`expeditionPallet` `ep` on((`es`.`palletFk` = `ep`.`id`))) left join `vn`.`expeditionTruck` `et` on((`ep`.`truckFk` = `et`.`id`))) left join `vn2008`.`Rutas_monitor` `rm` on((`rm`.`Id_Ruta` = `t`.`routeFk`))) where ((`t`.`shipped` >= curdate()) and `t`.`routeFk`) group by `et`.`id`,`ep`.`id` order by `fallos` desc,`et`.`ETD`,`et`.`id` */; -/*!50001 SET character_set_client = @saved_cs_client */; -/*!50001 SET character_set_results = @saved_cs_results */; -/*!50001 SET collation_connection = @saved_col_connection */; - --- --- Final view structure for view `expeditionTruck_Control__` --- - -/*!50001 DROP VIEW IF EXISTS `expeditionTruck_Control__`*/; -/*!50001 SET @saved_cs_client = @@character_set_client */; -/*!50001 SET @saved_cs_results = @@character_set_results */; -/*!50001 SET @saved_col_connection = @@collation_connection */; -/*!50001 SET character_set_client = utf8mb4 */; -/*!50001 SET character_set_results = utf8mb4 */; -/*!50001 SET collation_connection = utf8mb4_general_ci */; -/*!50001 CREATE ALGORITHM=UNDEFINED */ -/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ -/*!50001 VIEW `expeditionTruck_Control__` AS select `et`.`id` AS `id`,`et`.`ETD` AS `ETD`,ifnull(ucase(`et`.`description`),'SIN ESCANEAR') AS `description`,count(distinct `ep`.`id`) AS `pallets`,count(distinct `t`.`routeFk`) AS `routes`,count(distinct `es`.`id`) AS `scans`,count(distinct `e`.`id`) AS `expeditions`,sum((`et`.`id` <> `rm`.`expeditionTruckFk`)) AS `fallos` from (((((`vn`.`ticket` `t` left join `vn`.`expedition` `e` on((`t`.`id` = `e`.`ticketFk`))) left join `vn`.`expeditionScan` `es` on((`e`.`id` = `es`.`expeditionFk`))) left join `vn`.`expeditionPallet` `ep` on((`es`.`palletFk` = `ep`.`id`))) left join `vn`.`expeditionTruck` `et` on((`ep`.`truckFk` = `et`.`id`))) left join `vn2008`.`Rutas_monitor` `rm` on((`rm`.`Id_Ruta` = `t`.`routeFk`))) where ((`t`.`shipped` >= curdate()) and `t`.`routeFk`) group by `et`.`id` order by `fallos` desc,`et`.`ETD` */; +/*!50001 VIEW `expeditionTruck_Control_Detail_Pallet` AS select `e`.`truckFk` AS `id`,`e`.`etd` AS `ETD`,`e`.`description` AS `destino`,`e`.`palletFk` AS `pallet`,`e`.`routeFk` AS `route`,count(distinct `e`.`scanFk`) AS `scans`,`et`.`description` AS `destinos`,sum((`e`.`truckFk` <> `e`.`expeditionTruckFk`)) AS `fallos`,`e`.`expeditionTruckFk` AS `expeditionTruckFk`,max(`e`.`lastPacked`) AS `lastPacked` from (`vn`.`expeditionCommon` `e` left join `vn`.`expeditionTruck` `et` on((`et`.`id` = `e`.`expeditionTruckFk`))) group by `e`.`truckFk`,`e`.`palletFk`,`e`.`routeFk` order by `fallos` desc,`e`.`palletFk` */; /*!50001 SET character_set_client = @saved_cs_client */; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; @@ -67475,6 +72521,60 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `mistake` +-- + +/*!50001 DROP VIEW IF EXISTS `mistake`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mistake` AS select `wr`.`code` AS `revisador`,`s`.`concept` AS `concept`,`w`.`code` AS `sacador`,`w`.`firstName` AS `firstName`,`w`.`lastName` AS `lastName`,`mt`.`description` AS `description`,cast(`iss`.`created` as date) AS `created`,`w`.`id` AS `workerFk` from (((((`saleMistake` `sm` join `mistakeType` `mt` on((`mt`.`id` = `sm`.`typeFk`))) join `worker` `wr` on((`wr`.`id` = `sm`.`userFk`))) join `sale` `s` on((`s`.`id` = `sm`.`saleFk`))) join `itemShelvingSale` `iss` on((`iss`.`saleFk` = `sm`.`saleFk`))) join `worker` `w` on((`w`.`id` = `iss`.`userFk`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `mistakeRatio` +-- + +/*!50001 DROP VIEW IF EXISTS `mistakeRatio`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mistakeRatio` AS select `wr`.`code` AS `revisador`,`w`.`code` AS `sacador`,`w`.`firstName` AS `firstName`,`w`.`lastName` AS `lastName`,`mt`.`description` AS `description`,cast(`iss`.`created` as date) AS `created`,`w`.`id` AS `workerFk`,`sm`.`saleFk` AS `saleFk` from ((((`itemShelvingSale` `iss` join `worker` `w` on((`w`.`id` = `iss`.`userFk`))) left join `saleMistake` `sm` on((`iss`.`saleFk` = `sm`.`saleFk`))) left join `mistakeType` `mt` on((`mt`.`id` = `sm`.`typeFk`))) left join `worker` `wr` on((`wr`.`id` = `sm`.`userFk`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `newBornSales` +-- + +/*!50001 DROP VIEW IF EXISTS `newBornSales`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `newBornSales` AS select `v`.`importe` AS `amount`,`c`.`salesPersonFk` AS `userFk`,`v`.`fecha` AS `dated`,`cn`.`firstShipped` AS `firstShipped` from (((`bs`.`clientNewBorn` `cn` join `bs`.`ventas` `v` on((((`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`))) where ((`u`.`role` = 18) and (`u`.`name` not in ('ismaelalcolea','ruben'))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `originL10n` -- @@ -67565,6 +72665,42 @@ USE `vn`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Final view structure for view `rankingNewBornByQuarter__` +-- + +/*!50001 DROP VIEW IF EXISTS `rankingNewBornByQuarter__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `rankingNewBornByQuarter__` AS select sum(`v`.`importe`) AS `total`,`u`.`name` AS `name`,now() AS `time_sec`,`u`.`id` AS `userFk` from (((`bs`.`clientNewBorn` `cn` join `bs`.`ventas` `v` on((((`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`))) where ((`v`.`fecha` >= '2020-07-01') and (`cn`.`firstShipped` >= '2019-07-01') and (`u`.`role` = 18) and (`u`.`name` not in ('ismaelalcolea','ruben'))) group by `u`.`id` order by sum(`v`.`importe`) desc limit 20 */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `rankingSellingByQuarter__` +-- + +/*!50001 DROP VIEW IF EXISTS `rankingSellingByQuarter__`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `rankingSellingByQuarter__` AS select sum(`v`.`importe`) AS `importe`,`u`.`name` AS `name`,`u`.`id` AS `userFk`,now() AS `time_sec` from (`bs`.`vendedores` `v` join `account`.`user` `u` on((`u`.`id` = `v`.`Id_Trabajador`))) where ((`v`.`año` = year(curdate())) and (quarter(concat(year(curdate()),'-',`v`.`mes`,'-01')) = quarter(curdate())) and (`u`.`name` not in ('ismaelalcolea','ruben'))) group by `v`.`Id_Trabajador` order by sum(`v`.`importe`) desc limit 15 */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Final view structure for view `role` -- @@ -68210,4 +73346,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2020-09-28 8:35:00 +-- Dump completed on 2020-10-20 11:28:39 diff --git a/db/export-data.sh b/db/export-data.sh index 1d1b41d78..e7e588abd 100755 --- a/db/export-data.sh +++ b/db/export-data.sh @@ -82,3 +82,10 @@ TABLES=( workcenter ) dump_tables ${TABLES[@]} + +TABLES=( + sage + TiposIva + TiposTransacciones +) +dump_tables ${TABLES[@]} \ No newline at end of file diff --git a/db/export-structure.sh b/db/export-structure.sh index 891812824..1fef22a31 100755 --- a/db/export-structure.sh +++ b/db/export-structure.sh @@ -9,6 +9,7 @@ SCHEMAS=( nst pbx postgresql + sage salix stock util diff --git a/e2e/helpers/selectors.js b/e2e/helpers/selectors.js index e586f38ed..3bcce51a2 100644 --- a/e2e/helpers/selectors.js +++ b/e2e/helpers/selectors.js @@ -42,13 +42,24 @@ export default { taxNumber: 'vn-client-create vn-textfield[ng-model="$ctrl.client.fi"]', socialName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.socialName"]', street: 'vn-client-create vn-textfield[ng-model="$ctrl.client.street"]', + addPostCode: 'vn-client-create vn-datalist[ng-model="$ctrl.client.postcode"] vn-icon-button[icon="add_circle"]', + addProvince: 'vn-autocomplete[ng-model="$ctrl.location.provinceFk"] vn-icon-button[icon="add_circle"]', + addCity: 'vn-autocomplete[ng-model="$ctrl.location.townFk"] vn-icon-button[icon="add_circle"]', + newProvinceName: 'vn-textfield[ng-model="$ctrl.province.name"]', + newCityName: 'vn-textfield[ng-model="$ctrl.city.name"]', + newCityProvince: 'vn-autocomplete[ng-model="$ctrl.city.provinceFk"]', + newPostcode: 'vn-textfield[ng-model="$ctrl.location.code"]', postcode: 'vn-client-create vn-datalist[ng-model="$ctrl.client.postcode"]', city: 'vn-client-create vn-datalist[ng-model="$ctrl.client.city"]', - province: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.provinceFk"]', + province: 'vn-autocomplete[ng-model="$ctrl.client.provinceFk"]', country: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.countryFk"]', + dialogCountry: 'vn-autocomplete[ng-model="$ctrl.province.countryFk"]', userName: 'vn-client-create vn-textfield[ng-model="$ctrl.client.userName"]', email: 'vn-client-create vn-textfield[ng-model="$ctrl.client.email"]', salesPerson: 'vn-client-create vn-autocomplete[ng-model="$ctrl.client.salesPersonFk"]', + saveNewProvicenButton: '#saveProvince', + saveNewCityButton: '#saveCity', + saveNewPoscode: '#savePostcode', createButton: 'vn-client-create button[type=submit]' }, clientDescriptor: { diff --git a/e2e/paths/02-client/01_create_client.spec.js b/e2e/paths/02-client/01_create_client.spec.js index f7a996f48..202f27064 100644 --- a/e2e/paths/02-client/01_create_client.spec.js +++ b/e2e/paths/02-client/01_create_client.spec.js @@ -8,7 +8,7 @@ describe('Client create path', () => { beforeAll(async() => { browser = await getBrowser(); page = browser.page; - await page.loginAndModule('employee', 'client'); + await page.loginAndModule(' deliveryBoss', 'client'); }); afterAll(async() => { @@ -45,14 +45,40 @@ describe('Client create path', () => { expect(message.text).toBe('Some fields are invalid'); }); + it(`should create a new province`, async() => { + await page.waitToClick(selectors.createClientView.addPostCode); + await page.waitToClick(selectors.createClientView.addProvince); + await page.write(selectors.createClientView.newProvinceName, 'Massachusetts'); + await page.autocompleteSearch(selectors.createClientView.dialogCountry, 'España'); + await page.waitToClick(selectors.createClientView.saveNewProvicenButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toBe('The province has been created'); + }); + + it(`should create a new city`, async() => { + await page.waitToClick(selectors.createClientView.addCity); + await page.write(selectors.createClientView.newCityName, 'Boston'); + await page.autocompleteSearch(selectors.createClientView.newCityProvince, 'Massachusetts'); + await page.waitToClick(selectors.createClientView.saveNewCityButton); + const message = await page.waitForSnackbar(); + + expect(message.text).toBe('The city has been created'); + }); + + it(`should create a new post code`, async() => { + await page.write(selectors.createClientView.newPostcode, '61616'); + await page.waitToClick(selectors.createClientView.saveNewPoscode); + + const message = await page.waitForSnackbar(); + + expect(message.text).toBe('The postcode has been created. You can save the data now'); + }); + it(`should attempt to create a new user with all it's data but wrong email`, async() => { await page.write(selectors.createClientView.name, 'Carol Danvers'); await page.write(selectors.createClientView.socialName, 'AVG tax'); await page.write(selectors.createClientView.street, 'Many places'); - await page.autocompleteSearch(selectors.createClientView.country, 'España'); - await page.autocompleteSearch(selectors.createClientView.province, 'Province one'); - await page.write(selectors.createClientView.city, 'Valencia'); - await page.write(selectors.createClientView.postcode, '46000'); await page.clearInput(selectors.createClientView.email); await page.write(selectors.createClientView.email, 'incorrect email format'); await page.waitToClick(selectors.createClientView.createButton); @@ -82,14 +108,14 @@ describe('Client create path', () => { const clientCountry = await page .waitToGetProperty(selectors.createClientView.country, 'value'); - expect(clientCity).toEqual('Valencia'); - expect(clientProvince).toContain('Province one'); + expect(clientCity).toEqual('Boston'); + expect(clientProvince).toContain('Massachusetts'); expect(clientCountry).toEqual('España'); }); it(`should create a new user with all correct data`, async() => { await page.clearInput(selectors.createClientView.postcode); - await page.write(selectors.createClientView.postcode, '46000'); + await page.write(selectors.createClientView.postcode, '61616'); await page.waitToClick(selectors.createClientView.createButton); const message = await page.waitForSnackbar(); diff --git a/e2e/paths/04-item/09_regularize.spec.js b/e2e/paths/04-item/09_regularize.spec.js index fdb1e0184..5825243a0 100644 --- a/e2e/paths/04-item/09_regularize.spec.js +++ b/e2e/paths/04-item/09_regularize.spec.js @@ -32,7 +32,7 @@ describe('Item regularize path', () => { expect(userLocalWarehouse).toContain('Warehouse Four'); }); - it('should search for an specific item', async() => { + it('should search for a specific item', async() => { await page.accessToSearchResult('Ranged weapon pistol 9mm'); await page.waitForState('item.card.summary'); }); diff --git a/e2e/paths/12-entry/04_create.spec.js b/e2e/paths/12-entry/04_create.spec.js index 8cf23813b..20fa6b23d 100644 --- a/e2e/paths/12-entry/04_create.spec.js +++ b/e2e/paths/12-entry/04_create.spec.js @@ -26,7 +26,9 @@ describe('Entry create path', () => { await page.autocompleteSearch(selectors.entryIndex.newEntryCompany, 'ORN'); await page.waitToClick(selectors.entryIndex.saveNewEntry); - await page.waitFor(500); + await page.waitForNavigation({ + waitUntil: 'load', + }); await page.waitForState('entry.card.basicData'); }); }); diff --git a/gulpfile.js b/gulpfile.js index 39dbef71d..6bd2b3542 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -95,9 +95,7 @@ async function launchBackTest(done) { let options = { errorOnFail: false, - config: { - random: false - } + config: {} }; if (argv.ci) { diff --git a/loopback/common/methods/vn-model/specs/crud.spec.js b/loopback/common/methods/vn-model/specs/crud.spec.js index e2d261f98..4aa35c14d 100644 --- a/loopback/common/methods/vn-model/specs/crud.spec.js +++ b/loopback/common/methods/vn-model/specs/crud.spec.js @@ -2,41 +2,37 @@ const app = require('vn-loopback/server/server'); describe('Model crud()', () => { let insertId; - let ItemBarcode = app.models.ItemBarcode; + const barcodeModel = app.models.ItemBarcode; it('should inherit crud method from VnModel', () => { - expect(ItemBarcode.crud).toBeDefined(); + expect(barcodeModel.crud).toBeDefined(); }); - it('should create a new instance', async() => { - let data = {code: '500', itemFk: '1'}; - let creates = [data]; + it('should create, edit and delete an instance', async() => { + let barcodeData = {code: '500', itemFk: '1'}; + let creates = [barcodeData]; - await ItemBarcode.crud(null, null, creates); - let instance = await ItemBarcode.findOne({where: data}); + await barcodeModel.crud(null, null, creates); + let instance = await barcodeModel.findOne({where: barcodeData}); insertId = instance.id; expect(instance).not.toEqual(null); expect(instance.code).toEqual('500'); - }); - it('should update the instance', async() => { let updates = [{ where: {id: insertId}, data: {code: '501', itemFk: 1} }]; - await ItemBarcode.crud(null, updates); - let instance = await ItemBarcode.findById(insertId); + await barcodeModel.crud(null, updates); + let editedInstance = await barcodeModel.findById(insertId); - expect(instance.code).toEqual('501'); - }); + expect(editedInstance.code).toEqual('501'); - it('should delete the created instance', async() => { let deletes = [insertId]; - await ItemBarcode.crud(deletes); - let instance = await ItemBarcode.findById(insertId); + await barcodeModel.crud(deletes); + let deletedInstance = await barcodeModel.findById(insertId); - expect(instance).toEqual(null); + expect(deletedInstance).toEqual(null); }); }); diff --git a/loopback/locale/en.json b/loopback/locale/en.json index 04cc887b6..7243bccd5 100644 --- a/loopback/locale/en.json +++ b/loopback/locale/en.json @@ -57,12 +57,12 @@ "The postcode doesn't exist. Please enter a correct one": "The postcode doesn't exist. Please enter a correct one", "Can't create stowaway for this ticket": "Can't create stowaway for this ticket", "Swift / BIC can't be empty": "Swift / BIC can't be empty", - "MESSAGE_BOUGHT_UNITS": "Bought {{quantity}} units of {{concept}} (#{{itemId}}) for the ticket id [#{{ticketId}}]({{{url}}})", - "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} (#{{clientId}})]({{{url}}}) to *{{credit}} €*", - "MESSAGE_CHANGED_PAYMETHOD": "I have changed the pay method for client [{{clientName}} (#{{clientId}})]({{{url}}})", - "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} (#{{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [#{{ticketId}}]({{{ticketUrl}}})", - "Claim will be picked": "The product from the claim (#{{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked", - "This ticket is not an stowaway anymore": "The ticket id [#{{ticketId}}]({{{ticketUrl}}}) is not an stowaway anymore", + "MESSAGE_BOUGHT_UNITS": "Bought {{quantity}} units of {{concept}} ({{itemId}}) for the ticket id [{{ticketId}}]({{{url}}})", + "MESSAGE_INSURANCE_CHANGE": "I have changed the insurence credit of client [{{clientName}} ({{clientId}})]({{{url}}}) to *{{credit}} €*", + "MESSAGE_CHANGED_PAYMETHOD": "I have changed the pay method for client [{{clientName}} ({{clientId}})]({{{url}}})", + "Sent units from ticket": "I sent *{{quantity}}* units of [{{concept}} ({{itemId}})]({{{itemUrl}}}) to *\"{{nickname}}\"* coming from ticket id [{{ticketId}}]({{{ticketUrl}}})", + "Claim will be picked": "The product from the claim ({{claimId}})]({{{claimUrl}}}) from the client *{{clientName}}* will be picked", + "This ticket is not an stowaway anymore": "The ticket id [{{ticketId}}]({{{ticketUrl}}}) is not an stowaway anymore", "Customs agent is required for a non UEE member": "Customs agent is required for a non UEE member", "Incoterms is required for a non UEE member": "Incoterms is required for a non UEE member", "Client checked as validated despite of duplication": "Client checked as validated despite of duplication from client id {{clientId}}", @@ -70,6 +70,7 @@ "NOT_ZONE_WITH_THIS_PARAMETERS": "There's no zone available for this day", "Created absence": "The worker {{author}} has added an absence of type '{{absenceType}}' to {{employee}} for day {{dated}}.", "Deleted absence": "The worker {{author}} has deleted an absence of type '{{absenceType}}' to {{employee}} for day {{dated}}.", - "I have deleted the ticket id": "I have deleted the ticket id [#{{id}}]({{{url}}})", - "I have restored the ticket id": "I have restored the ticket id [#{{id}}]({{{url}}})" + "I have deleted the ticket id": "I have deleted the ticket id [{{id}}]({{{url}}})", + "I have restored the ticket id": "I have restored the ticket id [{{id}}]({{{url}}})", + "Changed this data from the ticket": "I have changed the data from the ticket [{{ticketId}}]({{{ticketUrl}}}): ```{{{changes}}}```" } \ No newline at end of file diff --git a/loopback/locale/es.json b/loopback/locale/es.json index db17262b4..4a2d48d5e 100644 --- a/loopback/locale/es.json +++ b/loopback/locale/es.json @@ -121,12 +121,12 @@ "Swift / BIC can't be empty": "Swift / BIC no puede estar vacío", "Customs agent is required for a non UEE member": "El agente de aduanas es requerido para los clientes extracomunitarios", "Incoterms is required for a non UEE member": "El incoterms es requerido para los clientes extracomunitarios", - "MESSAGE_BOUGHT_UNITS": "Se ha comprado {{quantity}} unidades de {{concept}} (#{{itemId}}) para el ticket id [#{{ticketId}}]({{{url}}})", + "MESSAGE_BOUGHT_UNITS": "Se ha comprado {{quantity}} unidades de {{concept}} (#{{itemId}}) para el ticket id [{{ticketId}}]({{{url}}})", "MESSAGE_INSURANCE_CHANGE": "He cambiado el crédito asegurado del cliente [{{clientName}} (#{{clientId}})]({{{url}}}) a *{{credit}} €*", "MESSAGE_CHANGED_PAYMETHOD": "He cambiado la forma de pago del cliente [{{clientName}} (#{{clientId}})]({{{url}}})", - "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [#{{ticketId}}]({{{ticketUrl}}})", + "Sent units from ticket": "Envio *{{quantity}}* unidades de [{{concept}} (#{{itemId}})]({{{itemUrl}}}) a *\"{{nickname}}\"* provenientes del ticket id [{{ticketId}}]({{{ticketUrl}}})", "Claim will be picked": "Se recogerá el género de la reclamación (#{{claimId}})]({{{claimUrl}}}) del cliente *{{clientName}}*", - "This ticket is not an stowaway anymore": "El ticket id [#{{ticketId}}]({{{ticketUrl}}}) ha dejado de ser un polizón", + "This ticket is not an stowaway anymore": "El ticket id [{{ticketId}}]({{{ticketUrl}}}) ha dejado de ser un polizón", "Client checked as validated despite of duplication": "Cliente comprobado a pesar de que existe el cliente id {{clientId}}", "ORDER_ROW_UNAVAILABLE": "No hay disponibilidad de este producto", "Distance must be lesser than 1000": "La distancia debe ser inferior a 1000", @@ -146,7 +146,8 @@ "Absence change notification on the labour calendar": "Notificacion de cambio de ausencia en el calendario laboral", "Created absence": "El empleado {{author}} ha añadido una ausencia de tipo '{{absenceType}}' a {{employee}} para el día {{dated}}.", "Deleted absence": "El empleado {{author}} ha eliminado una ausencia de tipo '{{absenceType}}' a {{employee}} del día {{dated}}.", - "I have deleted the ticket id": "He eliminado el ticket id [#{{id}}]({{{url}}})", - "I have restored the ticket id": "He restaurado el ticket id [#{{id}}]({{{url}}})", - "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación" + "I have deleted the ticket id": "He eliminado el ticket id [{{id}}]({{{url}}})", + "I have restored the ticket id": "He restaurado el ticket id [{{id}}]({{{url}}})", + "You can only restore a ticket within the first hour after deletion": "Únicamente puedes restaurar el ticket dentro de la primera hora después de su eliminación", + "Changed this data from the ticket": "He cambiado estos datos del ticket [{{ticketId}}]({{{ticketUrl}}}): ```{{{changes}}}```" } \ No newline at end of file diff --git a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js index 5fecf8bcd..226a07917 100644 --- a/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js +++ b/modules/claim/back/methods/claim-beginning/importToNewRefundTicket.spec.js @@ -1,26 +1,35 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('claimBeginning', () => { + const salesAssistantId = 21; let ticket; let refundTicketSales; let salesInsertedInClaimEnd; - afterAll(async() => { - let promises = []; - promises.push(app.models.Ticket.destroyById(ticket.id)); + const activeCtx = { + accessToken: {userId: salesAssistantId}, + }; + const ctx = {req: activeCtx}; - promises.push(app.models.Ticket.rawSql(`DELETE FROM vn.orderTicket WHERE ticketFk ='${ticket.id}';`)); + afterAll(async done => { + try { + await app.models.Ticket.destroyById(ticket.id); + await app.models.Ticket.rawSql(`DELETE FROM vn.orderTicket WHERE ticketFk ='${ticket.id}';`); + } catch (error) { + console.error(error); + } - await Promise.all(promises); + done(); }); describe('importToNewRefundTicket()', () => { it('should create a new ticket with negative sales and insert the negative sales into claimEnd', async() => { - let ctxOfSalesAssistant = {req: {accessToken: {userId: 21}}}; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); let claimId = 1; - ticket = await app.models.ClaimBeginning.importToNewRefundTicket(ctxOfSalesAssistant, claimId); - - await app.models.Ticket.findById(ticket.id); + ticket = await app.models.ClaimBeginning.importToNewRefundTicket(ctx, claimId); refundTicketSales = await app.models.Sale.find({where: {ticketFk: ticket.id}}); salesInsertedInClaimEnd = await app.models.ClaimEnd.find({where: {claimFk: claimId}}); diff --git a/modules/claim/back/methods/claim/specs/createFromSales.spec.js b/modules/claim/back/methods/claim/specs/createFromSales.spec.js index 5353e640a..e211143f9 100644 --- a/modules/claim/back/methods/claim/specs/createFromSales.spec.js +++ b/modules/claim/back/methods/claim/specs/createFromSales.spec.js @@ -1,14 +1,6 @@ const app = require('vn-loopback/server/server'); describe('Claim createFromSales()', () => { - let createdClaimFk; - - afterAll(async done => { - await app.models.Claim.destroyById(createdClaimFk); - - done(); - }); - const ticketId = 2; const newSale = [{ id: 3, @@ -27,10 +19,16 @@ describe('Claim createFromSales()', () => { expect(claimBeginning.saleFk).toEqual(newSale[0].id); expect(claimBeginning.quantity).toEqual(newSale[0].quantity); - createdClaimFk = claim.id; + const createdClaimId = claim.id; + + // restores + await app.models.Claim.destroyById(createdClaimId); }); it('should not be able to create a claim if exists that sale', async() => { + let claim = await app.models.Claim.createFromSales(ctx, ticketId, newSale); + const createdClaimId = claim.id; + let error; await app.models.Claim.createFromSales(ctx, ticketId, newSale) @@ -40,5 +38,8 @@ describe('Claim createFromSales()', () => { }); expect(error.toString()).toContain(`A claim with that sale already exists`); + + // restores + await app.models.Claim.destroyById(createdClaimId); }); }); diff --git a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js index 55189bd9a..0a280f5ac 100644 --- a/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/regularizeClaim.spec.js @@ -1,6 +1,17 @@ const app = require('vn-loopback/server/server'); describe('regularizeClaim()', () => { + const ctx = { + req: { + accessToken: {userId: 18}, + headers: {origin: 'http://localhost'} + } + }; + ctx.req.__ = (value, params) => { + return params.nickname; + }; + + const chatModel = app.models.Chat; const claimFk = 1; const pendentState = 1; const resolvedState = 3; @@ -10,33 +21,27 @@ describe('regularizeClaim()', () => { let claimEnds = []; let trashTicket; - afterAll(async done => { - let claim = await app.models.Claim.findById(claimFk); - await claim.updateAttributes({ - claimStateFk: pendentState, - hasToPickUp: false - }); - await app.models.Ticket.destroyById(trashTicket.id); + afterEach(async done => { + try { + let claim = await app.models.Claim.findById(claimFk); + await claim.updateAttributes({ + claimStateFk: pendentState, + hasToPickUp: false + }); - claimEnds.forEach(async line => { - await line.destroy(); - }); + for (claimEnd of claimEnds) + await claimEnd.destroy(); + + if (trashTicket) + await app.models.Ticket.destroyById(trashTicket.id); + } catch (error) { + console.error(error); + } done(); }); it('should send a chat message with value "Trash" and then change claim state to resolved', async() => { - const ctx = { - req: { - accessToken: {userId: 18}, - headers: {origin: 'http://localhost'} - } - }; - ctx.req.__ = (value, params) => { - return params.nickname; - }; - - const chatModel = app.models.Chat; spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, { @@ -61,23 +66,16 @@ describe('regularizeClaim()', () => { }); it('should send a chat message with value "Bueno" and then change claim state to resolved', async() => { - const ctx = { - req: { - accessToken: {userId: 18}, - headers: {origin: 'http://localhost'} - } - }; - ctx.req.__ = (value, params) => { - return params.nickname; - }; - - const chatModel = app.models.Chat; spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); - claimEnds.forEach(async claimEnd => { - claimEnd.updateAttributes({claimDestinationFk: okDestination}); + claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, { + claimFk: claimFk, + ticketFk: 1 }); + for (claimEnd of claimEnds) + await claimEnd.updateAttributes({claimDestinationFk: okDestination}); + await app.models.Claim.regularizeClaim(ctx, claimFk); expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); @@ -85,23 +83,16 @@ describe('regularizeClaim()', () => { }); it('should send a chat message to the salesPerson when claim isPickUp is enabled', async() => { - const ctx = { - req: { - accessToken: {userId: 18}, - headers: {origin: 'http://localhost'} - } - }; - ctx.req.__ = (value, params) => { - return params.nickname; - }; - - const chatModel = app.models.Chat; spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); - claimEnds.forEach(async claimEnd => { - claimEnd.updateAttributes({claimDestinationFk: okDestination}); + claimEnds = await app.models.ClaimEnd.importTicketSales(ctx, { + claimFk: claimFk, + ticketFk: 1 }); + for (claimEnd of claimEnds) + await claimEnd.updateAttributes({claimDestinationFk: okDestination}); + await app.models.Claim.regularizeClaim(ctx, claimFk); expect(chatModel.sendCheckingPresence).toHaveBeenCalledWith(ctx, 18, 'Bueno'); diff --git a/modules/claim/back/methods/claim/specs/updateClaim.spec.js b/modules/claim/back/methods/claim/specs/updateClaim.spec.js index b6ae23281..f1ee99eac 100644 --- a/modules/claim/back/methods/claim/specs/updateClaim.spec.js +++ b/modules/claim/back/methods/claim/specs/updateClaim.spec.js @@ -2,8 +2,7 @@ const app = require('vn-loopback/server/server'); describe('Update Claim', () => { let newDate = new Date(); - let newInstance; - let original = { + const originalData = { ticketFk: 3, clientFk: 101, ticketCreated: newDate, @@ -14,22 +13,11 @@ describe('Update Claim', () => { observation: 'observation' }; - beforeAll(async done => { - newInstance = await app.models.Claim.create(original); - - done(); - }); - - afterAll(async done => { - await app.models.Claim.destroyById(newInstance.id); - - done(); - }); - it(`should throw an error as the user doesn't have rights`, async() => { + let newClaim = await app.models.Claim.create(originalData); const forbiddenState = 3; const salesPersonId = 18; - let ctx = { + const ctx = { req: { accessToken: { userId: salesPersonId @@ -40,18 +28,23 @@ describe('Update Claim', () => { observation: 'valid observation' } }; - await app.models.Claim.updateClaim(ctx, newInstance.id) + await app.models.Claim.updateClaim(ctx, newClaim.id) .catch(e => { error = e; }); expect(error.message).toEqual(`You don't have enough privileges to change that field`); + + // restores + await app.models.Claim.destroyById(newClaim.id); }); it(`should success to update the claim within privileges `, async() => { + let newClaim = await app.models.Claim.create(originalData); + const correctState = 4; const salesPersonId = 18; - let ctx = { + const ctx = { req: { accessToken: { userId: salesPersonId @@ -63,14 +56,18 @@ describe('Update Claim', () => { hasToPickUp: false } }; - await app.models.Claim.updateClaim(ctx, newInstance.id); + await app.models.Claim.updateClaim(ctx, newClaim.id,); - let claimUpdated = await app.models.Claim.findById(newInstance.id); + let updatedClaim = await app.models.Claim.findById(newClaim.id); - expect(claimUpdated.observation).toEqual(ctx.args.observation); + expect(updatedClaim.observation).toEqual(ctx.args.observation); + + // restores + await app.models.Claim.destroyById(newClaim.id); }); it('should change some sensible fields as salesAssistant', async() => { + let newClaim = await app.models.Claim.create(originalData); const chatModel = app.models.Chat; spyOn(chatModel, 'sendCheckingPresence').and.callThrough(); @@ -90,13 +87,16 @@ describe('Update Claim', () => { ctx.req.__ = (value, params) => { return params.nickname; }; - await app.models.Claim.updateClaim(ctx, newInstance.id); + await app.models.Claim.updateClaim(ctx, newClaim.id); - let claimUpdated = await app.models.Claim.findById(newInstance.id); + let updatedClaim = await app.models.Claim.findById(newClaim.id); - expect(claimUpdated.observation).toEqual(ctx.args.observation); - expect(claimUpdated.claimStateFk).toEqual(ctx.args.claimStateFk); - expect(claimUpdated.workerFk).toEqual(ctx.args.workerFk); + expect(updatedClaim.observation).toEqual(ctx.args.observation); + expect(updatedClaim.claimStateFk).toEqual(ctx.args.claimStateFk); + expect(updatedClaim.workerFk).toEqual(ctx.args.workerFk); expect(chatModel.sendCheckingPresence).toHaveBeenCalled(); + + // restores + await app.models.Claim.destroyById(newClaim.id); }); }); diff --git a/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js b/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js index 5dbf6cb48..8dee7e4c6 100644 --- a/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js +++ b/modules/client/back/methods/client/specs/activeWorkersWithRole.spec.js @@ -7,7 +7,7 @@ describe('Client activeWorkersWithRole', () => { let isSalesPerson = await app.models.Account.hasRole(result[0].id, 'salesPerson'); - expect(result.length).toEqual(16); + expect(result.length).toEqual(17); expect(isSalesPerson).toBeTruthy(); }); diff --git a/modules/client/back/methods/client/specs/createAddress.spec.js b/modules/client/back/methods/client/specs/createAddress.spec.js index 29f9e145f..8b2d1f5e2 100644 --- a/modules/client/back/methods/client/specs/createAddress.spec.js +++ b/modules/client/back/methods/client/specs/createAddress.spec.js @@ -5,15 +5,6 @@ describe('Address createAddress', () => { const provinceId = 5; const incotermsId = 'FAS'; const customAgentOneId = 1; - let address; - let client; - - afterAll(async done => { - await client.updateAttributes({defaultAddressFk: 1}); - await address.destroy(); - - done(); - }); it('should throw a non uee member error if no incoterms is defined', async() => { const expectedResult = 'My edited address'; @@ -49,7 +40,6 @@ describe('Address createAddress', () => { } }; - try { await app.models.Client.createAddress(ctx, clientId); } catch (e) { @@ -61,7 +51,7 @@ describe('Address createAddress', () => { }); it('should verify that client defaultAddressFk is untainted', async() => { - client = await app.models.Client.findById(clientId); + const client = await app.models.Client.findById(clientId); expect(client.defaultAddressFk).toEqual(1); }); @@ -79,9 +69,13 @@ describe('Address createAddress', () => { } }; - address = await app.models.Client.createAddress(ctx, clientId); - client = await app.models.Client.findById(clientId); + const address = await app.models.Client.createAddress(ctx, clientId); + const client = await app.models.Client.findById(clientId); expect(client.defaultAddressFk).toEqual(address.id); + + // restores + await client.updateAttributes({defaultAddressFk: 1}); + await address.destroy(); }); }); diff --git a/modules/client/back/methods/client/specs/createWithUser.spec.js b/modules/client/back/methods/client/specs/createWithUser.spec.js index 71a6e7b39..35de8b300 100644 --- a/modules/client/back/methods/client/specs/createWithUser.spec.js +++ b/modules/client/back/methods/client/specs/createWithUser.spec.js @@ -4,13 +4,20 @@ describe('Client Create', () => { const clientName = 'Wade'; const AccountName = 'Deadpool'; - afterAll(async done => { + afterEach(async done => { let address = await app.models.Address.findOne({where: {nickname: clientName}}); let client = await app.models.Client.findOne({where: {name: clientName}}); let account = await app.models.Account.findOne({where: {name: AccountName}}); - await app.models.Address.destroyById(address.id); - await app.models.Client.destroyById(client.id); - await app.models.Account.destroyById(account.id); + + if (address && client && account) { + try { + await app.models.Address.destroyById(address.id); + await app.models.Client.destroyById(client.id); + await app.models.Account.destroyById(account.id); + } catch (error) { + console.error(error); + } + } done(); }); @@ -46,13 +53,8 @@ describe('Client Create', () => { expect(client.socialName).toEqual(newAccount.socialName); }); - it('should find an existing account', async() => { - let account = await app.models.Account.findOne({where: {name: newAccount.userName}}); - - expect(account.name).toEqual(newAccount.userName); - }); - it('should not be able to create a user if exists', async() => { + await app.models.Client.createWithUser(newAccount); try { let client = await app.models.Client.createWithUser(newAccount); diff --git a/modules/client/back/methods/client/specs/listWorkers.spec.js b/modules/client/back/methods/client/specs/listWorkers.spec.js index 329a27aa5..68eb84273 100644 --- a/modules/client/back/methods/client/specs/listWorkers.spec.js +++ b/modules/client/back/methods/client/specs/listWorkers.spec.js @@ -6,7 +6,7 @@ describe('Client listWorkers', () => { .then(result => { let amountOfEmployees = Object.keys(result).length; - expect(amountOfEmployees).toEqual(51); + expect(amountOfEmployees).toEqual(53); done(); }) .catch(done.fail); diff --git a/modules/client/back/methods/client/specs/updateAddress.spec.js b/modules/client/back/methods/client/specs/updateAddress.spec.js index 7dca0883e..6855d8e18 100644 --- a/modules/client/back/methods/client/specs/updateAddress.spec.js +++ b/modules/client/back/methods/client/specs/updateAddress.spec.js @@ -6,26 +6,11 @@ describe('Address updateAddress', () => { const provinceId = 5; const incotermsId = 'FAS'; const customAgentOneId = 1; - let oldAddress; - let address; - afterAll(async done => { - await address.updateAttributes({ - nickname: oldAddress.nickname, - provinceFk: 1, - customsAgentFk: null, - incotermsFk: null - }); - - done(); - }); - - it('should throw a non uee member error if no incoterms is defined', async() => { - const expectedResult = 'My edited address'; + it('should throw the non uee member error if no incoterms is defined', async() => { const ctx = { args: { provinceFk: provinceId, - nickname: expectedResult, customsAgentFk: customAgentOneId } }; @@ -41,16 +26,13 @@ describe('Address updateAddress', () => { }); it('should throw a non uee member error if no customsAgent is defined', async() => { - const expectedResult = 'My edited address'; const ctx = { args: { provinceFk: provinceId, - nickname: expectedResult, incotermsFk: incotermsId } }; - try { await app.models.Client.updateAddress(ctx, clientId, addressId); } catch (e) { @@ -72,13 +54,21 @@ describe('Address updateAddress', () => { } }; - oldAddress = await app.models.Address.findById(addressId); + let oldAddress = await app.models.Address.findById(addressId); await app.models.Client.updateAddress(ctx, clientId, addressId); - address = await app.models.Address.findById(addressId); + let address = await app.models.Address.findById(addressId); expect(address.nickname).toEqual(expectedResult); + + // restores + await address.updateAttributes({ + nickname: oldAddress.nickname, + provinceFk: oldAddress.provinceFk, + customsAgentFk: null, + incotermsFk: null + }); }); it('should update the address', async() => { @@ -96,5 +86,13 @@ describe('Address updateAddress', () => { address = await app.models.Address.findById(addressId); expect(address.nickname).toEqual(expectedResult); + + // restores + await address.updateAttributes({ + nickname: oldAddress.nickname, + provinceFk: oldAddress.provinceFk, + customsAgentFk: null, + incotermsFk: null + }); }); }); diff --git a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js index 21abddb81..596c9b140 100644 --- a/modules/client/back/methods/credit-classification/createWithInsurance.spec.js +++ b/modules/client/back/methods/credit-classification/createWithInsurance.spec.js @@ -2,7 +2,6 @@ const app = require('vn-loopback/server/server'); const LoopBackContext = require('loopback-context'); describe('Client createWithInsurance', () => { - let classificationId; const activeCtx = { accessToken: {userId: 101}, http: { @@ -16,12 +15,6 @@ describe('Client createWithInsurance', () => { return value; }; - afterAll(async done => { - await app.models.CreditClassification.destroyById(classificationId); - - done(); - }); - it('should verify the classifications and insurances are untainted', async() => { let classifications = await app.models.CreditClassification.find(); let insurances = await app.models.CreditInsurance.find(); @@ -57,8 +50,6 @@ describe('Client createWithInsurance', () => { }); let result = await app.models.CreditClassification.createWithInsurance(data, ctx); - classificationId = result.id; - expect(result.client).toEqual(101); let classifications = await app.models.CreditClassification.find(); @@ -66,5 +57,8 @@ describe('Client createWithInsurance', () => { expect(classifications.length).toEqual(6); expect(insurances.length).toEqual(4); + + // restore + await app.models.CreditClassification.destroyById(result.id); }); }); diff --git a/modules/client/front/address/create/index.html b/modules/client/front/address/create/index.html index d6b5bcf8e..233afa04b 100644 --- a/modules/client/front/address/create/index.html +++ b/modules/client/front/address/create/index.html @@ -153,9 +153,9 @@ - - + - - + - -
@@ -82,7 +76,7 @@ label="City" ng-model="$ctrl.client.city" selection="$ctrl.town" - data="townsLocation" + url="Towns/location" fields="['id', 'name', 'provinceFk']" value-field="name"> @@ -136,7 +130,7 @@ - - \ No newline at end of file + \ No newline at end of file diff --git a/modules/client/front/create/index.js b/modules/client/front/create/index.js index d8ded6560..1aa21c91e 100644 --- a/modules/client/front/create/index.js +++ b/modules/client/front/create/index.js @@ -81,6 +81,9 @@ export default class Controller extends Section { onResponse(response) { this.client.postcode = response.code; + this.client.city = response.city; + this.client.provinceFk = response.provinceFk; + this.client.countryFk = response.countryFk; } } diff --git a/modules/client/front/fiscal-data/index.html b/modules/client/front/fiscal-data/index.html index b3789b34a..70221dbd0 100644 --- a/modules/client/front/fiscal-data/index.html +++ b/modules/client/front/fiscal-data/index.html @@ -173,7 +173,7 @@ on-accept="$ctrl.onAcceptDuplication()"> - - \ No newline at end of file + \ No newline at end of file diff --git a/modules/client/front/fiscal-data/index.js b/modules/client/front/fiscal-data/index.js index 30c7d7656..58b22537c 100644 --- a/modules/client/front/fiscal-data/index.js +++ b/modules/client/front/fiscal-data/index.js @@ -159,6 +159,9 @@ export default class Controller extends Section { onResponse(response) { this.client.postcode = response.code; + this.client.city = response.city; + this.client.provinceFk = response.provinceFk; + this.client.countryFk = response.countryFk; } } diff --git a/modules/client/front/index.js b/modules/client/front/index.js index 7df6f7b10..758b94e3f 100644 --- a/modules/client/front/index.js +++ b/modules/client/front/index.js @@ -37,6 +37,8 @@ import './web-payment'; import './log'; import './sms'; import './postcode'; +import './postcode/province'; +import './postcode/city'; import './dms/index'; import './dms/create'; import './dms/edit'; diff --git a/modules/client/front/postcode/city/index.html b/modules/client/front/postcode/city/index.html new file mode 100644 index 000000000..a83505222 --- /dev/null +++ b/modules/client/front/postcode/city/index.html @@ -0,0 +1,27 @@ + + +

Please, ensure you put the correct data!

+ + + + + + +
+ + + + +
\ No newline at end of file diff --git a/modules/client/front/postcode/city/index.js b/modules/client/front/postcode/city/index.js new file mode 100644 index 000000000..c4c110745 --- /dev/null +++ b/modules/client/front/postcode/city/index.js @@ -0,0 +1,37 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { // Comprobar funcionamiento añadir ciudad + open($event) { + if ($event.defaultPrevented) return; + + this.$.cityDialog.show(); + $event.preventDefault(); + } + + onAccept() { + try { + if (!this.city.name) + throw new Error(`The city name can't be empty`); + if (!this.city.provinceFk) + throw new Error(`The province can't be empty`); + + this.$http.patch(`towns`, this.city).then(res => { + this.vnApp.showMessage(this.$t('The city has been created')); + this.emit('response', {$response: res.data}); + }); + } catch (e) { + this.vnApp.showError(this.$t(e.message)); + return false; + } + return true; + } +} + +ngModule.vnComponent('vnGeoCity', { + template: require('./index.html'), + controller: Controller, + bindings: { + data: '<', + } +}); diff --git a/modules/client/front/postcode/city/index.spec.js b/modules/client/front/postcode/city/index.spec.js new file mode 100644 index 000000000..c6cd8732f --- /dev/null +++ b/modules/client/front/postcode/city/index.spec.js @@ -0,0 +1,34 @@ +import './index'; + +describe('Client', () => { + describe('Component vnGeoCity', () => { + let controller; + let $httpBackend; + let $scope; + + beforeEach(ngModule('client')); + + beforeEach(inject(($componentController, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + const $element = angular.element(''); + controller = $componentController('vnGeoCity', {$element, $scope}); + controller.client = {id: 101}; + })); + + describe('onAccept()', () => { + it('should perform a POST query and show a success snackbar', () => { + let params = {name: 'Gotham City', provinceFk: 1}; + controller.city = {name: 'Gotham City', provinceFk: 1}; + + jest.spyOn(controller.vnApp, 'showMessage'); + $httpBackend.expect('PATCH', `towns`, params).respond(200, params); + + controller.onAccept(); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The city has been created'); + }); + }); + }); +}); diff --git a/modules/client/front/postcode/index.html b/modules/client/front/postcode/index.html index ade256459..8f9f35eb8 100644 --- a/modules/client/front/postcode/index.html +++ b/modules/client/front/postcode/index.html @@ -11,7 +11,7 @@ vn-focus vn-id="postcode" label="Postcode" - ng-model="$ctrl.data.code" + ng-model="$ctrl.location.code" required="true"> + + + +
+ + + + - + -
\ No newline at end of file +
+ + + + + + \ No newline at end of file diff --git a/modules/client/front/postcode/index.js b/modules/client/front/postcode/index.js index aca7a44d3..2c44ae13f 100644 --- a/modules/client/front/postcode/index.js +++ b/modules/client/front/postcode/index.js @@ -15,8 +15,9 @@ class Controller extends Component { const province = selection.province; const country = province.country; - this.data.provinceFk = province.id; - this.data.countryFk = country.id; + this.location.city = selection.name; + this.location.provinceFk = province.id; + this.location.countryFk = country.id; } open() { @@ -24,19 +25,35 @@ class Controller extends Component { } onOpen() { + this.location = {}; this.$.postcode.focus(); } + onProvinceResponse(response) { + this.location.provinceFk = response.id; + this.location.countryFk = response.countryFk; + } + + onCityResponse(response) { + this.location.townFk = response.id; + this.location.provinceFk = response.provinceFk; + this.location.countryFk = response.countryFk; + } + onAccept() { try { - if (!this.data.code) + if (!this.location.code) throw new Error(`The postcode can't be empty`); - if (!this.data.townFk) + if (!this.location.townFk) throw new Error(`The town can't be empty`); + if (!this.location.provinceFk) + throw new Error(`The province can't be empty`); + if (!this.location.provinceFk) + throw new Error(`The country can't be empty`); - this.$http.patch(`postcodes`, this.data).then(res => { - this.vnApp.showMessage(this.$t('The postcode has been saved')); - this.emit('response', {$response: res.data}); + this.$http.patch(`postcodes`, this.location).then(() => { + this.vnApp.showMessage(this.$t('The postcode has been created. You can save the data now')); + this.emit('response', {$response: this.location}); }); } catch (e) { this.vnApp.showError(this.$t(e.message)); @@ -46,7 +63,7 @@ class Controller extends Component { } } -ngModule.vnComponent('vnClientPostcode', { +ngModule.vnComponent('vnGeoPostcode', { template: require('./index.html'), controller: Controller, bindings: { diff --git a/modules/client/front/postcode/index.spec.js b/modules/client/front/postcode/index.spec.js index 8778fd9b0..607866f44 100644 --- a/modules/client/front/postcode/index.spec.js +++ b/modules/client/front/postcode/index.spec.js @@ -1,7 +1,7 @@ import './index'; describe('Client', () => { - describe('Component vnClientPostcode', () => { + describe('Component vnGeoPostcode', () => { let controller; let $httpBackend; let $scope; @@ -12,14 +12,14 @@ describe('Client', () => { $httpBackend = _$httpBackend_; $scope = $rootScope.$new(); const $element = angular.element(''); - controller = $componentController('vnClientPostcode', {$element, $scope}); + controller = $componentController('vnGeoPostcode', {$element, $scope}); controller.client = {id: 101}; })); describe('onAccept()', () => { it('should perform a POST query and show a success snackbar', () => { let params = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; - controller.data = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; + controller.location = {townFk: 1, provinceFk: 1, countryFk: 1, code: '46460'}; jest.spyOn(controller.vnApp, 'showMessage'); $httpBackend.expect('PATCH', `postcodes`, params).respond(200, params); @@ -27,7 +27,7 @@ describe('Client', () => { controller.onAccept(); $httpBackend.flush(); - expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The postcode has been saved'); + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The postcode has been created. You can save the data now'); }); }); }); diff --git a/modules/client/front/postcode/locale/es.yml b/modules/client/front/postcode/locale/es.yml index ab8b0fc21..782690e88 100644 --- a/modules/client/front/postcode/locale/es.yml +++ b/modules/client/front/postcode/locale/es.yml @@ -1,5 +1,11 @@ New postcode: Nuevo código postal +New city: Nueva ciudad +New province: Nueva provincia Please, ensure you put the correct data!: ¡Por favor, asegúrate de poner los datos correctos! The postcode can't be empty: El código postal no puede quedar vacío The town can't be empty: La población no puede quedar vacía -The postcode has been saved: El código postal ha sido guardado \ No newline at end of file +The province can't be empty: La provincia no puede quedar vacía +The country can't be empty: El país no puede quedar vacío +The postcode has been created. You can save the data now: Se ha creado el código postal. Ahora puedes guardar los datos +The city has been created: Se ha creado la ciudad +The province has been created: Se ha creado la provincia \ No newline at end of file diff --git a/modules/client/front/postcode/province/index.html b/modules/client/front/postcode/province/index.html new file mode 100644 index 000000000..03836901c --- /dev/null +++ b/modules/client/front/postcode/province/index.html @@ -0,0 +1,27 @@ + + +

Please, ensure you put the correct data!

+ + + + + + +
+ + + + +
\ No newline at end of file diff --git a/modules/client/front/postcode/province/index.js b/modules/client/front/postcode/province/index.js new file mode 100644 index 000000000..6a0193d94 --- /dev/null +++ b/modules/client/front/postcode/province/index.js @@ -0,0 +1,37 @@ +import ngModule from '../../module'; +import Component from 'core/lib/component'; + +class Controller extends Component { + open($event) { + if ($event.defaultPrevented) return; + + this.$.provinceDialog.show(); + $event.preventDefault(); + } + + onAccept() { + try { + if (!this.province.name) + throw new Error(`The province name can't be empty`); + if (!this.province.countryFk) + throw new Error(`The country can't be empty`); + + this.$http.patch(`provinces`, this.province).then(res => { + this.vnApp.showMessage(this.$t('The province has been created')); + this.emit('response', {$response: res.data}); + }); + } catch (e) { + this.vnApp.showError(this.$t(e.message)); + return false; + } + return true; + } +} + +ngModule.vnComponent('vnGeoProvince', { + template: require('./index.html'), + controller: Controller, + bindings: { + data: '<', + } +}); diff --git a/modules/client/front/postcode/province/index.spec.js b/modules/client/front/postcode/province/index.spec.js new file mode 100644 index 000000000..c28ecb489 --- /dev/null +++ b/modules/client/front/postcode/province/index.spec.js @@ -0,0 +1,34 @@ +import './index'; + +describe('Client', () => { + describe('Component vnGeoProvince', () => { + let controller; + let $httpBackend; + let $scope; + + beforeEach(ngModule('client')); + + beforeEach(inject(($componentController, _$httpBackend_, $rootScope) => { + $httpBackend = _$httpBackend_; + $scope = $rootScope.$new(); + const $element = angular.element(''); + controller = $componentController('vnGeoProvince', {$element, $scope}); + controller.client = {id: 101}; + })); + + describe('onAccept()', () => { + it('should perform a POST query and show a success snackbar', () => { + let params = {name: 'New Jersey', countryFk: 1}; + controller.province = {name: 'New Jersey', countryFk: 1}; + + jest.spyOn(controller.vnApp, 'showMessage'); + $httpBackend.expect('PATCH', `provinces`, params).respond(200, params); + + controller.onAccept(); + $httpBackend.flush(); + + expect(controller.vnApp.showMessage).toHaveBeenCalledWith('The province has been created'); + }); + }); + }); +}); diff --git a/modules/client/front/postcode/style.scss b/modules/client/front/postcode/style.scss index b9ef984b7..51e181357 100644 --- a/modules/client/front/postcode/style.scss +++ b/modules/client/front/postcode/style.scss @@ -1,6 +1,6 @@ @import "variables"; -vn-client-postcode { +vn-geo-postcode { vn-dialog { p { color: $color-alert diff --git a/modules/entry/back/methods/entry/specs/latestBuysFilter.spec.js b/modules/entry/back/methods/entry/specs/latestBuysFilter.spec.js index ba18fcf57..f386894dd 100644 --- a/modules/entry/back/methods/entry/specs/latestBuysFilter.spec.js +++ b/modules/entry/back/methods/entry/specs/latestBuysFilter.spec.js @@ -137,3 +137,4 @@ describe('Buy latests buys filter()', () => { expect(results.length).toBe(1); }); }); + diff --git a/modules/entry/front/summary/index.html b/modules/entry/front/summary/index.html index 67753e644..d97adfdd7 100644 --- a/modules/entry/front/summary/index.html +++ b/modules/entry/front/summary/index.html @@ -143,6 +143,9 @@ + + + diff --git a/modules/entry/front/summary/style.scss b/modules/entry/front/summary/style.scss index 27d361056..94e38c419 100644 --- a/modules/entry/front/summary/style.scss +++ b/modules/entry/front/summary/style.scss @@ -8,8 +8,18 @@ vn-entry-summary .summary { background-color: lighten($color-marginal, 10%); } - tbody { - border: 2px solid $color-marginal; + tbody tr:nth-child(1) { + border-top: 1px solid $color-marginal; + } + + tbody tr:nth-child(1), + tbody tr:nth-child(2) { + border-left: 1px solid $color-marginal; + border-right: 1px solid $color-marginal + } + + tbody tr:nth-child(3) { + height: inherit } tr { diff --git a/modules/invoiceOut/back/methods/invoiceOut/book.js b/modules/invoiceOut/back/methods/invoiceOut/book.js index a3a909f2a..358de8fd5 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/book.js +++ b/modules/invoiceOut/back/methods/invoiceOut/book.js @@ -1,7 +1,7 @@ module.exports = Self => { Self.remoteMethod('book', { - description: 'Book a invoiceOut', + description: 'Book an invoiceOut', accessType: 'WRITE', accepts: { arg: 'ref', diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js index 85821773c..0f0a7bade 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/book.spec.js @@ -2,38 +2,31 @@ const app = require('vn-loopback/server/server'); describe('invoiceOut book()', () => { const invoiceOutId = 5; - let bookedDate; - let OriginalInvoiceOut; - let updatedInvoiceOut; - - afterAll(async done => { - updatedInvoiceOut.updateAttributes({ - booked: OriginalInvoiceOut.booked, - hasPdf: OriginalInvoiceOut.hasPdf, - amount: OriginalInvoiceOut.amount - }); - - done(); - }); it('should check that invoice out booked is untainted', async() => { const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - bookedDate = invoiceOut.booked; - expect(invoiceOut.booked).toBeDefined(); expect(invoiceOut.hasPdf).toBeTruthy(); }); - it(`should confirm the book property have been updated`, async() => { - OriginalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - let invoiceOutRef = OriginalInvoiceOut.ref; + it('should update the booked property', async() => { + const originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + const bookedDate = originalInvoiceOut.booked; + const invoiceOutRef = originalInvoiceOut.ref; await app.models.InvoiceOut.book(invoiceOutRef); - updatedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); + const updatedInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); expect(updatedInvoiceOut.booked).not.toEqual(bookedDate); expect(updatedInvoiceOut.hasPdf).toBeFalsy(); + + // restores + await updatedInvoiceOut.updateAttributes({ + booked: originalInvoiceOut.booked, + hasPdf: originalInvoiceOut.hasPdf, + amount: originalInvoiceOut.amount + }); }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js index 0d272a81d..cea61eaf9 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/delete.spec.js @@ -1,20 +1,14 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('invoiceOut delete()', () => { const invoiceOutId = 2; let originalInvoiceOut; let originalTicket; - - afterAll(async done => { - const newInvoiceOut = await app.models.InvoiceOut.create(originalInvoiceOut); - await newInvoiceOut.updateAttribute('ref', originalInvoiceOut.ref); - - const promises = []; - promises.push(originalTicket.updateAttribute('refFk', newInvoiceOut.ref)); - Promise.all(promises); - - done(); - }); + const userId = 106; + const activeCtx = { + accessToken: {userId: userId}, + }; it('should check that there is one ticket in the target invoiceOut', async() => { const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); @@ -25,6 +19,9 @@ describe('invoiceOut delete()', () => { }); it(`should delete the target invoiceOut then check the ticket doesn't have a refFk anymore`, async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); originalInvoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); await app.models.InvoiceOut.delete(invoiceOutId); originalTicket = await app.models.Ticket.findById(3); @@ -32,5 +29,10 @@ describe('invoiceOut delete()', () => { expect(deletedInvoiceOut).toBeNull(); expect(originalTicket.refFk).toBeNull(); + + // restores + const restoredInvoiceOut = await app.models.InvoiceOut.create(originalInvoiceOut); + await restoredInvoiceOut.updateAttribute('ref', originalInvoiceOut.ref); + await originalTicket.updateAttribute('refFk', restoredInvoiceOut.ref); }); }); diff --git a/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js b/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js index 43cb9023b..2d495ea0e 100644 --- a/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js +++ b/modules/invoiceOut/back/methods/invoiceOut/specs/regenerate.spec.js @@ -4,16 +4,6 @@ describe('invoiceOut regenerate()', () => { const invoiceReportFk = 30; const invoiceOutId = 1; - afterAll(async done => { - const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); - await invoiceOut.updateAttributes({hasPdf: true}); - await app.models.InvoiceOut.rawSql(` - DELETE FROM vn.printServerQueue - WHERE reportFk = ?`, [invoiceReportFk]); - - done(); - }); - it('should check that the invoice has a PDF and is not in print generation queue', async() => { const invoiceOut = await app.models.InvoiceOut.findById(invoiceOutId); const [queue] = await app.models.InvoiceOut.rawSql(` @@ -35,5 +25,12 @@ describe('invoiceOut regenerate()', () => { expect(invoiceOut.hasPdf).toBeFalsy(); expect(queue.total).toEqual(1); + + // restores + const invoiceOutToRestore = await app.models.InvoiceOut.findById(invoiceOutId); + await invoiceOutToRestore.updateAttributes({hasPdf: true}); + await app.models.InvoiceOut.rawSql(` + DELETE FROM vn.printServerQueue + WHERE reportFk = ?`, [invoiceReportFk]); }); }); diff --git a/modules/item/back/methods/item/specs/getWasteDetail.spec.js b/modules/item/back/methods/item/specs/getWasteDetail.spec.js index b5556e154..5f11513e1 100644 --- a/modules/item/back/methods/item/specs/getWasteDetail.spec.js +++ b/modules/item/back/methods/item/specs/getWasteDetail.spec.js @@ -2,22 +2,12 @@ const app = require('vn-loopback/server/server'); describe('item getWasteDetail()', () => { it('should check for the waste breakdown for every worker', async() => { - let result = await app.models.Item.getWasteDetail(); + const result = await app.models.Item.getWasteDetail(); - const firstBuyer = result[0].buyer; - const firstBuyerLines = result[0].lines; - const secondBuyer = result[1].buyer; - const secondBuyerLines = result[1].lines; - const thirdBuyer = result[2].buyer; - const thirdBuyerLines = result[2].lines; + const length = result.length; + const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - expect(result.length).toEqual(3); - expect(firstBuyer).toEqual('CharlesXavier'); - expect(firstBuyerLines.length).toEqual(4); - expect(secondBuyer).toEqual('HankPym'); - expect(secondBuyerLines.length).toEqual(3); - - expect(thirdBuyer).toEqual('DavidCharlesHaller'); - expect(thirdBuyerLines.length).toEqual(3); + expect(anyResult.buyer).toMatch(/(CharlesXavier|HankPym|DavidCharlesHaller)/); + expect(anyResult.lines.length).toBeGreaterThanOrEqual(3); }); }); diff --git a/modules/item/back/methods/item/specs/new.spec.js b/modules/item/back/methods/item/specs/new.spec.js index 007178c97..da2d99bb6 100644 --- a/modules/item/back/methods/item/specs/new.spec.js +++ b/modules/item/back/methods/item/specs/new.spec.js @@ -4,12 +4,15 @@ describe('item new()', () => { let item; afterAll(async done => { - let sql = 'DELETE FROM vn.itemLog WHERE originFk = ?'; - await app.models.Item.rawSql(sql, [item.id]); - - sql = 'DELETE FROM vn.item WHERE id = ?'; - await app.models.Item.rawSql(sql, [item.id]); + try { + let sql = 'DELETE FROM vn.itemLog WHERE originFk = ?'; + await app.models.Item.rawSql(sql, [item.id]); + sql = 'DELETE FROM vn.item WHERE id = ?'; + await app.models.Item.rawSql(sql, [item.id]); + } catch (error) { + console.error(error); + } done(); }); diff --git a/modules/item/back/methods/item/specs/updateTaxes.spec.js b/modules/item/back/methods/item/specs/updateTaxes.spec.js index c488cbc5f..7ed6fa29a 100644 --- a/modules/item/back/methods/item/specs/updateTaxes.spec.js +++ b/modules/item/back/methods/item/specs/updateTaxes.spec.js @@ -1,13 +1,7 @@ const app = require('vn-loopback/server/server'); describe('item updateTaxes()', () => { - afterAll(async done => { - let taxesInFixtures = [{id: 3, taxClassFk: 1}]; - - await app.models.Item.updateTaxes(taxesInFixtures); - - done(); - }); + let taxesInFixtures = [{id: 3, taxClassFk: 1}]; it('should throw an error if the taxClassFk is blank', async() => { let error; @@ -29,14 +23,12 @@ describe('item updateTaxes()', () => { let taxes = [{id: 3, taxClassFk: 2}]; - let result = await app.models.Item.updateTaxes(taxes); - - expect(result).toBeTruthy(); - }); - - it('should confirm the tax class was updated', async() => { - let taxCountry = await app.models.ItemTaxCountry.findById(3); + await app.models.Item.updateTaxes(taxes); + taxCountry = await app.models.ItemTaxCountry.findById(3); expect(taxCountry.taxClassFk).toEqual(2); + + // restores + await app.models.Item.updateTaxes(taxesInFixtures); }); }); diff --git a/modules/order/back/methods/order/filter.js b/modules/order/back/methods/order/filter.js index 66b4244d0..9f5977cd5 100644 --- a/modules/order/back/methods/order/filter.js +++ b/modules/order/back/methods/order/filter.js @@ -138,34 +138,34 @@ module.exports = Self => { stmt = new ParameterizedSQL( `SELECT - o.id, - o.total, - o.date_send landed, - o.date_make created, - o.customer_id clientFk, - o.agency_id agencyModeFk, - o.address_id addressFk, - o.company_id companyFk, - o.source_app sourceApp, - o.confirmed isConfirmed, - c.name clientName, - c.salesPersonFk, - u.nickname workerNickname, - u.name name, - co.code companyCode, - zed.zoneFk, - zed.hourTheoretical, - zed.hourEffective - FROM hedera.order o - LEFT JOIN address a ON a.id = o.address_id - LEFT JOIN agencyMode am ON am.id = o.agency_id - LEFT JOIN client c ON c.id = o.customer_id - LEFT JOIN worker wk ON wk.id = c.salesPersonFk - LEFT JOIN account.user u ON u.id = wk.userFk - LEFT JOIN company co ON co.id = o.company_id - LEFT JOIN orderTicket ot ON ot.orderFk = o.id - LEFT JOIN ticket t ON t.id = ot.ticketFk - LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); + o.id, + o.total, + o.date_send landed, + o.date_make created, + o.customer_id clientFk, + o.agency_id agencyModeFk, + o.address_id addressFk, + o.company_id companyFk, + o.source_app sourceApp, + o.confirmed isConfirmed, + c.name clientName, + c.salesPersonFk, + u.nickname workerNickname, + u.name name, + co.code companyCode, + zed.zoneFk, + zed.hourTheoretical, + zed.hourEffective + FROM hedera.order o + LEFT JOIN address a ON a.id = o.address_id + LEFT JOIN agencyMode am ON am.id = o.agency_id + LEFT JOIN client c ON c.id = o.customer_id + LEFT JOIN worker wk ON wk.id = c.salesPersonFk + LEFT JOIN account.user u ON u.id = wk.userFk + LEFT JOIN company co ON co.id = o.company_id + LEFT JOIN orderTicket ot ON ot.orderFk = o.id + LEFT JOIN ticket t ON t.id = ot.ticketFk + LEFT JOIN zoneEstimatedDelivery zed ON zed.zoneFk = t.zoneFk`); if (args && args.ticketFk) { stmt.merge({ diff --git a/modules/order/back/methods/order/specs/filter.spec.js b/modules/order/back/methods/order/specs/filter.spec.js index 13cb8fdeb..1e6022ccb 100644 --- a/modules/order/back/methods/order/specs/filter.spec.js +++ b/modules/order/back/methods/order/specs/filter.spec.js @@ -39,6 +39,8 @@ describe('order filter()', () => { }); expect(hasEmptyLines).toBeFalsy(); + + ctx.args = {showEmpty: null}; }); it('should return the orders matching the showEmpty on true', async() => { @@ -50,5 +52,7 @@ describe('order filter()', () => { }); expect(hasEmptyLines).toBeTruthy(); + + ctx.args = {showEmpty: null}; }); }); diff --git a/modules/route/back/methods/route/specs/guessPriority.spec.js b/modules/route/back/methods/route/specs/guessPriority.spec.js index 075ea05c8..448501e67 100644 --- a/modules/route/back/methods/route/specs/guessPriority.spec.js +++ b/modules/route/back/methods/route/specs/guessPriority.spec.js @@ -14,18 +14,9 @@ describe('route guessPriority()', () => { done(); }); - it('should confirm the tickets in the target route have no priority yet', async() => { + it('should call guessPriority() and then check the tickets in the target route now have their priorities defined', async() => { routeTicketsToRestore = await app.models.Ticket.find({where: {routeFk: targetRouteId}}); - expect(routeTicketsToRestore.length).toEqual(2); - - expect(routeTicketsToRestore[0].id).toEqual(23); - expect(routeTicketsToRestore[0].priority).toBeNull(); - expect(routeTicketsToRestore[1].id).toEqual(24); - expect(routeTicketsToRestore[1].priority).toBeNull(); - }); - - it('should call guessPriority() and then check the tickets in the target route now have their priorities defined', async() => { await app.models.Route.guessPriority(targetRouteId); let routeTickets = await app.models.Ticket.find({where: {routeFk: targetRouteId}, fields: ['id', 'priority']}); diff --git a/modules/route/back/methods/route/specs/updateVolume.spec.js b/modules/route/back/methods/route/specs/updateVolume.spec.js index 3b4d51df7..0a191d9aa 100644 --- a/modules/route/back/methods/route/specs/updateVolume.spec.js +++ b/modules/route/back/methods/route/specs/updateVolume.spec.js @@ -1,46 +1,43 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('route updateVolume()', () => { const routeId = 1; - const workerFk = 9; - const ctx = {req: {accessToken: {userId: workerFk}}}; - let originalRoute; - let ticketToRestore; - let logIdToDestroy; + const userId = 50; + const activeCtx = { + accessToken: {userId: userId}, + }; + const ctx = {req: activeCtx}; - afterAll(async done => { - await originalRoute.updateAttributes({m3: 1.8}); - await ticketToRestore.updateAttributes({routeFk: null}); - await app.models.RouteLog.destroyById(logIdToDestroy); - done(); - }); + it('should confirm the route volume is updated and logged when a ticket is added', async() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + const route = await app.models.Route.findById(routeId); - it('should confirm the original volume of the route is the expected', async() => { - originalRoute = await app.models.Route.findById(routeId); + expect(route.m3).toEqual(1.8); - expect(originalRoute.m3).toEqual(1.8); - }); + const ticket = await app.models.Ticket.findById(14); - it('should confirm the route volume is updated when a ticket is added', async() => { - ticketToRestore = await app.models.Ticket.findById(14); - let updatedTicket = await app.models.Ticket.findById(14); - - await updatedTicket.updateAttributes({routeFk: routeId}); + await ticket.updateAttributes({routeFk: routeId}); await app.models.Route.updateVolume(ctx, routeId); - let updatedRoute = await app.models.Route.findById(routeId); + const updatedRoute = await app.models.Route.findById(routeId); - expect(updatedRoute.m3).not.toEqual(originalRoute.m3); - }); + expect(updatedRoute.m3).not.toEqual(route.m3); - it('should confirm the change is logged', async() => { - let logs = await app.models.RouteLog.find({fields: ['id', 'newInstance']}); + const logs = await app.models.RouteLog.find({fields: ['id', 'newInstance']}); - let m3Log = logs.filter(log => { - return log.newInstance.m3 === 1.9; + const m3Log = logs.filter(log => { + return log.newInstance.m3 === updatedRoute.m3; }); - logIdToDestroy = m3Log[0].id; + const logIdToDestroy = m3Log[0].id; expect(m3Log.length).toEqual(1); + + // restores + await ticket.updateAttributes({routeFk: null}); + await route.updateAttributes({m3: 1.8}); + await app.models.RouteLog.destroyById(logIdToDestroy); }); }); diff --git a/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js b/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js index 048d16c04..9633093f1 100644 --- a/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js +++ b/modules/ticket/back/methods/packaging/specs/listPackaging.spec.js @@ -1,7 +1,7 @@ const app = require('vn-loopback/server/server'); describe('ticket listPackaging()', () => { - it('should call the listPackaging method and return the response', async() => { + it('should return the packaging', async() => { let filter = {where: {packagingFk: 1}}; let response = await app.models.Packaging.listPackaging(filter); diff --git a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js index 8d3e0c248..0bcb94c03 100644 --- a/modules/ticket/back/methods/sale-tracking/listSaleTracking.js +++ b/modules/ticket/back/methods/sale-tracking/listSaleTracking.js @@ -22,22 +22,22 @@ module.exports = Self => { Self.listSaleTracking = async filter => { let stmt = new ParameterizedSQL(` - SELECT - st.id, - s.ticketFk, - s.quantity, - s.concept, - s.itemFk, - st.originalQuantity, - st.created, - st.workerFk, - u.nickname userNickname, - ste.name AS state - FROM saleTracking st - JOIN sale s ON s.id = st.saleFk - JOIN worker w ON w.id = st.workerFk - JOIN account.user u ON u.id = w.userFk - JOIN state ste ON ste.id = st.stateFk`); + SELECT + st.id, + s.ticketFk, + s.quantity, + s.concept, + s.itemFk, + st.originalQuantity, + st.created, + st.workerFk, + u.nickname userNickname, + ste.name AS state + FROM saleTracking st + JOIN sale s ON s.id = st.saleFk + JOIN worker w ON w.id = st.workerFk + JOIN account.user u ON u.id = w.userFk + JOIN state ste ON ste.id = st.stateFk`); stmt.merge(Self.makeSuffix(filter)); diff --git a/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js b/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js index 0d9937f89..7b19f45bb 100644 --- a/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js +++ b/modules/ticket/back/methods/sale-tracking/specs/listSaleTracking.spec.js @@ -5,7 +5,7 @@ describe('ticket listSaleTracking()', () => { let filter = {where: {ticketFk: 1}}; let result = await app.models.SaleTracking.listSaleTracking(filter); - expect(result[0].concept).toEqual('Ranged weapon longbow 2m'); + expect(result.length).toEqual(4); }); it(`should call the listSaleTracking method and return zero if doesn't have lines`, async() => { diff --git a/modules/ticket/back/methods/sale/specs/deleteSales.js b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js similarity index 71% rename from modules/ticket/back/methods/sale/specs/deleteSales.js rename to modules/ticket/back/methods/sale/specs/deleteSales.spec.js index c23ac6758..22ac49452 100644 --- a/modules/ticket/back/methods/sale/specs/deleteSales.js +++ b/modules/ticket/back/methods/sale/specs/deleteSales.spec.js @@ -2,12 +2,16 @@ const app = require('vn-loopback/server/server'); describe('sale deleteSales()', () => { let sale; - let newsale; + let newSale; beforeAll(async done => { - sale = await app.models.Sale.findOne({where: {id: 9}}); - sale.id = null; - newsale = await app.models.Sale.create(sale); + try { + sale = await app.models.Sale.findOne({where: {id: 9}}); + sale.id = null; + newSale = await app.models.Sale.create(sale); + } catch (error) { + console.error(error); + } done(); }); @@ -28,10 +32,10 @@ describe('sale deleteSales()', () => { expect(error).toEqual(new Error(`The sales of this ticket can't be modified`)); }); - it('should delete the sales', async() => { + it('should delete the sale', async() => { let ctx = {req: {accessToken: {userId: 9}}}; - const sales = [{id: newsale.id, instance: 0}]; + const sales = [{id: newSale.id, instance: 0}]; const ticketId = 16; let res = await app.models.Sale.deleteSales(ctx, sales, ticketId); diff --git a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js index 2ca266769..c8702c1db 100644 --- a/modules/ticket/back/methods/sale/specs/updatePrice.spec.js +++ b/modules/ticket/back/methods/sale/specs/updatePrice.spec.js @@ -16,14 +16,6 @@ describe('sale updatePrice()', () => { done(); }); - afterAll(async done => { - await originalSale.save(); - await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0}); - await originalSalesPersonMana.save(); - - done(); - }); - it('should throw an error if the ticket is not editable', async() => { let ctx = {req: {accessToken: {userId: 18}}}; let immutableSaleId = 1; @@ -43,36 +35,49 @@ describe('sale updatePrice()', () => { let price = ''; await app.models.Sale.updatePrice(ctx, saleId, price); - let saleUpdated = await app.models.Sale.findById(saleId); + let updatedSale = await app.models.Sale.findById(saleId); - expect(saleUpdated.price).toEqual(0); + expect(updatedSale.price).toEqual(0); + + // restores + await originalSale.updateAttributes(originalSale); + await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0}); + await originalSalesPersonMana.updateAttributes(originalSalesPersonMana); }); - it('should now set price as a decimal number in a string', async() => { + it('should now set price as a number in a string', async() => { let ctx = {req: {accessToken: {userId: 18}}}; let price = '8'; await app.models.Sale.updatePrice(ctx, saleId, price); - let saleUpdated = await app.models.Sale.findById(saleId); + let updatedSale = await app.models.Sale.findById(saleId); - expect(saleUpdated.price).toEqual(8); + expect(updatedSale.price).toEqual(8); + + // restores + await originalSale.updateAttributes(originalSale); + await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0}); + await originalSalesPersonMana.updateAttributes(originalSalesPersonMana); }); - it('should set price as a decimal number and check the sale has the mana component', async() => { + it('should set price as a decimal number and check the sale has the mana component changing the salesPersonMana', async() => { let ctx = {req: {accessToken: {userId: 18}}}; let price = 5.4; await app.models.Sale.updatePrice(ctx, saleId, price); - let saleUpdated = await app.models.Sale.findById(saleId); + let updatedSale = await app.models.Sale.findById(saleId); createdSaleComponent = await app.models.SaleComponent.findOne({where: {saleFk: saleId, componentFk: manaComponentId}}); - expect(saleUpdated.price).toBe(price); + expect(updatedSale.price).toBe(price); expect(createdSaleComponent.value).toEqual(-2.04); - }); - it('should check that the mana of salesPerson changed', async() => { let updatedSalesPersonMana = await app.models.WorkerMana.findById(18); expect(updatedSalesPersonMana.amount).not.toEqual(originalSalesPersonMana.amount); + + // restores + await originalSale.updateAttributes(originalSale); + await app.models.SaleComponent.updateAll({componentFk: manaComponentId, saleFk: saleId}, {value: 0}); + await originalSalesPersonMana.updateAttributes(originalSalesPersonMana); }); }); diff --git a/modules/ticket/back/methods/state/specs/editableState.spec.js b/modules/ticket/back/methods/state/specs/editableState.spec.js index 55e60beb8..fc0b80494 100644 --- a/modules/ticket/back/methods/state/specs/editableState.spec.js +++ b/modules/ticket/back/methods/state/specs/editableState.spec.js @@ -12,7 +12,7 @@ describe('ticket editableStates()', () => { expect(deliveredState).toBeTruthy(); }); - it(`should returns the expected states by a specific role`, async() => { + it(`should return the expected states by a specific role`, async() => { const productionRole = 18; const ctx = {req: {accessToken: {userId: productionRole}}}; let result = await app.models.State.editableStates(ctx, filter); diff --git a/modules/ticket/back/methods/ticket-request/confirm.js b/modules/ticket/back/methods/ticket-request/confirm.js index 0bc387fe8..67781c6c2 100644 --- a/modules/ticket/back/methods/ticket-request/confirm.js +++ b/modules/ticket/back/methods/ticket-request/confirm.js @@ -48,31 +48,26 @@ module.exports = Self => { include: {relation: 'ticket'} }, options); - const res = await models.Item.getVisibleAvailable(ctx.args.itemFk, request.ticket().warehouseFk, request.ticket().shipped); + const itemStock = await models.Item.getVisibleAvailable(ctx.args.itemFk, request.ticket().warehouseFk, request.ticket().shipped); + const isAvailable = itemStock.available > 0; - if (res.available < 0) + if (!isAvailable) throw new UserError(`This item is not available`); - if (request.saleFk) { - sale = await models.Sale.findById(request.saleFk, null, options); - await sale.updateAttributes({ - itemFk: ctx.args.itemFk, - quantity: ctx.args.quantity, - concept: item.name, - }, options); - } else { - sale = await models.Sale.create({ - ticketFk: request.ticketFk, - itemFk: ctx.args.itemFk, - quantity: ctx.args.quantity, - concept: item.name - }, options); - await request.updateAttributes({ - saleFk: sale.id, - itemFk: sale.itemFk, - isOk: true - }, options); - } + if (request.saleFk) + throw new UserError(`This request already contains a sale`); + + sale = await models.Sale.create({ + ticketFk: request.ticketFk, + itemFk: ctx.args.itemFk, + quantity: ctx.args.quantity, + concept: item.name + }, options); + await request.updateAttributes({ + saleFk: sale.id, + itemFk: sale.itemFk, + isOk: true + }, options); query = `CALL vn.sale_calculateComponent(?, NULL)`; await Self.rawSql(query, [sale.id], options); diff --git a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js index 134ccca40..bef6ad706 100644 --- a/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js +++ b/modules/ticket/back/methods/ticket-request/specs/confirm.spec.js @@ -1,9 +1,7 @@ const app = require('vn-loopback/server/server'); -describe('ticket-request confirm()', () => { - let originalRequest; - let originalSale; - let createdSaleId; +// #2512 confirm.spec pollutes other tests +xdescribe('ticket-request confirm()', () => { let ctx = { req: { accessToken: {userId: 9}, @@ -14,13 +12,6 @@ describe('ticket-request confirm()', () => { return value; }; - afterAll(async done => { - await originalRequest.updateAttributes(originalRequest); - await originalSale.updateAttributes(originalSale); - await app.models.Sale.destroyById(createdSaleId); - done(); - }); - it(`should throw an error if the item doesn't exist`, async() => { ctx.args = {itemFk: 999}; @@ -56,9 +47,8 @@ describe('ticket-request confirm()', () => { expect(error.message).toEqual(`This item is not available`); }); - it(`should update the sale details if the request already contains a sale id`, async() => { + it(`should throw if there's a sale id`, async() => { const requestId = 4; - const saleId = 11; const itemId = 1; const quantity = 10; @@ -68,17 +58,30 @@ describe('ticket-request confirm()', () => { quantity: quantity }; - originalRequest = await app.models.TicketRequest.findById(requestId); - originalSale = await app.models.Sale.findById(saleId); - const request = await app.models.TicketRequest.findById(requestId); - await request.updateAttributes({saleFk: saleId}); - await app.models.TicketRequest.confirm(ctx); - let updatedSale = await app.models.Sale.findById(saleId); + expect(request.saleFk).toBeNull(); - expect(updatedSale.itemFk).toEqual(itemId); - expect(updatedSale.quantity).toEqual(quantity); + await request.updateAttributes({saleFk: 2}); + + ctx.args = { + itemFk: itemId, + id: requestId, + quantity: quantity + }; + + let error; + + try { + await app.models.TicketRequest.confirm(ctx); + } catch (err) { + error = err; + } + + expect(error.message).toEqual(`This request already contains a sale`); + + // restores + await request.updateAttributes({saleFk: null}); }); it(`should create a new sale for the the request if there's no sale id`, async() => { @@ -86,6 +89,8 @@ describe('ticket-request confirm()', () => { const itemId = 1; const quantity = 10; + const originalRequest = await app.models.TicketRequest.findById(requestId); + ctx.args = { itemFk: itemId, id: requestId, @@ -96,11 +101,19 @@ describe('ticket-request confirm()', () => { await request.updateAttributes({saleFk: null}); await app.models.TicketRequest.confirm(ctx); - let updatedRequest = await app.models.TicketRequest.findById(requestId); - createdSaleId = updatedRequest.saleFk; + const updatedRequest = await app.models.TicketRequest.findById(requestId); + const createdSaleId = updatedRequest.saleFk; expect(updatedRequest.saleFk).toEqual(createdSaleId); expect(updatedRequest.isOk).toEqual(true); expect(updatedRequest.itemFk).toEqual(itemId); + + // restores + await originalRequest.updateAttributes(originalRequest); + await app.models.Sale.destroyById(createdSaleId); + + await app.models.Item.rawSql(` + TRUNCATE TABLE cache.last_buy + `); }); }); diff --git a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js b/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js index 3c6c51252..9b10f18f0 100644 --- a/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js +++ b/modules/ticket/back/methods/ticket-tracking/specs/changeState.spec.js @@ -1,24 +1,58 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('ticket changeState()', () => { + const salesPersonId = 18; + const employeeId = 1; + const productionId = 49; + let activeCtx = { + accessToken: {userId: 9}, + }; + let ctx = {req: activeCtx}; let ticket; beforeAll(async done => { - let originalTicket = await app.models.Ticket.findOne({where: {id: 16}}); - originalTicket.id = null; - ticket = await app.models.Ticket.create(originalTicket); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + + done(); + }); + + beforeEach(async done => { + try { + let originalTicket = await app.models.Ticket.findOne({where: {id: 16}}); + originalTicket.id = null; + ticket = await app.models.Ticket.create(originalTicket); + } catch (error) { + console.error(error); + } + + done(); + }); + + afterEach(async done => { + try { + await app.models.Ticket.destroyById(ticket.id); + } catch (error) { + console.error(error); + } done(); }); afterAll(async done => { - await app.models.Ticket.destroyById(ticket.id); + try { + await app.models.Ticket.destroyById(ticket.id); + } catch (error) { + console.error(error); + } done(); }); it('should throw if the ticket is not editable and the user isnt production', async() => { - let ctx = {req: {accessToken: {userId: 18}}}; + activeCtx.accessToken.userId = salesPersonId; let params = {ticketFk: 2, stateFk: 3}; let errCode; @@ -32,7 +66,7 @@ describe('ticket changeState()', () => { }); it('should throw an error if a worker with employee role attemps to a forbidden state', async() => { - let ctx = {req: {accessToken: {userId: 1}}}; + activeCtx.accessToken.userId = employeeId; let params = {ticketFk: 11, stateFk: 13}; let errCode; @@ -46,29 +80,21 @@ describe('ticket changeState()', () => { }); it('should be able to create a ticket tracking line for a not editable ticket if the user has the production role', async() => { - let ctx = {req: {accessToken: {userId: 49}}}; + activeCtx.accessToken.userId = productionId; let params = {ticketFk: ticket.id, stateFk: 3}; - let res = await app.models.TicketTracking.changeState(ctx, params); + let ticketTracking = await app.models.TicketTracking.changeState(ctx, params); - expect(res.__data.ticketFk).toBe(params.ticketFk); - expect(res.__data.stateFk).toBe(params.stateFk); - expect(res.__data.workerFk).toBe(49); - expect(res.__data.id).toBeDefined(); + expect(ticketTracking.__data.ticketFk).toBe(params.ticketFk); + expect(ticketTracking.__data.stateFk).toBe(params.stateFk); + expect(ticketTracking.__data.workerFk).toBe(49); + expect(ticketTracking.__data.id).toBeDefined(); + + // restores + await app.models.TicketTracking.destroyById(ticketTracking.__data.id); }); - it('should return an array with the created ticket tracking line', async() => { - let ctx = {req: {accessToken: {userId: 49}}}; - let params = {ticketFk: ticket.id, stateFk: 3}; - let res = await app.models.TicketTracking.changeState(ctx, params); - - expect(res.__data.ticketFk).toBe(params.ticketFk); - expect(res.__data.stateFk).toBe(params.stateFk); - expect(res.__data.workerFk).toBe(49); - expect(res.__data.id).toBeDefined(); - }); - - it('should return an array with the created ticket tracking line when the user is salesperson, uses the state assigned and thes a workerFk given', async() => { + it('should update the ticket tracking line when the user is salesperson, uses the state assigned and a valid worker id', async() => { let ctx = {req: {accessToken: {userId: 18}}}; let assignedState = await app.models.State.findOne({where: {code: 'PICKER_DESIGNED'}}); let params = {ticketFk: ticket.id, stateFk: assignedState.id, workerFk: 1}; diff --git a/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js b/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js index 520ccfb03..042ae0a1f 100644 --- a/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js +++ b/modules/ticket/back/methods/ticket-tracking/specs/setDelivered.spec.js @@ -1,24 +1,42 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('ticket setDelivered()', () => { + const userId = 50; + const activeCtx = { + accessToken: {userId: userId}, + }; + let ticketOne; let ticketTwo; beforeAll(async done => { - let originalTicketOne = await app.models.Ticket.findById(8); - let originalTicketTwo = await app.models.Ticket.findById(10); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + try { + let originalTicketOne = await app.models.Ticket.findById(8); + let originalTicketTwo = await app.models.Ticket.findById(10); - originalTicketOne.id = null; - originalTicketTwo.id = null; - ticketOne = await app.models.Ticket.create(originalTicketOne); - ticketTwo = await app.models.Ticket.create(originalTicketTwo); + originalTicketOne.id = null; + originalTicketTwo.id = null; + + ticketOne = await app.models.Ticket.create(originalTicketOne); + ticketTwo = await app.models.Ticket.create(originalTicketTwo); + } catch (error) { + console.error(error); + } done(); }); afterAll(async done => { - await app.models.Ticket.destroyById(ticketOne.id); - await app.models.Ticket.destroyById(ticketTwo.id); + try { + await app.models.Ticket.destroyById(ticketOne.id); + await app.models.Ticket.destroyById(ticketTwo.id); + } catch (error) { + console.error(error); + } done(); }); @@ -31,6 +49,8 @@ describe('ticket setDelivered()', () => { let state = await app.models.TicketTracking.setDelivered(ctx, params); expect(state.id).toEqual(delivered.id); + + // restores + await app.models.TicketTracking.destroyById(state.id); }); }); - diff --git a/modules/ticket/back/methods/ticket/componentUpdate.js b/modules/ticket/back/methods/ticket/componentUpdate.js index 15cfa0597..9010fc3ac 100644 --- a/modules/ticket/back/methods/ticket/componentUpdate.js +++ b/modules/ticket/back/methods/ticket/componentUpdate.js @@ -76,6 +76,7 @@ module.exports = Self => { companyFk, shipped, landed, isDeleted, option) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; + const $t = ctx.req.__; // $translate const isEditable = await models.Ticket.isEditable(ctx, id); if (!isEditable) @@ -88,29 +89,26 @@ module.exports = Self => { if (!zoneShipped || zoneShipped.zoneFk != zoneFk) throw new UserError(`You don't have privileges to change the zone`); } - const originalTicket = await models.Ticket.findById(id, {fields: - ['id', 'clientFk', 'agencyModeFk', 'addressFk', 'zoneFk', + const originalTicket = await models.Ticket.findById(id, { + include: { + relation: 'client', + scope: { + fields: 'salesPersonFk' + } + }, + fields: ['id', 'clientFk', 'agencyModeFk', 'addressFk', 'zoneFk', 'warehouseFk', 'companyFk', 'shipped', 'landed', 'isDeleted'] }); const updatedTicket = Object.assign({}, ctx.args); delete updatedTicket.ctx; delete updatedTicket.option; + // Force unroute const hasToBeUnrouted = true; - const propertiesChange = diff(originalTicket, updatedTicket); + const changedProperties = diff(originalTicket, updatedTicket); - let logRecord = { - originFk: id, - userFk: userId, - action: 'update', - changedModel: 'Ticket', - changedModelId: id, - oldInstance: originalTicket, - newInstance: propertiesChange - }; - - let query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; - let res = await Self.rawSql(query, [ + const query = 'CALL vn.ticket_componentMakeUpdate(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'; + const res = await Self.rawSql(query, [ id, clientFk, agencyModeFk, @@ -125,7 +123,45 @@ module.exports = Self => { option ]); - await models.TicketLog.create(logRecord); + await models.TicketLog.create({ + originFk: id, + userFk: userId, + action: 'update', + changedModel: 'Ticket', + changedModelId: id, + oldInstance: originalTicket, + newInstance: changedProperties + }); + + const salesPersonId = originalTicket.client().salesPersonFk; + if (salesPersonId) { + const origin = ctx.req.headers.origin; + + let changesMade = ''; + for (let change in changedProperties) { + let value = changedProperties[change]; + if (value instanceof Date) { + value = new Intl.DateTimeFormat('es', { + year: '2-digit', + month: '2-digit', + day: '2-digit', + hour: '2-digit', + minute: '2-digit', + second: '2-digit' + }).format(value); + } + + changesMade += `${change}: ${value}\r\n`; + } + + const message = $t('Changed this data from the ticket', { + ticketId: id, + ticketUrl: `${origin}/#!/ticket/${id}/summary`, + changes: changesMade + }); + await models.Chat.sendCheckingPresence(ctx, salesPersonId, message); + } + return res; }; }; diff --git a/modules/ticket/back/methods/ticket/priceDifference.js b/modules/ticket/back/methods/ticket/priceDifference.js index a303412fe..2631481c6 100644 --- a/modules/ticket/back/methods/ticket/priceDifference.js +++ b/modules/ticket/back/methods/ticket/priceDifference.js @@ -87,15 +87,14 @@ module.exports = Self => { const map = new Map(); // Sale price component, one per sale - difComponents.forEach(difComponent => { + for (difComponent of difComponents) map.set(difComponent.saleFk, difComponent); - }); function round(value) { return Math.round(value * 100) / 100; } - salesObj.items.forEach(sale => { + for (sale of salesObj.items) { const difComponent = map.get(sale.id); if (difComponent) { @@ -110,7 +109,7 @@ module.exports = Self => { salesObj.totalUnitPrice += sale.price; salesObj.totalUnitPrice = round(salesObj.totalUnitPrice); - }); + } return salesObj; }; diff --git a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js index 8954e6d47..f3039b447 100644 --- a/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js +++ b/modules/ticket/back/methods/ticket/specs/componentUpdate.spec.js @@ -1,7 +1,8 @@ const app = require('vn-loopback/server/server'); describe('ticket componentUpdate()', () => { - const ticketId = 11; + const userID = 101; + const ticketID = 11; const today = new Date(); const tomorrow = new Date(); tomorrow.setDate(tomorrow.getDate() + 1); @@ -13,39 +14,50 @@ describe('ticket componentUpdate()', () => { let componentOfSaleEight; beforeAll(async done => { - let deliveryComponenet = await app.models.Component.findOne({where: {code: 'delivery'}}); - deliveryComponentId = deliveryComponenet.id; - componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; - componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; + try { + let deliveryComponenet = await app.models.Component.findOne({where: {code: 'delivery'}}); + deliveryComponentId = deliveryComponenet.id; + componentOfSaleSeven = `SELECT value FROM vn.saleComponent WHERE saleFk = 7 AND componentFk = ${deliveryComponentId}`; + componentOfSaleEight = `SELECT value FROM vn.saleComponent WHERE saleFk = 8 AND componentFk = ${deliveryComponentId}`; - [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); - firstvalueBeforeChange = componentValue.value; + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); + firstvalueBeforeChange = componentValue.value; - [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); - secondvalueBeforeChange = componentValue.value; + [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); + secondvalueBeforeChange = componentValue.value; + } catch (error) { + console.error(error); + } done(); }); - it('should change the agencyMode to modify the sale components value', async() => { - const clientId = 102; - const addressId = 122; - const agencyModeId = 8; - const warehouseId = 1; - const zoneId = 5; + it('should change the agencyMode to modify the sale components value and then undo the changes', async() => { + const clientID = 102; + const addressID = 122; + const agencyModeID = 8; + const warehouseID = 1; + const zoneID = 5; const shipped = today; - const companyId = 442; + const companyID = 442; const isDeleted = false; const landed = tomorrow; const option = 1; let ctx = { - args: {clientFk: 102, - agencyModeFk: 8}, - req: {accessToken: {userId: 101}}}; + args: {clientFk: clientID, + agencyModeFk: agencyModeID}, + req: { + accessToken: {userId: userID}, + headers: {origin: 'http://localhost'}, + __: (value, params) => { + return params.nickname; + } + } + }; - await app.models.Ticket.componentUpdate(ctx, ticketId, clientId, agencyModeId, addressId, - zoneId, warehouseId, companyId, shipped, landed, isDeleted, option); + await app.models.Ticket.componentUpdate(ctx, ticketID, clientID, agencyModeID, addressID, + zoneID, warehouseID, companyID, shipped, landed, isDeleted, option); [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); let firstvalueAfterChange = componentValue.value; @@ -55,33 +67,32 @@ describe('ticket componentUpdate()', () => { expect(firstvalueBeforeChange).not.toEqual(firstvalueAfterChange); expect(secondvalueBeforeChange).not.toEqual(secondvalueAfterChange); - }); - it('should change the agencyMode to go back to the originals sale components value', async() => { - const clientId = 102; - const addressId = 122; - const agencyModeId = 7; - const warehouseId = 1; - const zoneId = 3; - const shipped = today; - const companyId = 442; - const isDeleted = false; - const landed = tomorrow; - const option = 1; + // restores + const restores = { + clientID: 102, + addressID: 122, + agencyModeID: 7, + warehouseID: 1, + zoneID: 3, + shipped: today, + companyID: 442, + isDeleted: false, + landed: tomorrow, + option: 1, + }; - let ctx = { - args: {clientFk: 102, - agencyModeFk: 7}, - req: {accessToken: {userId: 101}}}; + ctx.clientFk = restores.clientID; + ctx.agencyModeFk = restores.agencyModeID; - await app.models.Ticket.componentUpdate(ctx, ticketId, clientId, agencyModeId, addressId, - zoneId, warehouseId, companyId, shipped, landed, isDeleted, option); + await app.models.Ticket.componentUpdate(ctx, ticketID, restores.clientID, restores.agencyModeID, restores.addressID, + restores.zoneID, restores.warehouseID, restores.companyID, restores.shipped, restores.landed, restores.isDeleted, restores.option); [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleSeven); - let firstvalueAfterChange = componentValue.value; + firstvalueAfterChange = componentValue.value; [componentValue] = await app.models.SaleComponent.rawSql(componentOfSaleEight); - let secondvalueAfterChange = componentValue.value; + secondvalueAfterChange = componentValue.value; expect(firstvalueBeforeChange).toEqual(firstvalueAfterChange); expect(secondvalueBeforeChange).toEqual(secondvalueAfterChange); diff --git a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js index 56375940d..563c1334d 100644 --- a/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js +++ b/modules/ticket/back/methods/ticket/specs/deleteStowaway.spec.js @@ -13,90 +13,52 @@ describe('ticket deleteStowaway()', () => { return params.nickname; }; - afterAll(async() => { - await app.models.Stowaway.rawSql( - `CALL ticketStateUpdate(?, ?)`, [shipId, 'OK']); - await app.models.Stowaway.rawSql( - `CALL ticketStateUpdate(?, ?)`, [stowawayId, 'FREE']); - }); - - it('should create an stowaway', async() => { + it(`should create an stowaway, delete it and see the states of both stowaway and ship go back to the last states`, async() => { await app.models.Stowaway.rawSql(` INSERT INTO stowaway (id, shipFk) VALUES (?, ?) `, [stowawayId, shipId]); await app.models.Stowaway.rawSql( `CALL ticketStateUpdate(?, ?)`, [shipId, 'BOARDING']); + await app.models.Stowaway.rawSql( + `CALL ticketStateUpdate(?, ?)`, [stowawayId, 'BOARDING']); - const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + let createdStowaways = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); - expect(stowawayExists).toEqual(1); - }); + expect(createdStowaways).toEqual(1); - it('should confirm that the ship ticket is on "BOARDING" state', async() => { - const shipState = await app.models.TicketLastState.findOne({ + let shipState = await app.models.TicketLastState.findOne({ where: { ticketFk: shipId } }); + let stowawayState = await app.models.TicketLastState.findOne({ + where: { + ticketFk: stowawayId + } + }); expect(shipState.name).toEqual('Embarcando'); - }); + expect(stowawayState.name).toEqual('Embarcando'); - it('should delete the stowaway from the ship ticket', async() => { await app.models.Ticket.deleteStowaway(ctx, shipId); + await app.models.Ticket.deleteStowaway(ctx, stowawayId); - const stowawayExists = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); + createdStowaways = await app.models.Stowaway.count({id: stowawayId, shipFk: shipId}); - expect(stowawayExists).toEqual(0); - }); + expect(createdStowaways).toEqual(0); - it('should confirm that the ship ticket is not on "BOARDING" state anymore', async() => { - const shipState = await app.models.TicketLastState.findOne({ + shipState = await app.models.TicketLastState.findOne({ where: { ticketFk: shipId } }); + stowawayState = await app.models.TicketLastState.findOne({ + where: { + ticketFk: stowawayId + } + }); expect(shipState.name).toEqual('OK'); - }); - - it('should create again an stowaway', async() => { - await app.models.Stowaway.rawSql(` - INSERT INTO stowaway (id, shipFk) VALUES (?, ?) - `, [shipId, stowawayId]); - await app.models.Stowaway.rawSql( - `CALL ticketStateUpdate(?, ?)`, [stowawayId, 'BOARDING']); - - const stowawayExists = await app.models.Stowaway.count({id: shipId, shipFk: stowawayId}); - - expect(stowawayExists).toEqual(1); - }); - - it('should confirm that the stowaway ticket is on "BOARDING" state', async() => { - const shipState = await app.models.TicketLastState.findOne({ - where: { - ticketFk: stowawayId - } - }); - - expect(shipState.name).toEqual('Embarcando'); - }); - - it('should delete the stowaway from the stowaway ticket', async() => { - await app.models.Ticket.deleteStowaway(ctx, stowawayId); - - const stowawayExists = await app.models.Stowaway.count({id: shipId, shipFk: stowawayId}); - - expect(stowawayExists).toEqual(0); - }); - - it('should confirm that the stowaway ticket is not on "BOARDING" state anymore', async() => { - const shipState = await app.models.TicketLastState.findOne({ - where: { - ticketFk: stowawayId - } - }); - - expect(shipState.name).toEqual('Libre'); + expect(stowawayState.name).toEqual('Libre'); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/filter.spec.js b/modules/ticket/back/methods/ticket/specs/filter.spec.js index 85b410671..f5733c8da 100644 --- a/modules/ticket/back/methods/ticket/specs/filter.spec.js +++ b/modules/ticket/back/methods/ticket/specs/filter.spec.js @@ -5,9 +5,8 @@ describe('ticket filter()', () => { const ctx = {req: {accessToken: {userId: 9}}, args: {}}; const filter = {order: 'id DESC'}; const result = await app.models.Ticket.filter(ctx, filter); - const ticketId = result[0].id; - expect(ticketId).toEqual(24); + expect(result.length).toEqual(24); }); it('should return the tickets matching the problems on true', async() => { @@ -71,7 +70,7 @@ describe('ticket filter()', () => { const length = result.length; const anyResult = result[Math.floor(Math.random() * Math.floor(length))]; - expect(result.length).toEqual(7); + expect(length).toEqual(7); expect(anyResult.state).toMatch(/(Libre|Arreglar)/); }); diff --git a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js index b91751d5d..79bd59848 100644 --- a/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js +++ b/modules/ticket/back/methods/ticket/specs/makeInvoice.spec.js @@ -1,41 +1,53 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('ticket makeInvoice()', () => { + const userId = 19; + const activeCtx = { + accessToken: {userId: userId}, + }; + const ctx = {req: activeCtx}; + let invoice; let ticketId = 11; const okState = 3; - afterAll(async done => { - let ticket = await app.models.Ticket.findById(11); - await ticket.updateAttributes({refFk: null}); - - let ticketTrackings = await app.models.TicketTracking.find({ - where: { - ticketFk: ticketId, - stateFk: {neq: okState} - }, - order: 'id DESC' + beforeAll(async done => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx }); + }); - for (let state of ticketTrackings) - await state.destroy(); + afterAll(async done => { + try { + let ticket = await app.models.Ticket.findById(11); + await ticket.updateAttributes({refFk: null}); - let invoiceOut = await app.models.InvoiceOut.findById(invoice.invoiceFk); - await invoiceOut.destroy(); + let ticketTrackings = await app.models.TicketTracking.find({ + where: { + ticketFk: ticketId, + stateFk: {neq: okState} + }, + order: 'id DESC' + }); + for (let state of ticketTrackings) + await state.destroy(); + + let invoiceOut = await app.models.InvoiceOut.findById(invoice.invoiceFk); + await invoiceOut.destroy(); + } catch (error) { + console.error(error); + } done(); }); - it('should invoice a ticket', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; + it('should invoice a ticket, then try again to fail', async() => { invoice = await app.models.Ticket.makeInvoice(ctx, ticketId); expect(invoice.invoiceFk).toBeDefined(); expect(invoice.serial).toEqual('T'); - }); - it('should not invoice an already invoiced ticket', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; let error; await app.models.Ticket.makeInvoice(ctx, ticketId).catch(e => { @@ -43,5 +55,7 @@ describe('ticket makeInvoice()', () => { }).finally(() => { expect(error.message).toEqual(`This ticket can't be invoiced`); }); + + expect(error).toBeDefined(); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/restore.spec.js b/modules/ticket/back/methods/ticket/specs/restore.spec.js index 1abb52dc5..97cf78f91 100644 --- a/modules/ticket/back/methods/ticket/specs/restore.spec.js +++ b/modules/ticket/back/methods/ticket/specs/restore.spec.js @@ -1,20 +1,24 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); const models = app.models; describe('ticket restore()', () => { const employeeUser = 110; - const ctx = { - req: { - accessToken: {userId: employeeUser}, - headers: { - origin: 'http://localhost:5000' - }, - __: () => {} - } + const activeCtx = { + accessToken: {userId: employeeUser}, + headers: { + origin: 'http://localhost:5000' + }, + __: () => {} }; + const ctx = {req: activeCtx}; + let createdTicket; beforeEach(async done => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); try { const sampleTicket = await models.Ticket.findById(11); sampleTicket.id = undefined; diff --git a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js index 518b6a4d8..6bd265169 100644 --- a/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js +++ b/modules/ticket/back/methods/ticket/specs/setDeleted.spec.js @@ -1,18 +1,17 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); const models = app.models; describe('ticket setDeleted()', () => { + const userId = 106; + const employeeUser = 110; + const activeCtx = { + accessToken: {userId: userId}, + }; + it('should throw an error if the given ticket has a claim', async() => { + const ctx = {req: activeCtx}; const ticketId = 16; - const ctx = { - req: { - accessToken: {userId: 106}, - headers: { - origin: 'http://localhost:5000' - }, - __: () => {} - } - }; let error; try { @@ -26,7 +25,9 @@ describe('ticket setDeleted()', () => { }); it('should delete the ticket, remove the stowaway link and change the stowaway ticket state to "FIXING" and get rid of the itemshelving', async() => { - const employeeUser = 110; + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); const ctx = { req: { accessToken: {userId: employeeUser}, @@ -96,7 +97,8 @@ describe('ticket setDeleted()', () => { expect(stowaway).toBeNull(); expect(stowawayTicketState.code).toEqual('FIXING'); - await shipTicket.destroy(); - await stowawayTicket.destroy(); + // restores + await models.Ticket.destroyById(shipTicket.id); + await models.Ticket.destroyById(stowawayTicket.id); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js index 63f2034bb..3d62ccce9 100644 --- a/modules/ticket/back/methods/ticket/specs/transferSales.spec.js +++ b/modules/ticket/back/methods/ticket/specs/transferSales.spec.js @@ -1,18 +1,36 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('sale transferSales()', () => { - let createdTicketId; + const userId = 101; + const activeCtx = { + accessToken: {userId: userId}, + }; + const ctx = {req: activeCtx}; + let createdTicketsIds = []; - afterAll(async done => { - createdTicketsIds.forEach(async createdTicketId => { - await app.models.Ticket.destroyById(createdTicketId); + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx }); + }); + + afterEach(async done => { + if (createdTicketsIds.length) { + try { + createdTicketsIds.forEach(async createdTicketId => { + await app.models.Ticket.destroyById(createdTicketId); + }); + } catch (error) { + console.error(error); + } + } + done(); }); it('should throw an error as the ticket is not editable', async() => { - const ctx = {req: {accessToken: {userId: 101}}}; let error; const currentTicketId = 1; @@ -29,7 +47,6 @@ describe('sale transferSales()', () => { }); it('should throw an error if the receiving ticket is not editable', async() => { - const ctx = {req: {accessToken: {userId: 101}}}; let error; const currentTicketId = 16; @@ -45,60 +62,41 @@ describe('sale transferSales()', () => { expect(error).toBeDefined(); }); - it('should transfer the sales from one ticket to a new one', async() => { - const ctx = {req: {accessToken: {userId: 101}}}; - let currentTicket = await app.models.Ticket.findById(11); - let originalTicketSales = await app.models.Ticket.getSales(currentTicket.id); - salesToRestone = originalTicketSales; + it('should transfer the sales from one ticket to a new one then send them back and delete the created ticket', async() => { + const formerTicketId = 11; + let createdTicketId = undefined; - expect(originalTicketSales.length).toEqual(2); + let formerTicketSales = await app.models.Ticket.getSales(formerTicketId); - const currentTicketId = currentTicket.id; - const receiverTicketId = undefined; + expect(formerTicketSales.length).toEqual(2); let createdTicket = await app.models.Ticket.transferSales( - ctx, currentTicketId, receiverTicketId, originalTicketSales); + ctx, formerTicketId, createdTicketId, formerTicketSales); + createdTicketId = createdTicket.id; - createdTicketsIds.push(createdTicket.id); + createdTicketsIds.push(createdTicketId); - originalTicketSales = await app.models.Ticket.getSales(currentTicket.id); - receiverTicketSales = await app.models.Ticket.getSales(createdTicket.id); + formerTicketSales = await app.models.Ticket.getSales(formerTicketId); + createdTicketSales = await app.models.Ticket.getSales(createdTicketId); - expect(originalTicketSales.length).toEqual(0); - expect(receiverTicketSales.length).toEqual(2); - }); - - it('should transfer back the sales and set the created ticket as deleted', async() => { - const ctx = {req: {accessToken: {userId: 101}}}; - const currentTicket = await app.models.Ticket.findById(createdTicketId); - const receiverTicketId = 11; - - let createdTicket = await app.models.Ticket.findById(createdTicketId); - let createdTicketSales = await app.models.Ticket.getSales(createdTicketId); - let receiverTicketSales = await app.models.Ticket.getSales(receiverTicketId); - - const currentTicketId = currentTicket.id; - const sales = createdTicketSales; - - expect(createdTicket.isDeleted).toBeFalsy(); + expect(formerTicketSales.length).toEqual(0); expect(createdTicketSales.length).toEqual(2); - expect(receiverTicketSales.length).toEqual(0); await app.models.Ticket.transferSales( - ctx, currentTicketId, receiverTicketId, sales); + ctx, createdTicketId, formerTicketId, createdTicketSales); + + formerTicketSales = await app.models.Ticket.getSales(formerTicketId); + createdTicketSales = await app.models.Ticket.getSales(createdTicketId); createdTicket = await app.models.Ticket.findById(createdTicketId); - createdTicketSales = await app.models.Ticket.getSales(createdTicketId); - receiverTicketSales = await app.models.Ticket.getSales(receiverTicketId); expect(createdTicket.isDeleted).toBeTruthy(); + expect(formerTicketSales.length).toEqual(2); expect(createdTicketSales.length).toEqual(0); - expect(receiverTicketSales.length).toEqual(2); }); describe('sale transferPartialSales()', () => { it('should throw an error in the quantity to transfer exceeds the amount from the original sale', async() => { - const ctx = {req: {accessToken: {userId: 101}}}; let error; let currentTicket = await app.models.Ticket.findById(11); let currentTicketSales = await app.models.Ticket.getSales(currentTicket.id); @@ -119,44 +117,51 @@ describe('sale transferSales()', () => { }); it('should transfer two sales to a new ticket but one shall be partial', async() => { - const ctx = {req: {accessToken: {userId: 101}}}; - const originalTicketId = 11; - const receiverTicketId = undefined; + const formerTicketId = 11; + let createdTicketId = undefined; - let currentTicketSales = await app.models.Ticket.getSales(originalTicketId); + let formerTicketSales = await app.models.Ticket.getSales(formerTicketId); - const originalPartialSaleId = currentTicketSales[0].id; - const originalCompleteSaleId = currentTicketSales[1].id; - let originalQuantity = currentTicketSales[0].quantity; - currentTicketSales[0].quantity = 1; + const partialSaleId = formerTicketSales[0].id; + const completeSaleId = formerTicketSales[1].id; + let partialSaleTotalQuantity = formerTicketSales[0].quantity; + + expect(partialSaleTotalQuantity).toEqual(15); + + formerTicketSales[0].quantity = 1; let createdTicket = await app.models.Ticket.transferSales( - ctx, originalTicketId, receiverTicketId, currentTicketSales); + ctx, formerTicketId, createdTicketId, formerTicketSales); createdTicketId = createdTicket.id; createdTicketsIds.push(createdTicket.id); - currentTicketSales = await app.models.Ticket.getSales(originalTicketId); - receiverTicketSales = await app.models.Ticket.getSales(createdTicketId); + formerTicketSales = await app.models.Ticket.getSales(formerTicketId); + createdTicketSales = await app.models.Ticket.getSales(createdTicketId); - const [createdPartialSale] = receiverTicketSales.filter(sale => { - return sale.id != originalCompleteSaleId; + const [createdPartialSale] = createdTicketSales.filter(sale => { + return sale.id != completeSaleId; }); - expect(currentTicketSales.length).toEqual(1); - expect(currentTicketSales[0].quantity).toEqual(originalQuantity -= 1); - expect(receiverTicketSales.length).toEqual(2); + expect(formerTicketSales.length).toEqual(1); + expect(formerTicketSales[0].quantity).toEqual(partialSaleTotalQuantity - 1); + expect(createdTicketSales.length).toEqual(2); expect(createdPartialSale.quantity).toEqual(1); - let saleToRestore = await app.models.Sale.findById(originalPartialSaleId); - await saleToRestore.updateAttribute('quantity', originalQuantity); + let saleToRestore = await app.models.Sale.findById(partialSaleId); + await saleToRestore.updateAttribute('quantity', partialSaleTotalQuantity); - let saleToReturnToTicket = await app.models.Sale.findById(originalCompleteSaleId); - await saleToReturnToTicket.updateAttribute('ticketFk', originalTicketId); + let saleToReturnToTicket = await app.models.Sale.findById(completeSaleId); + await saleToReturnToTicket.updateAttribute('ticketFk', formerTicketId); - currentTicketSales = await app.models.Ticket.getSales(originalTicketId); + formerTicketSales = await app.models.Ticket.getSales(formerTicketId); - expect(currentTicketSales.length).toEqual(2); + const [returningPartialSale] = formerTicketSales.filter(sale => { + return sale.id == partialSaleId; + }); + + expect(returningPartialSale.quantity).toEqual(partialSaleTotalQuantity); + expect(formerTicketSales.length).toEqual(2); }); }); }); diff --git a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js index 42689c73e..2e71842b4 100644 --- a/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateDiscount.spec.js @@ -7,21 +7,29 @@ describe('sale updateDiscount()', () => { let salesPersonMana; beforeAll(async done => { - originalSale = await app.models.Sale.findById(originalSaleId); - let manaDiscount = await app.models.Component.findOne({where: {code: 'buyerDiscount'}}); - componentId = manaDiscount.id; + try { + originalSale = await app.models.Sale.findById(originalSaleId); + let manaDiscount = await app.models.Component.findOne({where: {code: 'buyerDiscount'}}); + componentId = manaDiscount.id; - let ticket = await app.models.Ticket.findById(originalSale.ticketFk); - let client = await app.models.Client.findById(ticket.clientFk); - salesPersonMana = await app.models.WorkerMana.findById(client.salesPersonFk); + let ticket = await app.models.Ticket.findById(originalSale.ticketFk); + let client = await app.models.Client.findById(ticket.clientFk); + salesPersonMana = await app.models.WorkerMana.findById(client.salesPersonFk); + } catch (error) { + console.error(error); + } done(); }); afterAll(async done => { - await originalSale.save(); - await app.models.SaleComponent.updateAll({componentFk: componentId, saleFk: originalSaleId}, {value: 0}); - await salesPersonMana.save(); + try { + await originalSale.save(); + await app.models.SaleComponent.updateAll({componentFk: componentId, saleFk: originalSaleId}, {value: 0}); + await salesPersonMana.save(); + } catch (error) { + console.error(error); + } done(); }); diff --git a/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js b/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js index a08565df2..ffe61e35d 100644 --- a/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js +++ b/modules/ticket/back/methods/ticket/specs/updateEditableTicket.spec.js @@ -1,4 +1,11 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); + +const userId = 9; +const activeCtx = { + accessToken: {userId: userId}, +}; +const ctx = {req: activeCtx}; describe('ticket updateEditableTicket()', () => { const validTicketId = 12; @@ -7,7 +14,6 @@ describe('ticket updateEditableTicket()', () => { const originalData = {addressFk: 123}; afterAll(async done => { - let ctx = {req: {accessToken: {userId: 9}}}; await app.models.Ticket.updateEditableTicket(ctx, validTicketId, originalData); done(); @@ -15,7 +21,6 @@ describe('ticket updateEditableTicket()', () => { it('should now throw an error if the ticket is not editable', async() => { let error; - let ctx = {req: {accessToken: {userId: 9}}}; await app.models.Ticket.updateEditableTicket(ctx, invalidTicketId, data).catch(e => { error = e; @@ -27,8 +32,9 @@ describe('ticket updateEditableTicket()', () => { }); it('should edit the ticket address', async() => { - let ctx = {req: {accessToken: {userId: 9}}}; - + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); await app.models.Ticket.updateEditableTicket(ctx, validTicketId, data); let updatedTicket = await app.models.Ticket.findById(validTicketId); diff --git a/modules/ticket/back/models/ticket.js b/modules/ticket/back/models/ticket.js index fcdca2f13..c47f33081 100644 --- a/modules/ticket/back/models/ticket.js +++ b/modules/ticket/back/models/ticket.js @@ -1,4 +1,6 @@ +const LoopBackContext = require('loopback-context'); + module.exports = Self => { require('../methods/ticket/changeWorker')(Self); require('../methods/ticket/getVolume')(Self); @@ -35,13 +37,16 @@ module.exports = Self => { require('../methods/ticket/getComponentsSum')(Self); Self.observe('before save', async function(ctx) { + const loopBackContext = LoopBackContext.getCurrentContext(); + const httpCtx = loopBackContext.active; + if (ctx.isNewInstance) return; let changes = ctx.data || ctx.instance; if (changes.routeFk === null && ctx.currentInstance.routeFk != null) { let instance = JSON.parse(JSON.stringify(ctx.currentInstance)); - let userId = ctx.options.accessToken.userId; + let userId = httpCtx.accessToken.userId; let logRecord = { originFk: ctx.currentInstance.routeFk, userFk: userId, diff --git a/modules/ticket/front/basic-data/step-one/index.js b/modules/ticket/front/basic-data/step-one/index.js index e7eb30583..e1e74ae3f 100644 --- a/modules/ticket/front/basic-data/step-one/index.js +++ b/modules/ticket/front/basic-data/step-one/index.js @@ -56,8 +56,16 @@ class Controller extends Component { set warehouseId(value) { if (value != this.ticket.warehouseFk) { this.ticket.warehouseFk = value; - this.ticket.agencyModeFk = null; - this.ticket.zoneFk = null; + + this.getShipped({ + landed: this.ticket.landed, + addressFk: this.ticket.addressFk, + agencyModeFk: this.ticket.agencyModeFk, + warehouseFk: value + }).then(() => { + if (this.zoneId == null) + this.ticket.agencyModeFk = null; + }); } } @@ -177,8 +185,8 @@ class Controller extends Component { ); } - let query = `tickets/${this.ticket.id}/priceDifference`; - let params = { + const query = `tickets/${this.ticket.id}/priceDifference`; + const params = { landed: this.ticket.landed, addressId: this.ticket.addressFk, agencyModeId: this.ticket.agencyModeFk, @@ -202,9 +210,13 @@ class Controller extends Component { * Returns a landing date */ getLanded(params) { + const validParams = this.shipped && this.addressId + && this.agencyModeId && this.warehouseId; + if (!validParams) return this.$q.resolve(); + this.ticket.zoneFk = null; const query = `Agencies/getLanded`; - this.$http.get(query, {params}).then(res => { + return this.$http.get(query, {params}).then(res => { if (res.data) { this.ticket.zoneFk = res.data.zoneFk; this.ticket.landed = res.data.landed; @@ -221,9 +233,13 @@ class Controller extends Component { * Returns a shipment date */ getShipped(params) { + const validParams = this.landed && this.addressId + && this.agencyModeId && this.warehouseId; + if (!validParams) return this.$q.resolve(); + this.ticket.zoneFk = null; const query = `Agencies/getShipped`; - this.$http.get(query, {params}).then(res => { + return this.$http.get(query, {params}).then(res => { if (res.data) { this.ticket.zoneFk = res.data.zoneFk; this.ticket.landed = params.landed; diff --git a/modules/ticket/front/basic-data/step-one/index.spec.js b/modules/ticket/front/basic-data/step-one/index.spec.js index bd88b88ac..c7d09a7b1 100644 --- a/modules/ticket/front/basic-data/step-one/index.spec.js +++ b/modules/ticket/front/basic-data/step-one/index.spec.js @@ -323,6 +323,7 @@ describe('Ticket', () => { warehouseFk: 1 }; const serializedParams = $httpParamSerializer(params); + controller.ticket.shipped = shipped; $httpBackend.expect('GET', `Agencies/getLanded?${serializedParams}`).respond(200, expectedResult); controller.getLanded(params); @@ -344,6 +345,7 @@ describe('Ticket', () => { warehouseFk: 1 }; const serializedParams = $httpParamSerializer(params); + controller.ticket.landed = landed; $httpBackend.expect('GET', `Agencies/getShipped?${serializedParams}`).respond(200, expectedResult); controller.getShipped(params); diff --git a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js index 733b713f0..a3fc98aa6 100644 --- a/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js +++ b/modules/travel/back/methods/thermograph/specs/createThermograph.spec.js @@ -18,7 +18,7 @@ describe('Termograph createThermograph()', () => { done(); }); - it(`should create a thermograph which is saved in both thermograph and travelThermograph`, async() => { + it(`should be able to create just once a thermograph which is saved in both thermograph and travelThermograph`, async() => { let createdTravelThermograpth = await models.TravelThermograph.findOne({where: {thermographFk: thermographId}}); expect(createdTravelThermograpth).toBeNull(); @@ -32,9 +32,7 @@ describe('Termograph createThermograph()', () => { expect(createdTravelThermograpth.warehouseFk).toEqual(warehouseId); expect(createdTravelThermograpth.temperature).toEqual(temperature); - }); - it(`should not be able to created duplicated entries`, async() => { let error; try { diff --git a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js index ff5e13a2d..5e3732988 100644 --- a/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js +++ b/modules/worker/back/methods/worker-time-control/specs/timeEntry.spec.js @@ -1,12 +1,37 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); + +describe('workerTimeControl add/delete timeEntry()', () => { + const HHRRId = 37; + const teamBossId = 13; + const employeeId = 1; + let activeCtx = { + accessToken: {userId: 50}, + }; + let ctx = {req: activeCtx}; -describe('workerTimeControl addTimeEntry()', () => { let timeEntry; let createdTimeEntry; + afterEach(async() => { + if (createdTimeEntry) { + try { + await app.models.WorkerTimeControl.destroyById(createdTimeEntry.id); + } catch (error) { + console.error(error); + } + } + }); + + beforeAll(() => { + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + }); + it('should fail to add a time entry if the target user is not a subordinate', async() => { + activeCtx.accessToken.userId = employeeId; let error; - let ctx = {req: {accessToken: {userId: 1}}}; let data = { workerFk: 2, timed: new Date() @@ -24,8 +49,8 @@ describe('workerTimeControl addTimeEntry()', () => { }); it('should fail to add if the current and the target user are the same and is not team boss', async() => { + activeCtx.accessToken.userId = employeeId; let error; - let ctx = {req: {accessToken: {userId: 1}}}; let data = { workerFk: 1, timed: new Date() @@ -42,12 +67,11 @@ describe('workerTimeControl addTimeEntry()', () => { expect(error.message).toBe(`You don't have enough privileges`); }); - it('should add if the current user is team boss and the target user is a subordinate', async() => { - todayAtSix = new Date(); + it('should add if the current user is team boss and the target user is a himself', async() => { + activeCtx.accessToken.userId = teamBossId; + let todayAtSix = new Date(); todayAtSix.setHours(18, 30, 0, 0); - let teamBossId = 13; - let ctx = {req: {accessToken: {userId: teamBossId}}}; let data = { workerFk: teamBossId, timed: todayAtSix @@ -60,10 +84,20 @@ describe('workerTimeControl addTimeEntry()', () => { expect(createdTimeEntry).toBeDefined(); }); - it('should try but fail to delete the created time entry for the team boss as team boss', async() => { + it('should try but fail to delete his own time entry', async() => { + activeCtx.accessToken.userId = teamBossId; let error; - let teamBossId = 13; - let ctx = {req: {accessToken: {userId: teamBossId}}}; + let todayAtSeven = new Date(); + todayAtSeven.setHours(19, 30, 0, 0); + + let data = { + workerFk: teamBossId, + timed: todayAtSeven + }; + + timeEntry = await app.models.WorkerTimeControl.addTimeEntry(ctx, data); + + createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id); try { await app.models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id); @@ -77,13 +111,23 @@ describe('workerTimeControl addTimeEntry()', () => { }); it('should delete the created time entry for the team boss as HHRR', async() => { - let HHRRId = 37; - let ctx = {req: {accessToken: {userId: HHRRId}}}; + activeCtx.accessToken.userId = HHRRId; + + let todayAtFive = new Date(); + todayAtFive.setHours(17, 30, 0, 0); + + let data = { + workerFk: teamBossId, + timed: todayAtFive + }; + + timeEntry = await app.models.WorkerTimeControl.addTimeEntry(ctx, data); + + createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id); expect(createdTimeEntry).toBeDefined(); - ctx.req.accessToken.userId = HHRRId; - await app.models.WorkerTimeControl.deleteTimeEntry(ctx, timeEntry.id); + await app.models.WorkerTimeControl.deleteTimeEntry(ctx, createdTimeEntry.id); createdTimeEntry = await app.models.WorkerTimeControl.findById(timeEntry.id); diff --git a/modules/zone/back/methods/agency/getLanded.js b/modules/zone/back/methods/agency/getLanded.js index 27ac88327..4505c68dd 100644 --- a/modules/zone/back/methods/agency/getLanded.js +++ b/modules/zone/back/methods/agency/getLanded.js @@ -37,9 +37,12 @@ module.exports = Self => { Self.getLanded = async(ctx, shipped, addressFk, agencyModeFk, warehouseFk) => { const userId = ctx.req.accessToken.userId; const models = Self.app.models; - const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); + const roles = await models.Account.getRoles(userId); + const canSeeExpired = roles.filter(role => + role == 'productionBoss' || role == 'administrative' + ); let showExpired = false; - if (isProductionBoss) showExpired = true; + if (canSeeExpired.length) showExpired = true; let stmts = []; stmts.push(new ParameterizedSQL( diff --git a/modules/zone/back/methods/zone/deleteZone.js b/modules/zone/back/methods/zone/deleteZone.js index 7bf807f7d..c8ac63f22 100644 --- a/modules/zone/back/methods/zone/deleteZone.js +++ b/modules/zone/back/methods/zone/deleteZone.js @@ -49,7 +49,7 @@ module.exports = Self => { await models.Ticket.rawSql('UPDATE ticket SET zoneFk = NULL WHERE zoneFk = ?', [id], options); - ticketList.forEach(ticket => { + for (ticket of ticketList) { if (ticket.ticketState().alertLevel == 0) { promises.push(models.TicketTracking.create({ ticketFk: ticket.id, @@ -57,7 +57,7 @@ module.exports = Self => { workerFk: worker.id }, options)); } - }); + } await Promise.all(promises); await models.Zone.destroyById(id, options); await tx.commit(); diff --git a/modules/zone/back/methods/zone/includingExpired.js b/modules/zone/back/methods/zone/includingExpired.js index 6428d5b88..a27d04466 100644 --- a/modules/zone/back/methods/zone/includingExpired.js +++ b/modules/zone/back/methods/zone/includingExpired.js @@ -32,9 +32,12 @@ module.exports = Self => { && where.agencyModeFk && where.warehouseFk; if (filterByAvailability) { - const isProductionBoss = await models.Account.hasRole(userId, 'productionBoss'); + const roles = await models.Account.getRoles(userId); + const canSeeExpired = roles.filter(role => + role == 'productionBoss' || role == 'administrative' + ); let showExpired = false; - if (isProductionBoss) showExpired = true; + if (canSeeExpired.length) showExpired = true; stmt = new ParameterizedSQL(`CALL vn.zone_getLanded(?, ?, ?, ?, ?)`, [ where.shipped, diff --git a/modules/zone/back/methods/zone/specs/deleteZone.spec.js b/modules/zone/back/methods/zone/specs/deleteZone.spec.js index c7f4cb939..8722837af 100644 --- a/modules/zone/back/methods/zone/specs/deleteZone.spec.js +++ b/modules/zone/back/methods/zone/specs/deleteZone.spec.js @@ -1,62 +1,81 @@ const app = require('vn-loopback/server/server'); +const LoopBackContext = require('loopback-context'); describe('zone deletezone()', () => { + const userId = 9; + const activeCtx = { + accessToken: {userId: userId}, + }; + const ctx = {req: activeCtx}; let zoneId = 9; - let originalZoneTickets; let originalZone; let originalZoneWarehouses; + let originalTickets; + let ticketIDs; let originalZoneIncluded; - let ticketsId; - let originalTicketsState; + let originalTicketStates; beforeAll(async done => { - originalZone = await app.models.Zone.findById(zoneId); - originalZoneTickets = await app.models.Ticket.find({where: {zoneFk: zoneId}}); - originalZoneWarehouses = await app.models.ZoneWarehouse.findById(zoneId); - originalZoneIncluded = await app.models.ZoneIncluded.find({where: {zoneFk: zoneId}}); - ticketsId = originalZoneTickets.map(originalZoneTickets => originalZoneTickets.id); - originalTicketsState = await app.models.TicketState.find({where: { - ticketFk: {inq: ticketsId}, - code: 'FIXING'}}); + spyOn(LoopBackContext, 'getCurrentContext').and.returnValue({ + active: activeCtx + }); + try { + originalZone = await app.models.Zone.findById(zoneId); + originalZoneWarehouses = await app.models.ZoneWarehouse.findById(zoneId); + originalTickets = await app.models.Ticket.find({ + where: { + zoneFk: zoneId + } + }); + ticketIDs = originalTickets.map(ticket => ticket.id); + originalZoneIncluded = await app.models.ZoneIncluded.find({where: {zoneFk: zoneId}}); + originalTicketStates = await app.models.TicketState.find({where: { + ticketFk: {inq: ticketIDs}, + code: 'FIXING'}}); + } catch (error) { + console.error(error); + } + done(); }); afterAll(async done => { - await originalZone.save(); - await app.models.ZoneWarehouse.create(originalZoneWarehouses); + try { + await originalZone.save(); + await app.models.ZoneWarehouse.create(originalZoneWarehouses); - for (ticket of originalZoneTickets) - await ticket.updateAttributes({zoneFk: zoneId}); + for (ticket of originalTickets) + await ticket.updateAttributes({zoneFk: zoneId}); - for (zoneIncluded of originalZoneIncluded) - await zoneIncluded.save(); + for (zoneIncluded of originalZoneIncluded) + await zoneIncluded.save(); - const fixingStateId = 1; - const ticketIds = originalZoneTickets.map(ticket => ticket.id); - const trackings = await app.models.TicketTracking.find({where: { - ticketFk: {inq: ticketIds}, - stateFk: fixingStateId}}); + const fixingStateId = 1; + const trackings = await app.models.TicketTracking.find({where: { + ticketFk: {inq: ticketIDs}, + stateFk: fixingStateId}}); - for (let tracking of trackings) - await app.models.TicketTracking.destroyById(tracking.id); + for (let tracking of trackings) + await app.models.TicketTracking.destroyById(tracking.id); + } catch (error) { + console.error(error); + } done(); }); it('should delete a zone and update their tickets', async() => { - const ctx = {req: {accessToken: {userId: 9}}}; await app.models.Zone.deleteZone(ctx, zoneId); - let updatedZone = await app.models.Zone.findById(zoneId); - let zoneUpdatedTicket = await app.models.Ticket.findById(originalZoneTickets[0].id); - let ticketsId = originalZoneTickets.map(originalZoneTickets => originalZoneTickets.id); + const updatedZone = await app.models.Zone.findById(zoneId); + const anUpdatedTicket = await app.models.Ticket.findById(ticketIDs[0]); - let updatedTicketState = await app.models.TicketState.find({where: { - ticketFk: {inq: ticketsId}, + const updatedTicketStates = await app.models.TicketState.find({where: { + ticketFk: {inq: ticketIDs}, code: 'FIXING'}}); expect(updatedZone).toBeNull(); - expect(zoneUpdatedTicket.zoneFk).not.toBe(zoneId); - expect(originalTicketsState.length).not.toBeGreaterThan(updatedTicketState.length); + expect(anUpdatedTicket.zoneFk).toBeNull(); + expect(updatedTicketStates.length).toBeGreaterThan(originalTicketStates.length); }); }); diff --git a/print/templates/reports/delivery-note/delivery-note.js b/print/templates/reports/delivery-note/delivery-note.js index 22b0a7cf6..5bf9824f6 100755 --- a/print/templates/reports/delivery-note/delivery-note.js +++ b/print/templates/reports/delivery-note/delivery-note.js @@ -3,6 +3,7 @@ const Component = require(`${appPath}/core/component`); const reportHeader = new Component('report-header'); const reportFooter = new Component('report-footer'); const md5 = require('md5'); +const fs = require('fs-extra'); module.exports = { name: 'delivery-note', @@ -24,11 +25,14 @@ module.exports = { }, computed: { dmsPath() { - const pathHash = md5(this.signature.id.toString()).substring(0, 3); - const hostPath = `file:///${config.storage.root}/${pathHash}`; + if (!this.signature) return; - if (this.signature && this.signature.id) - return `${hostPath}/${this.signature.id}.png`; + const hash = md5(this.signature.id.toString()).substring(0, 3); + const file = `${config.storage.root}/${hash}/${this.signature.id}.png`; + const src = fs.readFileSync(file); + const base64 = Buffer.from(src, 'utf8').toString('base64'); + + return `data:image/png;base64, ${base64}`; }, serviceTotal() { let total = 0.00;