From e4c17492f0d98208bfa135708c348e77c66d8553 Mon Sep 17 00:00:00 2001 From: Bernat Exposito Domenech Date: Mon, 16 Dec 2019 09:22:59 +0100 Subject: [PATCH] update structure --- db/dump/structure.sql | 3606 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 3605 insertions(+), 1 deletion(-) diff --git a/db/dump/structure.sql b/db/dump/structure.sql index 761f07c39..b539efaa4 100644 --- a/db/dump/structure.sql +++ b/db/dump/structure.sql @@ -4845,6 +4845,3456 @@ DELIMITER ; /*!50003 SET character_set_results = @saved_cs_results */ ; /*!50003 SET collation_connection = @saved_col_connection */ ; +-- +-- Current Database: `bs` +-- + +CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */; + +USE `bs`; + +-- +-- Temporary table structure for view `bajasLaborales` +-- + +DROP TABLE IF EXISTS `bajasLaborales`; +/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `bajasLaborales` AS SELECT + 1 AS `firstname`, + 1 AS `name`, + 1 AS `business_id`, + 1 AS `lastDate`, + 1 AS `endContract`, + 1 AS `type`, + 1 AS `dias`, + 1 AS `userFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `bancos_evolution` +-- + +DROP TABLE IF EXISTS `bancos_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `bancos_evolution` ( + `Fecha` date NOT NULL, + `Id_Banco` int(11) NOT NULL, + `saldo` double NOT NULL DEFAULT '0', + `quilla` double NOT NULL DEFAULT '0', + `deuda` double NOT NULL DEFAULT '0', + `liquidez` double NOT NULL DEFAULT '0', + `disponibilidad ajena` double NOT NULL DEFAULT '0', + `saldo_aux` double NOT NULL DEFAULT '0' COMMENT 'Saldo auxiliar para el calculo de lo dispuesto en las polizas', + PRIMARY KEY (`Fecha`,`Id_Banco`), + KEY `fk_banco_evolution_idx` (`Id_Banco`), + CONSTRAINT `fk_banco_evolution` FOREIGN KEY (`Id_Banco`) REFERENCES `vn`.`bank` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los saldos bancarios'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `carteras` +-- + +DROP TABLE IF EXISTS `carteras`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `carteras` ( + `CodigoTrabajador` varchar(3) CHARACTER SET latin1 NOT NULL, + `Año` int(11) NOT NULL, + `Mes` int(11) NOT NULL, + `Peso` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`CodigoTrabajador`,`Año`,`Mes`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientDied` +-- + +DROP TABLE IF EXISTS `clientDied`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientDied` ( + `id` int(11) NOT NULL DEFAULT '0', + `clientName` varchar(50) COLLATE utf8_unicode_ci NOT NULL, + `lastInvoiced` date DEFAULT NULL, + `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `Boss` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `Aviso` varchar(13) CHARACTER SET utf8 DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `clientNewBorn` +-- + +DROP TABLE IF EXISTS `clientNewBorn`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `clientNewBorn` ( + `clientFk` int(11) NOT NULL, + `shipped` date NOT NULL, + PRIMARY KEY (`clientFk`), + CONSTRAINT `clientNewBorn_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Listado de clientes que se consideran nuevos a efectos de cobrar la comision adicional del comercial'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `compradores` +-- + +DROP TABLE IF EXISTS `compradores`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `compradores` ( + `Id_Trabajador` int(11) NOT NULL, + `año` int(4) NOT NULL, + `semana` int(2) NOT NULL, + `importe` decimal(10,2) DEFAULT NULL, + `comision` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`Id_Trabajador`,`año`,`semana`), + CONSTRAINT `comprador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `compradores_evolution` +-- + +DROP TABLE IF EXISTS `compradores_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `compradores_evolution` ( + `Id_Trabajador` int(11) NOT NULL, + `fecha` date NOT NULL, + `importe` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`Id_Trabajador`,`fecha`), + CONSTRAINT `evo_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `experienceIberflora2016` +-- + +DROP TABLE IF EXISTS `experienceIberflora2016`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `experienceIberflora2016` ( + `Id_Cliente` int(11) NOT NULL, + `isVisitor` tinyint(4) NOT NULL DEFAULT '0', + PRIMARY KEY (`Id_Cliente`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Lista de clientes que participan en el estudio sobre la mejora del consumo tras la visita a las instalaciones de Silla'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `fondo_maniobra` +-- + +DROP TABLE IF EXISTS `fondo_maniobra`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `fondo_maniobra` ( + `fecha` date NOT NULL, + `fondo` double DEFAULT NULL, + `clientes_facturas` double DEFAULT NULL, + `clientes_cobros` double DEFAULT NULL, + `proveedores_facturas` double DEFAULT NULL, + `proveedores_pagos` double DEFAULT NULL, + `fondo_medio` double DEFAULT NULL, + PRIMARY KEY (`fecha`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `indicators` +-- + +DROP TABLE IF EXISTS `indicators`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `indicators` ( + `updated` date NOT NULL, + `lastYearSales` int(11) DEFAULT NULL, + `totalGreuge` int(11) DEFAULT NULL, + `latePaymentRate` decimal(5,4) DEFAULT NULL, + `countEmployee` decimal(10,2) DEFAULT NULL, + `averageMana` int(11) DEFAULT NULL, + `bankingPool` int(11) DEFAULT NULL, + `lastMonthActiveClients` int(11) DEFAULT NULL, + `lastMonthLostClients` int(11) DEFAULT NULL, + `lastMonthNewClients` int(11) DEFAULT NULL, + `lastMonthWebBuyingRate` decimal(5,4) DEFAULT NULL, + `productionHours` decimal(10,1) DEFAULT NULL, + `dailyWorkersCost` decimal(10,0) DEFAULT NULL, + `volumeM3` decimal(10,0) DEFAULT NULL, + `salesValue` decimal(10,0) DEFAULT NULL, + `valueM3` decimal(10,0) DEFAULT NULL, + `hoursM3` decimal(5,2) DEFAULT NULL, + `workerCostM3` decimal(10,1) DEFAULT NULL, + `salesWorkersCostRate` decimal(10,2) DEFAULT NULL, + `thisWeekSales` decimal(10,2) DEFAULT NULL, + `lastYearWeekSales` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`updated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores actuales para una consulta diaria rápida por los directivos.'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `lastIndicators` +-- + +DROP TABLE IF EXISTS `lastIndicators`; +/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `lastIndicators` AS SELECT + 1 AS `updated`, + 1 AS `lastYearSales`, + 1 AS `incLastYearSales`, + 1 AS `totalGreuge`, + 1 AS `incTotalGreuge`, + 1 AS `latePaymentRate`, + 1 AS `incLatePaymentRate`, + 1 AS `countEmployee`, + 1 AS `incCountEmployee`, + 1 AS `averageMana`, + 1 AS `incAverageMana`, + 1 AS `bankingPool`, + 1 AS `incbankingPool`, + 1 AS `lastMonthActiveClients`, + 1 AS `incLastMonthActiveClients`, + 1 AS `lastMonthLostClients`, + 1 AS `incLastMonthLostClients`, + 1 AS `lastMonthNewClients`, + 1 AS `incLastMonthNewClients`, + 1 AS `lastMonthWebBuyingRate`, + 1 AS `incLastMonthWebBuyingRate`, + 1 AS `productionHours`, + 1 AS `dailyWorkersCost`, + 1 AS `volumeM3`, + 1 AS `salesValue`, + 1 AS `valueM3`, + 1 AS `hoursM3`, + 1 AS `workerCostM3`, + 1 AS `salesWorkersCostRate`, + 1 AS `thisWeekSales`, + 1 AS `lastYearWeekSales`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `m3` +-- + +DROP TABLE IF EXISTS `m3`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `m3` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `fecha` date NOT NULL, + `provinceFk` smallint(5) unsigned DEFAULT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '0', + `m3` decimal(10,2) DEFAULT NULL, + `year` int(11) DEFAULT NULL, + `month` int(11) DEFAULT NULL, + `week` int(11) DEFAULT NULL, + `day` int(11) DEFAULT NULL, + `dayName` varchar(12) COLLATE utf8_unicode_ci DEFAULT NULL, + `euros` decimal(10,2) DEFAULT '0.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `m3Silla` +-- + +DROP TABLE IF EXISTS `m3Silla`; +/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `m3Silla` AS SELECT + 1 AS `fecha`, + 1 AS `year`, + 1 AS `month`, + 1 AS `week`, + 1 AS `day`, + 1 AS `dayName`, + 1 AS `Volumen`, + 1 AS `Euros`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `m3analisis` +-- + +DROP TABLE IF EXISTS `m3analisis`; +/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `m3analisis` AS SELECT + 1 AS `fecha`, + 1 AS `year`, + 1 AS `month`, + 1 AS `week`, + 1 AS `day`, + 1 AS `dayName`, + 1 AS `Volumen`, + 1 AS `Euros`, + 1 AS `Departamento`, + 1 AS `Horas`, + 1 AS `Salarios`, + 1 AS `tiempoM3`, + 1 AS `valorM3`, + 1 AS `costeLaboralM3`, + 1 AS `costeEuros`, + 1 AS `precioHora`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `manaCustomer` +-- + +DROP TABLE IF EXISTS `manaCustomer`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `manaCustomer` ( + `Id_Cliente` int(11) NOT NULL, + `Mana` decimal(10,0) NOT NULL DEFAULT '0', + `dated` date NOT NULL, + PRIMARY KEY (`Id_Cliente`,`dated`), + KEY `manaCustomerIdx1` (`dated`), + CONSTRAINT `cliente_fk` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `manaSpellersExcluded` +-- + +DROP TABLE IF EXISTS `manaSpellersExcluded`; +/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `manaSpellersExcluded` AS SELECT + 1 AS `workerFk`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Temporary table structure for view `mana_spellers` +-- + +DROP TABLE IF EXISTS `mana_spellers`; +/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `mana_spellers` AS SELECT + 1 AS `Id_Trabajador`, + 1 AS `size`, + 1 AS `used`, + 1 AS `prices_modifier_rate`, + 1 AS `prices_modifier_activated`, + 1 AS `minRate`, + 1 AS `maxRate`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `mana_spellers_excluded` +-- + +DROP TABLE IF EXISTS `mana_spellers_excluded`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `mana_spellers_excluded` ( + `Id_Trabajador` int(11) NOT NULL, + PRIMARY KEY (`Id_Trabajador`), + CONSTRAINT `mana_spellers_excluded_fk1` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Usuarios que tienen que estar excluidos del cálculo del maná'; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `mermas` +-- + +DROP TABLE IF EXISTS `mermas`; +/*!50001 DROP VIEW IF EXISTS `mermas`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `mermas` AS SELECT + 1 AS `Comprador`, + 1 AS `Familia`, + 1 AS `Referencia`, + 1 AS `Item`, + 1 AS `Cantidad`, + 1 AS `Coste_Unitario`, + 1 AS `Importe`, + 1 AS `Cliente`, + 1 AS `ticketFk`, + 1 AS `Fecha`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `mermasCache` +-- + +DROP TABLE IF EXISTS `mermasCache`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `mermasCache` ( + `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `año` int(4) NOT NULL, + `Valor_Compra` decimal(10,0) DEFAULT NULL, + `Faltas` decimal(10,0) DEFAULT NULL, + `Basura` decimal(10,0) DEFAULT NULL, + PRIMARY KEY (`Comprador`,`año`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `nightTask` +-- + +DROP TABLE IF EXISTS `nightTask`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `nightTask` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `started` datetime DEFAULT NULL, + `finished` datetime DEFAULT NULL, + `lastFinished` datetime DEFAULT NULL, + `order` int(11) DEFAULT NULL, + `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL, + `error` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `errorCode` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeInsert` BEFORE INSERT ON `nightTask` FOR EACH ROW +BEGIN + + IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN + + CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`nightTaskBeforeUpdate` BEFORE UPDATE ON `nightTask` FOR EACH ROW +BEGIN + + IF NOT (NEW.`schema`REGEXP '^[0-9a-zA-Z_]+$') OR NOT (NEW.`procedure`REGEXP '^[0-9a-zA-Z_]+$') THEN + + CALL util.throw('ONLY_ALPHANUMERICS_ALLOWED'); + + END IF; + +END */;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + +-- +-- Table structure for table `nightTaskConfig` +-- + +DROP TABLE IF EXISTS `nightTaskConfig`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `nightTaskConfig` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `logMail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `payMethodClient` +-- + +DROP TABLE IF EXISTS `payMethodClient`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `payMethodClient` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `payMethodFk` tinyint(3) unsigned NOT NULL DEFAULT '0', + `clientFk` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`id`), + KEY `FkPayMethod_idx` (`payMethodFk`), + KEY `FkClientPayMethod_idx` (`clientFk`), + KEY `FkDateClientPayMethod` (`dated`,`clientFk`), + CONSTRAINT `FkClientPayMethod` FOREIGN KEY (`clientFk`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `FkPayMethodClient` FOREIGN KEY (`payMethodFk`) REFERENCES `vn`.`payMethod` (`id`) ON UPDATE CASCADE +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_bin; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `payMethodClientEvolution` +-- + +DROP TABLE IF EXISTS `payMethodClientEvolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `payMethodClientEvolution` ( + `id` int(11) NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `payMethodName` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `amountClient` int(11) NOT NULL, + `amount` decimal(10,2) NOT NULL, + `equalizationTax` decimal(10,2) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivity` +-- + +DROP TABLE IF EXISTS `productivity`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `productivity` ( + `id` int(10) unsigned NOT NULL AUTO_INCREMENT, + `dated` date NOT NULL, + `hh` int(10) unsigned NOT NULL, + `mm` int(10) unsigned NOT NULL, + `m3` double NOT NULL DEFAULT '0', + `workers` int(11) NOT NULL DEFAULT '0', + `wCost` double NOT NULL DEFAULT '0', + `numCoordinadores` int(11) NOT NULL DEFAULT '0', + `costCoordinacion` double NOT NULL DEFAULT '0', + `numSacadores` int(11) NOT NULL DEFAULT '0', + `costSacado` double NOT NULL DEFAULT '0', + `numEncajadores` int(11) NOT NULL DEFAULT '0', + `costEncajado` double NOT NULL DEFAULT '0', + `numPaletizadores` int(11) NOT NULL DEFAULT '0', + `costPaletizado` double NOT NULL DEFAULT '0', + `numCamareros` int(11) NOT NULL DEFAULT '0', + `costCamara` double NOT NULL DEFAULT '0', + `numComplementos` int(11) NOT NULL DEFAULT '0', + `costComplementos` double NOT NULL DEFAULT '0', + `numArtificial` int(11) NOT NULL DEFAULT '0', + `costArtificial` double NOT NULL DEFAULT '0', + `m3FV` double NOT NULL DEFAULT '0', + `m3PCA` double NOT NULL DEFAULT '0', + `m3Artificial` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`id`) +) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivityDepartment` +-- + +DROP TABLE IF EXISTS `productivityDepartment`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `productivityDepartment` ( + `dated` date NOT NULL, + `amountCoordinacion` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountSacado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountEncajado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountPaletizado` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountCamara` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountComplementos` decimal(10,2) NOT NULL DEFAULT '0.00', + `amountArtificial` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `productivity_evolution` +-- + +DROP TABLE IF EXISTS `productivity_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `productivity_evolution` ( + `dated` date NOT NULL, + `m3productionCost` decimal(10,2) NOT NULL DEFAULT '0.00', + PRIMARY KEY (`dated`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `salaries2018` +-- + +DROP TABLE IF EXISTS `salaries2018`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `salaries2018` ( + `person_id` int(11) NOT NULL DEFAULT '0', + `sex` enum('M','F') CHARACTER SET utf8 NOT NULL DEFAULT 'F' COMMENT 'M Masculino F Femenino', + `edad` int(6) DEFAULT NULL, + `antiguedad` int(6) DEFAULT NULL, + `Modalidad` varchar(22) CHARACTER SET utf8mb4 NOT NULL DEFAULT '', + `reason` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, + `worker` varchar(82) CHARACTER SET utf8 DEFAULT NULL, + `totalDays` decimal(32,0) DEFAULT NULL, + `totalAnual` decimal(16,0) DEFAULT NULL, + `virtualMonthlySalary` decimal(16,0) DEFAULT NULL, + `departamento` varchar(45) COLLATE utf8_unicode_ci NOT NULL, + `category_name` varchar(50) CHARACTER SET utf8 NOT NULL, + `level_name` varchar(5) CHARACTER SET utf8 DEFAULT NULL, + `thisYearDateStart` varchar(10) CHARACTER SET utf8mb4 DEFAULT NULL, + PRIMARY KEY (`person_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `salePersonEvolution` +-- + +DROP TABLE IF EXISTS `salePersonEvolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `salePersonEvolution` ( + `dated` date NOT NULL DEFAULT '0000-00-00', + `amount` decimal(10,2) NOT NULL DEFAULT '0.00', + `equalizationTax` decimal(10,2) NOT NULL DEFAULT '0.00', + `salesPersonFk` int(11) NOT NULL DEFAULT '0', + PRIMARY KEY (`dated`,`salesPersonFk`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `salesByWeek` +-- + +DROP TABLE IF EXISTS `salesByWeek`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `salesByWeek` ( + `week` int(11) NOT NULL, + `year` int(11) NOT NULL, + `sales` double DEFAULT NULL, + UNIQUE KEY `week` (`week`,`year`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vendedores` +-- + +DROP TABLE IF EXISTS `vendedores`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vendedores` ( + `Id_Trabajador` int(11) NOT NULL, + `año` int(4) NOT NULL, + `mes` int(2) NOT NULL, + `importe` decimal(10,2) DEFAULT NULL, + `comision` decimal(10,2) DEFAULT NULL, + `comisionArrendada` decimal(10,2) DEFAULT NULL COMMENT 'comision proveniente de clientes que han sido donados. Ver tabla Clientes_cedidos', + `comisionCedida` decimal(10,2) DEFAULT NULL COMMENT 'comision generada por los clientes que han sido donados. Ver tabla Clientes_cedidos', + `comisionNuevos` decimal(10,2) DEFAULT NULL, + PRIMARY KEY (`Id_Trabajador`,`año`,`mes`), + CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `vendedores_evolution` +-- + +DROP TABLE IF EXISTS `vendedores_evolution`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `vendedores_evolution` ( + `workerFk` int(11) NOT NULL, + `year` int(11) NOT NULL, + `sales` decimal(10,2) DEFAULT NULL, + `month` int(11) NOT NULL, + PRIMARY KEY (`workerFk`,`year`,`month`), + CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`workerFk`) REFERENCES `vn`.`worker` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ventas` +-- + +DROP TABLE IF EXISTS `ventas`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ventas` ( + `Id_Movimiento` int(11) NOT NULL, + `importe` decimal(10,3) NOT NULL DEFAULT '0.000', + `recargo` decimal(10,3) NOT NULL DEFAULT '0.000', + `fecha` date NOT NULL, + `tipo_id` smallint(5) unsigned NOT NULL, + `Id_Cliente` int(11) NOT NULL DEFAULT '1', + `empresa_id` smallint(5) unsigned NOT NULL DEFAULT '442', + PRIMARY KEY (`Id_Movimiento`), + KEY `tip_to_tip_idx` (`tipo_id`), + KEY `clientes_bs_ventas_idx` (`Id_Cliente`), + KEY `empresa_bs_ventas_idx` (`empresa_id`), + KEY `fecha_bs` (`fecha`), + CONSTRAINT `clientes_bs_ventas` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn`.`client` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn`.`company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn`.`sale` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, + CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn`.`itemType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `ventas_contables` +-- + +DROP TABLE IF EXISTS `ventas_contables`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `ventas_contables` ( + `year` int(4) NOT NULL, + `month` int(2) NOT NULL, + `venta` decimal(10,2) DEFAULT NULL, + `grupo` int(1) NOT NULL, + `reino_id` int(10) unsigned NOT NULL, + `tipo_id` smallint(5) unsigned NOT NULL, + `empresa_id` int(4) NOT NULL, + `gasto` varchar(10) CHARACTER SET latin1 NOT NULL, + PRIMARY KEY (`year`,`month`,`grupo`,`reino_id`,`tipo_id`,`empresa_id`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Table structure for table `warehouseProduction_kk` +-- + +DROP TABLE IF EXISTS `warehouseProduction_kk`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `warehouseProduction_kk` ( + `fecha` date NOT NULL, + `warehouse_id` smallint(6) unsigned NOT NULL, + `m3` decimal(10,0) NOT NULL DEFAULT '0', + `labourCost` decimal(10,0) NOT NULL DEFAULT '0', + `workerHours` decimal(10,0) NOT NULL DEFAULT '0', + PRIMARY KEY (`fecha`,`warehouse_id`), + KEY `warehouseProduction_fk1_idx` (`warehouse_id`), + CONSTRAINT `warehouseProduction_fk1` FOREIGN KEY (`warehouse_id`) REFERENCES `vn`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Temporary table structure for view `workerMana` +-- + +DROP TABLE IF EXISTS `workerMana`; +/*!50001 DROP VIEW IF EXISTS `workerMana`*/; +SET @saved_cs_client = @@character_set_client; +SET character_set_client = utf8; +/*!50001 CREATE VIEW `workerMana` AS SELECT + 1 AS `workerFk`, + 1 AS `amount`*/; +SET character_set_client = @saved_cs_client; + +-- +-- Table structure for table `workerSpeed` +-- + +DROP TABLE IF EXISTS `workerSpeed`; +/*!40101 SET @saved_cs_client = @@character_set_client */; +/*!40101 SET character_set_client = utf8 */; +CREATE TABLE `workerSpeed` ( + `workerCode` varchar(3) COLLATE utf8_unicode_ci NOT NULL, + `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL, + `warehouseFk` smallint(6) unsigned NOT NULL DEFAULT '1', + `LitrosMinuto` decimal(10,1) DEFAULT NULL, + `LitrosMinutoLastHour` decimal(10,1) DEFAULT NULL, + `lastUpdated` datetime NOT NULL DEFAULT '0000-00-00 00:00:00', + PRIMARY KEY (`workerCode`,`warehouseFk`,`accion`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; +/*!40101 SET character_set_client = @saved_cs_client */; + +-- +-- Dumping events for database 'bs' +-- +/*!50106 SET @save_time_zone= @@TIME_ZONE */ ; +/*!50106 DROP EVENT IF EXISTS `nightTask_launchAll` */; +DELIMITER ;; +/*!50003 SET @saved_cs_client = @@character_set_client */ ;; +/*!50003 SET @saved_cs_results = @@character_set_results */ ;; +/*!50003 SET @saved_col_connection = @@collation_connection */ ;; +/*!50003 SET character_set_client = utf8mb4 */ ;; +/*!50003 SET character_set_results = utf8mb4 */ ;; +/*!50003 SET collation_connection = utf8mb4_unicode_ci */ ;; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ;; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ;; +/*!50003 SET @saved_time_zone = @@time_zone */ ;; +/*!50003 SET time_zone = 'SYSTEM' */ ;; +/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightTask_launchAll` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTask_launchAll */ ;; +/*!50003 SET time_zone = @saved_time_zone */ ;; +/*!50003 SET sql_mode = @saved_sql_mode */ ;; +/*!50003 SET character_set_client = @saved_cs_client */ ;; +/*!50003 SET character_set_results = @saved_cs_results */ ;; +/*!50003 SET collation_connection = @saved_col_connection */ ;; +DELIMITER ; +/*!50106 SET TIME_ZONE= @save_time_zone */ ; + +-- +-- Dumping routines for database 'bs' +-- +/*!50003 DROP FUNCTION IF EXISTS `tramo` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` FUNCTION `tramo`(vDateTime DATETIME) RETURNS varchar(20) CHARSET utf8 COLLATE utf8_unicode_ci +BEGIN + + DECLARE vTramo VARCHAR(20); + DECLARE vHour INT; + + SET vHour = HOUR(vDateTime) ; + + SET vTramo = + CASE + WHEN vHour BETWEEN 0 AND 14 THEN 'Mañana' + WHEN vHour BETWEEN 15 AND 24 THEN 'Tarde' + END ; + +RETURN vTramo; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `analisisComponentes` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `analisisComponentes`() +BEGIN + +DECLARE vDateStart DATE DEFAULT '2016-01-01'; +DECLARE vDateEnd DATE DEFAULT '2016-11-30'; +DECLARE vDate DATE; + +SET vDate = vDateStart; + +DELETE FROM bs.ventasComponentes; + +WHILE vDate <= vDateEnd DO + + INSERT INTO bs.ventasComponentes + SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe + FROM vn2008.Movimientos_componentes mc + JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento + JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento + WHERE v.fecha = vDate + AND empresa_id IN (442,567) + GROUP BY mc.Id_Componente; + + SET vDate = TIMESTAMPADD(DAY,1,vDate); + + IF DAY(vDate) MOD 28 = 0 THEN + + SELECT vDate; + + END IF; + +END WHILE; + + SELECT vDate; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `bancos_evolution_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `bancos_evolution_add`() +BEGIN + /* + + Inserta en la tabla bancos_evolution los saldos acumulados + + */ + + + DECLARE vCurrentDate DATE; + DECLARE vStartingDate DATE DEFAULT '2016-01-01'; + DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 7, CURDATE()); + + DELETE FROM bs.bancos_evolution WHERE Fecha > vStartingDate; + + SET vCurrentDate = vStartingDate; + + WHILE vCurrentDate < vMaxDate DO + + REPLACE bs.bancos_evolution( Fecha + ,Id_Banco + ,saldo) + + SELECT vCurrentDate + , Id_Banco + , sum(saldo) + + FROM + ( + + SELECT Id_Banco + ,saldo_aux as saldo + FROM bs.bancos_evolution + + WHERE Fecha = TIMESTAMPADD(DAY,-1,vCurrentDate) -- los saldos acumulados del dia anterior + + UNION ALL + + SELECT c.Id_Banco, IFNULL(sum(Entrada),0) - ifnull(sum(Salida),0) as saldo + FROM vn2008.Cajas c + JOIN vn2008.Bancos b using(Id_Banco) -- saldos de las cajas + WHERE cash IN (0,3) + AND Cajafecha = vCurrentDate + AND (Serie = 'MB' OR cash = 3) + GROUP BY Id_Banco + + UNION ALL + + SELECT id_banco, - importe -- pagos futuros + FROM vn2008.pago + WHERE fecha = vCurrentDate + AND fecha >= CURDATE() + AND NOT conciliado + + UNION ALL + + SELECT Id_Banco, Entregado -- cobros futuros + FROM vn2008.Recibos + WHERE Fechacobro = vCurrentDate + AND Fechacobro > CURDATE() + + UNION ALL + + SELECT sp.Id_Banco, Importe -- saldos de la tabla prevision + FROM vn2008.Saldos_Prevision sp + JOIN vn2008.Bancos b using(Id_Banco) + WHERE cash IN (0,3) + AND Fecha = vCurrentDate + + + + )sub + GROUP BY Id_Banco; + + -- Utilizamos el saldo_auxiliar para calcular lo dispuesto en las polizas + + UPDATE bs.bancos_evolution be + SET saldo_aux = saldo; + + -- Ahora actualizamos la quilla + UPDATE bs.bancos_evolution be + LEFT JOIN + ( + SELECT Id_Banco, - sum(importe) as quilla + FROM vn2008.Bancos_poliza + WHERE vCurrentDate between apertura AND IFNULL(cierre, vCurrentDate) + GROUP BY Id_Banco + ) sub using(Id_Banco) + SET be.quilla = sub.quilla + WHERE be.Fecha = vCurrentDate; + + + SET vCurrentDate = TIMESTAMPADD(DAY,1,vCurrentDate); + + END WHILE; + + + -- Deuda + UPDATE bs.bancos_evolution be + JOIN vn2008.Bancos using(Id_Banco) + SET be.deuda = IF(cash = 3, be.saldo_aux, 0) + , be.saldo = IF(cash = 3, 0, be.saldo_aux) + WHERE Fecha >= vStartingDate; + + + -- Liquidez + update bs.bancos_evolution set liquidez = saldo - quilla + deuda WHERE Fecha >= vStartingDate; + + -- Disponibilidad + update bs.bancos_evolution set `disponibilidad ajena` = - quilla + deuda WHERE Fecha >= vStartingDate; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `campaignComparative` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `campaignComparative`(vDateFrom DATE, vDateTo DATE) +BEGIN + SELECT + workerName, + id, + name, + CAST(SUM(previousAmmount) AS DECIMAL(10, 0)) AS previousAmmount, + CAST(SUM(currentAmmount) AS DECIMAL(10, 0)) AS currentAmmount + FROM ( + (SELECT + CONCAT(w.firstname, ' ', w.lastName) AS workerName, + c.id, + c.name, + SUM(v.importe) AS previousAmmount, + 0 currentAmmount + FROM bs.ventas v + INNER JOIN vn.`client` c ON v.Id_Cliente = c.id + INNER JOIN vn.worker w ON c.salesPersonFk = w.id + WHERE v.fecha BETWEEN DATE_ADD(vDateFrom, INTERVAL - 1 YEAR) + AND DATE_ADD(vDateTo, INTERVAL - 1 YEAR) + GROUP BY w.id, v.Id_Cliente) + UNION ALL + (SELECT + CONCAT(w.firstname, ' ', w.lastName) AS workerName, + c.id, + c.name, + 0 AS previousAmmount, + SUM(s.quantity * s.price) AS currentAmmount + FROM vn.sale s + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN vn.client c ON c.id = t.clientFk + JOIN vn.worker w ON c.salesPersonFk = w.id + WHERE t.shipped BETWEEN vDateFrom + AND vDateTo + GROUP BY w.id, c.id) + ) comparative + GROUP BY workerName, id + HAVING (previousAmmount <> 0 OR currentAmmount <> 0) + ORDER BY workerName, id; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `carteras_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `carteras_add`() +BEGIN + +DELETE FROM bs.carteras +WHERE Año >= YEAR(CURDATE()) - 1; + +INSERT INTO bs.carteras(Año,Mes,CodigoTrabajador,Peso) +SELECT year as Año, month as Mes, CodigoTrabajador, sum(importe) as Peso +FROM vn2008.time t +JOIN bs.ventas v on t.date = v.fecha +JOIN vn2008.Clientes c on c.Id_Cliente = v.Id_Cliente +JOIN vn2008.Trabajadores tr on tr.Id_Trabajador = c.Id_Trabajador +WHERE t.year >= YEAR(CURDATE()) - 1 +GROUP BY CodigoTrabajador, Año, Mes; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `clientDied` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientDied`() +BEGIN + + IF DAY(CURDATE()) = 6 THEN + + SET @primerAviso := TIMESTAMPADD(MONTH,-1,CURDATE()); + SET @segundoAviso := TIMESTAMPADD(MONTH,-2,CURDATE()); + SET @tercerAviso := TIMESTAMPADD(MONTH,-3,CURDATE()); + + TRUNCATE TABLE bs.clientDied; + + INSERT INTO bs.clientDied + SELECT c.id, + c.name as clientName, + maxIssued as lastInvoiced, + w.code AS workerCode, + b.code AS Boss, + CASE + WHEN IFNULL(maxIssued,'2000-01-01') < @tercerAviso THEN 'Tercer Aviso' + WHEN maxIssued < @segundoAviso THEN 'Segundo Aviso' + WHEN maxIssued < @primerAviso THEN 'Primer Aviso' + END as Aviso + FROM vn.client c + JOIN vn.worker w ON w.id = c.salesPersonFk + JOIN vn2008.jerarquia j ON j.worker_id = w.id + JOIN vn.worker b ON b.id = j.boss_id + JOIN bs.mana_spellers ms ON ms.Id_Trabajador = c.salesPersonFk + LEFT JOIN (SELECT clientFk, max(issued) as maxIssued FROM vn.invoiceOut GROUP BY clientFk) io ON io.clientFk = c.id + WHERE (maxIssued IS NULL OR maxIssued < @primerAviso) + AND c.created < @tercerAviso; + + END IF; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `clientNewBorn_Update` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `clientNewBorn_Update`() +BEGIN + + DECLARE fromDated DATE DEFAULT '2019-04-01'; + + -- Eliminamos clientes que ya no son nuevos + DELETE FROM bs.clientNewBorn + WHERE shipped < TIMESTAMPADD(YEAR,-1,CURDATE()); + + -- Clientes nuevos + REPLACE bs.clientNewBorn(clientFk,shipped) + SELECT t.clientFk, MIN(t.shipped) as shipped + FROM vn.ticket t + WHERE shipped > '2001-01-01' + GROUP BY t.clientFk + HAVING shipped >= GREATEST(TIMESTAMPADD(YEAR,-1,CURDATE()), fromDated); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `comercialesCompleto` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `comercialesCompleto`(IN vWorker INT, vDate DATE) +BEGIN + +CALL vn.subordinateGetList(vWorker); + +SELECT + c.Id_Cliente id_cliente, + c.calidad, + c.Cliente cliente, + cr.recobro * 100 tarifa, + c.Telefono telefono, + c.movil, + c.POBLACION poblacion, + p.`name` provincia, + vn2008.red(f.futur) futur, + c.Credito credito, + pm.`name` forma_pago, + vn2008.red(c365 / 12) consumo_medio365, + vn2008.red(c365) consumo365, + vn2008.red(CmLy.peso) peso_mes_año_pasado, + vn2008.red(CmLy.peso * 1.19) objetivo, + tr.CodigoTrabajador, + vn2008.red(mes_actual.consumo) consumoMes, + vn2008.red(IFNULL(mes_actual.consumo, 0) - IFNULL(CmLy.peso * 1.19, 0)) como_lo_llevo, + DATE(LastTicket) ultimo_ticket, + dead.muerto, + g.Greuge, + cr.recobro +FROM + vn2008.Clientes c + LEFT JOIN + (SELECT Id_Cliente, CAST( SUM(Importe) as DECIMAL(12,2)) AS Greuge + FROM vn2008.Greuges + GROUP BY Id_Cliente + ) g ON g.Id_Cliente = c.Id_Cliente + LEFT JOIN + vn2008.province p ON p.province_id = c.province_id + JOIN + vn2008.pay_met pm ON pm.id = c.pay_met_id + LEFT JOIN + vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + LEFT JOIN + bi.claims_ratio cr on cr.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT v.Id_Cliente, SUM(importe) c365 -- optimizat de 6s /5.3s/ 4.7s a 0.3/0.4/0.3 + FROM bs.ventas v + JOIN vn2008.Clientes c USING (Id_Cliente) + + WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, vDate) AND vDate + GROUP BY v.Id_Cliente) c365 ON c365.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + Id_Cliente, SUM(importe) consumo + FROM + bs.ventas v + INNER JOIN vn2008.Clientes c USING (Id_Cliente) + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + AND (v.fecha BETWEEN TIMESTAMPADD(DAY, - DAY(vDate) + 1, vDate) AND TIMESTAMPADD(DAY, - 1, vDate)) + GROUP BY Id_Cliente) mes_actual ON mes_actual.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + t.Id_Cliente, + SUM(m.preu * m.Cantidad * (1 - m.Descuento / 100)) futur + FROM + vn2008.Tickets t + JOIN vn2008.Clientes c ON c.Id_Cliente = t.Id_Cliente + JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + AND DATE(Fecha) BETWEEN vDate AND LAST_DAY(vDate) + GROUP BY Id_Cliente) f ON c.Id_Cliente = f.Id_Cliente + LEFT JOIN + (SELECT + MAX(t.Fecha) LastTicket, c.Id_Cliente + FROM + vn2008.Tickets t + JOIN vn2008.Clientes c ON c.Id_cliente = t.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY t.Id_Cliente) LastTicket ON LastTicket.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + SUM(importe) peso, c.Id_Cliente + FROM + bs.ventas v + JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + MONTH(fecha) = MONTH(vDate) + AND YEAR(fecha) = YEAR(vDate) - 1 + AND (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY c.Id_Cliente) CmLy ON CmLy.Id_Cliente = c.Id_Cliente + LEFT JOIN + (SELECT + c.Id_Cliente, + IF(MAX(Fecha) < DATE_FORMAT(TIMESTAMPADD(MONTH, - 1, vDate), '%Y- %m-01'), TRUE, FALSE) muerto + FROM + vn2008.Facturas f + JOIN vn2008.Clientes c ON c.Id_cliente = f.Id_Cliente + + LEFT JOIN vn2008.Trabajadores tr ON c.Id_Trabajador = tr.Id_Trabajador + WHERE + (c.Id_Trabajador = vWorker OR tr.boss = vWorker) + GROUP BY Id_Cliente) dead ON dead.Id_Cliente = c.Id_Cliente + JOIN tmp.subordinate s ON s.workerFk = c.Id_Trabajador; + +DROP TEMPORARY TABLE tmp.subordinate; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `compradores_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add`(IN intYEAR INT, IN intWEEK_START INT, IN intWEEK_END INT) +BEGIN + +REPLACE bs.compradores + +SELECT tp.Id_Trabajador + , intYEAR as año + , tm.week as semana + , sum(importe) as importe + , 0 as comision + +FROM bs.ventas v +JOIN vn2008.time tm on tm.date = v.fecha +JOIN vn2008.Tipos tp using(tipo_id) +WHERE tm.year = intYEAR and tm.week between intWEEK_START and intWEEK_END +AND reino_id != 6 +GROUP BY tp.Id_Trabajador, tm.week; + + + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `compradores_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compradores_add_launcher`() +BEGIN + + DECLARE vYear INT; + DECLARE vWeek INT; + DECLARE done BOOL DEFAULT FALSE; + + DECLARE rs CURSOR FOR + SELECT year, week + FROM vn.time + WHERE (year = vYear AND week >= vWeek) + OR year > vYear; + + DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE; + + SELECT MAX(año) INTO vYear + FROM compradores; + + SELECT MAX(semana) INTO vWeek + FROM compradores + WHERE año = vYear; + + OPEN rs; + + FETCH rs INTO vYear, vWeek; + + WHILE NOT done DO + + CALL compradores_add(vYear, vWeek, vWeek); + + FETCH rs INTO vYear, vWeek; + + END WHILE; + + CLOSE rs; + + CALL compradores_evolution_add; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `compradores_evolution_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `compradores_evolution_add`() +BEGIN +/* + +Inserta en la tabla compradores_evolution las ventas acumuladas en los ultimos 365 dias + +*/ + +DECLARE datFEC DATE; + + +SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.compradores_evolution; + + WHILE datFEC < CURDATE() DO + + SELECT datFEC; + + REPLACE bs.compradores_evolution( Id_Trabajador + , fecha + , importe) + + SELECT Id_Trabajador + , datFEC as fecha + , sum(importe) as importe + + FROM + ( + + SELECT Id_Trabajador + , importe + FROM bs.compradores_evolution + WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC) -- las ventas acumuladas del dia anterior + + UNION ALL + + SELECT Id_Trabajador + , importe * IF(v.fecha < datFEC,-1,1) -- se restan las ventas del año anterior y se suman las del actual + FROM bs.ventas v + JOIN vn2008.Tipos tp using(tipo_id) + WHERE fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC)) + AND reino_id != 6 + + )sub + GROUP BY Id_Trabajador; + + + + + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `fondo_evolution_add` */; +ALTER DATABASE `bs` CHARACTER SET latin1 COLLATE latin1_swedish_ci ; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `fondo_evolution_add`() +BEGIN +/* + +Inserta en la tabla fondo_maniobra los saldos acumulados en los ultimos 365 dias + +*/ + +DECLARE datFEC DATE DEFAULT '2015-01-01'; + + +SELECT TIMESTAMPADD(DAY,1,MAX(fecha)) INTO datFEC FROM bs.fondo_maniobra; + + WHILE datFEC < CURDATE() DO + + -- esto solo sirve para no aburrirse mientras esperamos... + + IF day(datFEC) mod 28 = 0 then + SELECT datFEC; + end if; + + + REPLACE bs.fondo_maniobra(Fecha, clientes_facturas, clientes_cobros,proveedores_facturas,proveedores_pagos, fondo) + SELECT datFEC as Fecha, Facturas, Cobros,Recibidas,Pagos, Facturas + Cobros + Recibidas + Pagos + FROM + ( + SELECT Sum(Facturas.Importe) AS Facturas + FROM vn2008.Facturas + INNER JOIN vn2008.Clientes ON Facturas.Id_Cliente = Clientes.Id_cliente + WHERE Clientes.`real` + AND empresa_id <>1381 + AND Fecha between '2011-01-01' and datFEC) fac + JOIN + ( + SELECT - Sum(Entregado) AS Cobros + FROM vn2008.Recibos + INNER JOIN vn2008.Clientes ON Recibos.Id_Cliente = Clientes.Id_cliente + WHERE Clientes.`real` + AND empresa_id <> 1381 + AND Fechacobro Between '2011-01-01' and datFEC) cob + JOIN + ( + SELECT - Sum(cantidad) AS Recibidas + FROM vn2008.recibida + INNER JOIN vn2008.recibida_vencimiento ON recibida.id = recibida_vencimiento.recibida_id + WHERE empresa_id <> 1381 + AND recibida.fecha Between '2015-01-01' and datFEC) rec + JOIN + ( + SELECT Sum(importe) AS Pagos + FROM vn2008.pago + WHERE empresa_id <>1381 AND pago.fecha Between '2015-01-01' and datFEC) pag; + + + + UPDATE bs.fondo_maniobra + JOIN + (SELECT avg(fondo) as media + FROM bs.fondo_maniobra + WHERE fecha <= datFEC) sub + SET fondo_medio = media + WHERE fecha = datFEC; + + + SET datFEC = TIMESTAMPADD(DAY,1,datFEC); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ; +/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdate`(vDated DATE) +BEGIN + + DECLARE oneYearBefore DATE DEFAULT TIMESTAMPADD(YEAR,-1,vDated); + DECLARE twoMonthsBefore DATE DEFAULT TIMESTAMPADD(DAY,-60,vDated); + DECLARE oneMonthBefore DATE DEFAULT TIMESTAMPADD(DAY,-30,vDated); + DECLARE vWeek INT; + + REPLACE indicators(updated) + VALUES(vDated); + + -- Ventas totales del ultimo año + UPDATE indicators + SET lastYearSales = + ( + SELECT SUM(importe + recargo) + FROM bs.ventas v + JOIN vn2008.empresa e ON e.id = v.empresa_id + JOIN vn2008.empresa_grupo eg ON eg.empresa_grupo_id = e.empresa_grupo + WHERE fecha BETWEEN oneYearBefore AND vDated + AND eg.grupo = 'Verdnatura' + ) + WHERE updated = vDated; + + -- Greuge total acumulado + UPDATE indicators + SET totalGreuge = + ( + SELECT SUM(amount) + FROM vn.greuge + WHERE shipped <= vDated + ) + WHERE updated = vDated; + + + -- Tasa de morosidad con respecto a las ventas del último mes + UPDATE indicators + SET latePaymentRate = + (SELECT SUM(amount) FROM bi.defaulters WHERE date = vDated and amount > 0) + / + ( SELECT SUM(importe + recargo) FROM bs.ventas WHERE fecha BETWEEN oneMonthBefore AND vDated) + WHERE updated = vDated; + + -- Número de trabajadores activos + UPDATE indicators + SET countEmployee = + ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) + FROM + postgresql.business AS b + JOIN postgresql.profile p ON p.profile_id = b.provider_id + JOIN postgresql.person pe ON pe.person_id = p.person_id + LEFT JOIN + postgresql.business_labour AS bl ON bl.business_id = b.business_id + LEFT JOIN + postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + WHERE + (vDated BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDated)) + AND pe.name = 'VERDNATURA LEVANTE SL' + ) + WHERE updated = vDated; + + -- Maná medio acumulado por comercial + UPDATE indicators + SET averageMana = + (SELECT avg(used) + FROM bs.mana_spellers + ) + WHERE updated = vDated; + + -- Número de clientes que han comprado en los últimos 30 dias + UPDATE indicators + SET lastMonthActiveClients = + (SELECT COUNT(DISTINCT t.clientFk) + FROM vn.ticket t + WHERE t.shipped BETWEEN oneMonthBefore AND vDated + ) + WHERE updated = vDated; + + -- Número de clientes que no han comprado en los últimos 30 dias, pero compraron en los 30 anteriores + UPDATE indicators + SET lastMonthLostClients = + (SELECT COUNT(lm.clientFk) + FROM + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped BETWEEN oneMonthBefore AND vDated + ) cm + RIGHT JOIN + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped >= twoMonthsBefore + AND t.shipped < oneMonthBefore + ) lm ON lm.clientFk = cm.clientFk + WHERE cm.clientFk IS NULL + ) + WHERE updated = vDated; + + -- Número de clientes que han comprado en los últimos 30 dias, pero no compraron en los 30 anteriores + UPDATE indicators + SET lastMonthNewClients = + (SELECT COUNT(cm.clientFk) + FROM + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped BETWEEN oneMonthBefore AND vDated + ) cm + LEFT JOIN + ( + SELECT DISTINCT t.clientFk + FROM vn.ticket t + WHERE t.shipped >= twoMonthsBefore + AND t.shipped < oneMonthBefore + ) lm ON lm.clientFk = cm.clientFk + WHERE lm.clientFk IS NULL + ) + WHERE updated = vDated; + + -- Porcentaje de autopedidos sobre los pedidos totales + UPDATE indicators + SET lastMonthWebBuyingRate = + ( SELECT (SUM(source_app != '') - SUM(source_app = 'TPV')) / SUM(source_app != '') + FROM hedera.`order` + WHERE date_send BETWEEN oneMonthBefore AND vDated + ) + WHERE updated = vDated; + + -- Indicadores de producción + UPDATE indicators i + JOIN productionIndicators pi ON pi.dated = i.updated + SET i.productionHours = pi.productionHours, + i.dailyWorkersCost = pi.dailyWorkersCost, + i.volumeM3 = pi.volumeM3, + i.salesValue = pi.salesValue, + i.valueM3 = pi.valueM3, + i.hoursM3 = pi.hoursM3, + i.workerCostM3 = pi.workerCostM3, + i.salesWorkersCostRate = pi.salesWorkersCostRate + WHERE updated BETWEEN oneMonthBefore AND vDated; + + -- CAP Para el calculo de las ventas agrupado por semanas + + SELECT week + FROM vn.time + WHERE dated=vDated INTO vWeek; + + TRUNCATE `bs`.`salesByWeek`; + + INSERT INTO `bs`.`salesByWeek` (week,year,sales) + SELECT `t`.`week` AS `week`,`t`.`year` AS `year`, SUM(`v`.`importe` + `v`.`recargo`) AS `sales` + FROM `bs`.`ventas` `v` + LEFT JOIN `vn`.`time` `t` ON `t`.`dated` = fecha + GROUP BY `t`.`week` , `t`.`year` + ORDER BY `t`.`week` , `t`.`year`; + + -- CAP Indicador Ventas semana actual + UPDATE indicators i + JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated) + SET i.thisWeekSales = s.sales + WHERE updated = vDated; + + -- CAP indicador ventas semana actual en el año pasado + UPDATE indicators i + JOIN `bs`.`salesByWeek` s ON s.week= vWeek AND s.year = YEAR(vDated)-1 + SET i.lastYearWeekSales = s.sales + WHERE updated = vDated; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `indicatorsUpdateLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `indicatorsUpdateLauncher`() +BEGIN + + DECLARE vDated DATE; + + SELECT IFNULL(TIMESTAMPADD(DAY,1,MAX(updated)), '2018-04-01') + INTO vDated + FROM bs.indicators; + + WHILE vDated < CURDATE() DO + + CALL indicatorsUpdate(vDated); + + SELECT TIMESTAMPADD(DAY,1,MAX(updated)) + INTO vDated + FROM bs.indicators; + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `m3Add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `m3Add`() +BEGIN + + DECLARE datSTART DATE; + DECLARE datEND DATE; + + SELECT TIMESTAMPADD(WEEK, -1,MAX(fecha)) INTO datSTART + FROM bs.m3; + + SET datEND = TIMESTAMPADD(DAY,-1,CURDATE()); + + DELETE FROM bs.m3 + WHERE fecha >= datSTART; + + INSERT INTO bs.m3 (fecha, provinceFk, warehouseFk, m3, year, month, week, day, dayName, euros) + SELECT v.fecha, a.provinceFk, t.warehouseFk, sum(i.compression * s.quantity * r.cm3) / 1000000 AS m3, + tm.year, tm.month, tm.week, tm.day, dayname(v.fecha), sum(importe) + FROM vn.ticket t + JOIN vn.sale s ON s.ticketFk = t.id + JOIN vn.item i ON i.id = s.itemFk + JOIN vn.itemType it ON it.id = i.typeFk + JOIN bs.ventas v ON v.Id_Movimiento = s.id -- Filtra solo por ventas "buenas" + JOIN vn.time tm ON tm.dated = v.fecha + JOIN bi.rotacion r ON r.Id_Article = s.itemFk AND r.warehouse_id = t.warehouseFk + JOIN vn.address a ON a.id = t.addressFk + WHERE v.fecha BETWEEN datSTART AND datEND + AND s.quantity > 0 -- evita abonos + AND t.companyFk = 442 -- Verdnatura + GROUP BY t.warehouseFk, v.fecha, a.provinceFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `manaCustomerUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `manaCustomerUpdate`() +BEGIN +DECLARE vToDated DATE; + DECLARE vFromDated DATE; + DECLARE vForDeleteDated DATE; + DECLARE vManaId INT DEFAULT 37; + DECLARE vManaAutoId INT DEFAULT 39; + DECLARE vManaBankId INT DEFAULT 66; + DECLARE vManaGreugeTypeId INT DEFAULT 3; + + SELECT IFNULL(max(dated), '2016-01-01') + INTO vFromDated + FROM bs.manaCustomer; + + DELETE + FROM bs.manaCustomer + WHERE dated = vFromDated; + + SELECT IFNULL(max(dated), '2016-01-01') + INTO vFromDated + FROM bs.manaCustomer; + + WHILE timestampadd(DAY,30,vFromDated) < CURDATE() DO + + SELECT + timestampadd(DAY,30,vFromDated), + timestampadd(DAY,-90,vFromDated) + INTO + vToDated, + vForDeleteDated; + + DELETE FROM bs.manaCustomer + WHERE dated <= vForDeleteDated; + + + INSERT INTO bs.manaCustomer(Id_Cliente, Mana, dated) + + SELECT + Id_Cliente, + cast(sum(mana) as decimal(10,2)) as mana, + vToDated as dated + FROM + + ( + SELECT cs.Id_Cliente, Cantidad * Valor as mana + FROM vn2008.Tickets t + JOIN vn2008.Consignatarios cs using(Id_Consigna) + JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket + JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento + WHERE Id_Componente IN (vManaAutoId, vManaId) + AND t.Fecha > vFromDated + AND date(t.Fecha) <= vToDated + + + UNION ALL + + SELECT r.Id_Cliente, - Entregado + FROM vn2008.Recibos r + WHERE Id_Banco = vManaBankId + AND Fechacobro > vFromDated + AND Fechacobro <= vToDated + + UNION ALL + + SELECT g.Id_Cliente, g.Importe + FROM vn2008.Greuges g + WHERE Greuges_type_id = vManaGreugeTypeId + AND Fecha > vFromDated + AND Fecha <= vToDated + + UNION ALL + + SELECT Id_Cliente, mana + FROM bs.manaCustomer + WHERE dated = vFromDated + ) sub + + GROUP BY Id_Cliente + HAVING Id_Cliente; + + SET vFromDated = vToDated; + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `manaSpellers_actualize` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `manaSpellers_actualize`() +BEGIN + + /* PAK 2019/08/09 updated + * + * Recalcula el valor del campo con el modificador de precio para el componente de maná automático. + * La tabla mana_spellers es una caché + * + */ + + UPDATE mana_spellers me + JOIN + (SELECT Id_Trabajador, FLOOR(SUM(importe)/12) as pesoCarteraMensual + FROM bs.vendedores + WHERE año * 100 + mes >= (YEAR(CURDATE()) -1) * 100 + MONTH(CURDATE()) + GROUP BY Id_Trabajador + ) lastYearSales USING(Id_Trabajador) + SET me.prices_modifier_rate = GREATEST(me.minRate,LEAST(me.maxRate,ROUND(- me.used/lastYearSales.pesoCarteraMensual,3))) ; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `mermasCacheUpdate` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `mermasCacheUpdate`() +BEGIN + + DECLARE vTimeRange INT DEFAULT 30; + DECLARE vCurYearStarted DATE DEFAULT TIMESTAMPADD(DAY, - vTimeRange, CURDATE()); + DECLARE vCurYearFinished DATE DEFAULT CURDATE(); + DECLARE vLastYearStarted DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearStarted); + DECLARE vLastYearFinished DATE DEFAULT TIMESTAMPADD(YEAR, -1 , vCurYearFinished); + + REPLACE bs.mermasCache + SELECT Comprador, + IF(Fecha < vCurYearStarted, year(CURDATE()) - 1,year(CURDATE())) año, + CAST(sum(Importe) as DECIMAL(10,0)) as Valor_Compra, + CAST(sum(IF(Cliente LIKE 'FALTAS',Importe,0)) as DECIMAL(10,0)) as Faltas, + CAST(sum(IF(Cliente LIKE 'BASURA',Importe,0)) as DECIMAL(10,0)) as Basura + FROM bs.mermas + WHERE Fecha BETWEEN vCurYearStarted AND vCurYearFinished + OR Fecha BETWEEN vLastYearStarted AND vLastYearFinished + GROUP BY año, Comprador; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchAll` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchAll`() +BEGIN +/** + * Runs all nightly tasks. + */ + DECLARE vDone BOOL; + DECLARE vError VARCHAR(255); + DECLARE vErrorCode VARCHAR(255); + DECLARE vNErrors INT DEFAULT 0; + DECLARE vSchema VARCHAR(255); + DECLARE vProcedure VARCHAR(255); + DECLARE vLogMail VARCHAR(255); + DECLARE vId INT; + + DECLARE rs CURSOR FOR + SELECT id, `schema`, `procedure` + FROM nightTask + WHERE finished <= CURDATE() + OR finished IS NULL + ORDER BY `order`; + + DECLARE CONTINUE HANDLER FOR NOT FOUND + SET vDone = TRUE; + + SET max_sp_recursion_depth = 3; + OPEN rs; + + myLoop: LOOP + SET vDone = FALSE; + FETCH rs INTO vId, vSchema, vProcedure; + + IF vDone THEN + LEAVE myLoop; + END IF; + + UPDATE nightTask + SET `started` = NOW(), + `finished` = NULL, + `error` = NULL, + `errorCode` = NULL + WHERE id = vId; + + SET vError = NULL; + CALL nightTask_launchTask( + vSchema, + vProcedure, + vError, + vErrorCode + ); + + IF vError IS NOT NULL THEN + SET vNErrors = vNErrors + 1; + + UPDATE nightTask + SET `error` = vError, + `errorCode` = vErrorCode + WHERE id = vId; + ELSE + UPDATE nightTask + SET finished = NOW(), + lastFinished = NOW() + WHERE id = vId; + END IF; + END LOOP; + + CLOSE rs; + + SELECT logMail INTO vLogMail + FROM nightTaskConfig LIMIT 1; + + IF vNErrors > 0 AND vLogMail IS NOT NULL THEN + INSERT INTO vn.mail SET + `sender` = vLogMail, + `subject` = 'Nightly task failed', + `body` = CONCAT( + vNErrors, ' procedures of nightly tasks have failed. ', + 'Please, see `', SCHEMA() ,'`.`nightTask` table for more info.' + ); + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `nightTask_launchTask` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `nightTask_launchTask`( + vSchema VARCHAR(255), + vProcedure VARCHAR(255), + OUT vError VARCHAR(255), + OUT vErrorCode VARCHAR(255) +) +BEGIN +/** + * Runs an specific procedure from nightly tasks, if an error + * occurs, instead of throw it, #vError and #vErrorCode variables + * are setted. + * + * @param vSchema The procedure schema + * @param vProcedure The procedure name + * @param vError The error message, if any + * @param vErrorCode The error code, if any + */ + DECLARE EXIT HANDLER FOR SQLEXCEPTION + GET DIAGNOSTICS CONDITION 1 + vError = MESSAGE_TEXT, + vErrorCode = RETURNED_SQLSTATE; + + CALL util.exec(CONCAT('CALL `', vSchema ,'`.`', vProcedure ,'`')); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `payMethodClientAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `payMethodClientAdd`() +BEGIN + INSERT IGNORE INTO `bs`.`payMethodClient` (dated, payMethodFk, clientFk) + SELECT CURDATE(), c.payMethodFk, c.id + FROM vn.client c + JOIN vn.payMethod p ON c.payMethodFk = p.id; + + TRUNCATE `bs`.`payMethodClientEvolution` ; + + INSERT INTO `bs`.`payMethodClientEvolution` (dated, payMethodName, amountClient, amount, equalizationTax) + SELECT p.dated, pm.name, COUNT(p.clientFk), SUM(sub.importe) , SUM(sub.recargo) + FROM bs.payMethodClient p + JOIN (SELECT SUM(v.importe) AS importe, SUM(v.recargo) as recargo, v.fecha, v.Id_cliente + FROM bs.ventas v + WHERE v.fecha>= (SELECT MIN(dated) FROM bs. payMethodClient) + GROUP BY v.Id_cliente, v.fecha) sub ON sub.fecha = p.dated AND sub.Id_cliente = p.ClientFk + JOIN vn.payMethod pm ON p.payMethodFk = pm.id + GROUP BY dated,payMethodFk; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityAdd`(vDate DATE) +BEGIN + + DECLARE vDateStart DATETIME DEFAULT vDate; + DECLARE vDateEnd DATETIME DEFAULT util.dayEnd(vDate); + DECLARE myDepLft INT; + DECLARE myDepRgt INT; + + DROP TEMPORARY TABLE IF EXISTS tmp.productivity; + + CREATE TEMPORARY TABLE tmp.productivity + ENGINE = MEMORY + SELECT hh, + mm, + 000.00 as m3, + 000.00 as m3FV, + 000.00 as m3PCA, + 000.00 as m3Artificial, + 0 as workers, + 000.00 as wCost, + 0 as numCoordinadores, + 000.00 as costCoordinacion, + 0 as numSacadores, + 000.00 as costSacado, + 0 as numEncajadores, + 000.00 as costEncajado, + 0 as numPaletizadores, + 000.00 as costPaletizado, + 0 as numCamareros, + 000.00 as costCamara, + 0 as numComplementos, + 000.00 as costComplementos, + 0 as numArtificial, + 000.00 as costArtificial + FROM vn.dayMinute; + +-- Trabajadores + CALL vn.dayMinuteWorker(vDateStart,vDateEnd); -- Genera la tabla tmp.dayMinuteWorker + CALL vn.workerDepartmentByDate(vDate); + + -- General + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + WHERE Almacen IN (1,44) + AND wdd.production + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.workers = sub.workers, p.wCost = sub.Bruto; + + -- Coordinadores + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'COORDINACION'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numCoordinadores = sub.workers, p.costCoordinacion = sub.Bruto; + + -- Sacado + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'SACADO'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numSacadores = sub.workers, p.costSacado = sub.Bruto; + + -- Encajado + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'ENCAJADO'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numEncajadores = sub.workers, p.costEncajado = sub.Bruto; + + -- Paletizado + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'PALETIZADO'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numPaletizadores = sub.workers, p.costPaletizado = sub.Bruto; + + -- Cámara + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'CAMARA'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numCamareros = sub.workers, p.costCamara = sub.Bruto; + + -- Complementos + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'COMPLEMENTOS'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numComplementos = sub.workers, p.costComplementos = sub.Bruto; + + -- Artificial + SELECT lft, rgt INTO myDepLft, myDepRgt + FROM vn.department + WHERE name = 'ARTIFICIAL'; + + UPDATE tmp.productivity p + JOIN + (SELECT Hora, Minuto, count(*) as workers, sum(wdd.costeHora) / 60 as Bruto + FROM tmp.dayMinuteWorker dmw + JOIN tmp.workerDepartmentByDate wdd ON wdd.userFk = dmw.userFk + JOIN vn.department d ON d.id = wdd.departmentFk + WHERE Almacen IN (1,44) + AND d.lft BETWEEN myDepLft AND myDepRgt + GROUP BY Hora, Minuto + ) sub ON p.hh = sub.Hora AND p.mm = sub.Minuto + SET p.numArtificial = sub.workers, p.costArtificial = sub.Bruto; + + -- m3 + CALL vn.ticketBuiltTime(vDate); -- Genera la tabla tmp.ticketBuiltTime(ticketFk,builtTime) + CALL vn.ticketVolumeByDate_ventas(vDate); -- Genera la tabla tmp.ticketVolumeByDate(ticketFk,m3), filtrado por las ventas validas + CALL vn.ticketVolumeByDate_ventas_Artificial(vDate); -- Genera la tabla tmp.ticketVolumeByDate_ventas_Artificial + + UPDATE tmp.productivity p + JOIN + (SELECT HOUR(builtTime) hh, + MINUTE(builtTime) mm, + sum(tvd.m3) as m3, + sum(IF(t.warehouseFk = 1,tvd.m3,0)) as m3FV, + sum(IF(t.warehouseFk = 44,tvd.m3 - IFNULL(tvda.m3,0),0)) as m3PCA, + sum(IFNULL(tvda.m3,0)) as m3Artificial + FROM tmp.ticketBuiltTime tbt + JOIN tmp.ticketVolumeByDate tvd ON tvd.ticketFk = tbt.ticketFk + LEFT JOIN tmp.ticketVolumeByDate_Artificial tvda ON tvda.ticketFk = tbt.ticketFk + JOIN vn.ticket t ON t.id = tbt.ticketFk + WHERE t.warehouseFk IN (1,44) + GROUP BY hh,mm + ) v ON v.hh = p.hh AND v.mm = p.mm + SET p.m3 = v.m3, p.m3FV = v.m3FV, p.m3PCA = v.m3PCA, p.m3Artificial = v.m3Artificial; + + + + DELETE FROM bs.productivity + WHERE dated = vDate; + + INSERT INTO bs.productivity(dated, + hh, + mm, + m3, + m3FV, + m3PCA, + m3Artificial, + workers, + wCost, + numCoordinadores, + costCoordinacion, + numSacadores, + costSacado, + numEncajadores, + costEncajado, + numPaletizadores, + costPaletizado, + numCamareros, + costCamara, + numComplementos, + costComplementos, + numArtificial, + costArtificial) + SELECT vDate, + hh, + mm, + m3, + m3FV, + m3PCA, + m3Artificial, + workers, + wCost, + numCoordinadores, + costCoordinacion, + numSacadores, + costSacado, + numEncajadores, + costEncajado, + numPaletizadores, + costPaletizado, + numCamareros, + costCamara, + numComplementos, + costComplementos, + numArtificial, + costArtificial + FROM tmp.productivity p; + + -- Productivity Evolution + REPLACE bs.productivity_evolution(dated, m3productionCost) + SELECT CURDATE(), sum(wCost) / sum(m3) + FROM bs.productivity + WHERE dated BETWEEN TIMESTAMPADD(YEAR,-1,CURDATE()) AND CURDATE(); + + DROP TEMPORARY TABLE tmp.dayMinuteWorker; + DROP TEMPORARY TABLE tmp.productivity; + DROP TEMPORARY TABLE tmp.ticketBuiltTime; + DROP TEMPORARY TABLE tmp.ticketVolumeByDate; + DROP TEMPORARY TABLE tmp.workerDepartmentByDate; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentAdd`(IN vDateStartPeriod DATETIME, IN vDateEndPeriod DATETIME, IN vDateStart DATETIME) +BEGIN + + DECLARE vEndingDate DATETIME; + + SET vEndingDate = vDateStart; + + WHILE vEndingDate <= vDateEndPeriod DO + REPLACE INTO bs.productivityDepartment + SELECT vEndingDate, + CAST(((productivityCoordinacionLastYear - productivityCoordinacion) / 2) * m3 AS DECIMAL (10,2)) AS amountCoordinacion, + CAST(((productivitySacadoLastYear - productivitySacado) / 2) * m3 AS DECIMAL (10,2)) AS amountSacado, + CAST(((productivityEncajadoLastYear - productivityEncajado) / 2) * m3 AS DECIMAL (10,2)) AS amountEncajado, + CAST(((productivityPaletizadoLastYear - productivityPaletizado) / 2) * m3 AS DECIMAL (10,2)) AS amountPaletizado, + CAST(((productivityCamaraLastYear - productivityCamara) / 2) * m3FV AS DECIMAL (10,2)) AS amountCamara, + CAST(((productivityComplementosLastYear - productivityComplementos) / 2) * m3PCA AS DECIMAL (10,2)) AS amountComplementos, + CAST(((productivityArtificialLastYear - productivityArtificial) / 2) * m3Artificial AS DECIMAL (10,2)) AS amountArtificia + FROM + (SELECT + SUM(p.m3) AS m3, SUM(p.m3FV) as m3FV, SUM(p.m3PCA) as m3PCA, SUM(p.m3Artificial) as m3Artificial, + SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacion, + SUM(p.costSacado) / SUM(p.m3) AS productivitySacado, + SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajado, + SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizado, + SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamara, + SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementos, + SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificial + FROM + bs.productivity p + WHERE + p.dated BETWEEN vDateStartPeriod AND vEndingDate) sub + JOIN + (SELECT + SUM(p.costCoordinacion) / SUM(p.m3) AS productivityCoordinacionLastYear, + SUM(p.costSacado) / SUM(p.m3) AS productivitySacadoLastYear, + SUM(p.costEncajado) / SUM(p.m3) AS productivityEncajadoLastYear, + SUM(p.costPaletizado) / SUM(p.m3) AS productivityPaletizadoLastYear, + SUM(p.costCamara) / SUM(p.m3FV) AS productivityCamaraLastYear, + SUM(p.costComplementos) / SUM(p.m3PCA) AS productivityComplementosLastYear, + SUM(p.costArtificial) / SUM(p.m3Artificial) AS productivityArtificialLastYear + FROM + bs.productivity p + WHERE + p.dated BETWEEN DATE_ADD(vDateStartPeriod, INTERVAL - 1 YEAR) AND DATE_ADD(vEndingDate, INTERVAL - 1 YEAR)) sub1; + + SET vEndingDate = TIMESTAMPADD(DAY,1, vEndingDate); + END WHILE; + END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityDepartmentLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityDepartmentLauncher`() +BEGIN + CALL bs.productivityDepartmentAdd('2019-05-06', CURDATE(),DATE_SUB(CURDATE(), INTERVAL 2 WEEK)); +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher`() +BEGIN + + DECLARE vDateFrom DATE; + + SELECT LEAST(TIMESTAMPADD(MONTH, -1, CURDATE()),MAX(dated)) + INTO vDateFrom + FROM bs.productivity; + + WHILE CURDATE() > vDateFrom DO + CALL bs.productivityAdd(vDateFrom); + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + END WHILE; + + SET vDateFrom = TIMESTAMPADD(MONTH, -13, CURDATE()); + + WHILE TIMESTAMPADD(MONTH, -12, CURDATE()) > vDateFrom DO + CALL bs.productivityAdd(vDateFrom); + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `productivityLauncher_manual` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `productivityLauncher_manual`(vDateFrom DATE, vToDate DATE) +BEGIN + + TRUNCATE tmp.log; + + WHILE vToDate >= vDateFrom DO + + INSERT INTO tmp.log(text) VALUES (vDateFrom); + CALL bs.productivityAdd(vDateFrom); + + CALL bs.productivityAdd(TIMESTAMPADD(YEAR, -1,vDateFrom)); + INSERT INTO tmp.log(text) VALUES (TIMESTAMPADD(YEAR, -1,vDateFrom)); + + SET vDateFrom = TIMESTAMPADD(DAY,1,vDateFrom); + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `pruebas` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `pruebas`(IN vDateStart DATE, IN vDateEnd DATE) +BEGIN + +WHILE vDateStart <> vDateEnd +DO + UPDATE indicators + SET countEmployee = + ( SELECT CAST(SUM(hours_week) / 40 AS DECIMAL (10 , 2 )) + FROM + postgresql.business AS b + JOIN postgresql.profile p ON p.profile_id = b.provider_id + JOIN postgresql.person pe ON pe.person_id = p.person_id + LEFT JOIN + postgresql.business_labour AS bl ON bl.business_id = b.business_id + LEFT JOIN + postgresql.calendar_labour_type AS cl ON cl.calendar_labour_type_id = bl.calendar_labour_type_id + WHERE + (vDateStart BETWEEN b.date_start AND b.date_end OR (b.date_end IS NULL AND b.date_start <= vDateStart)) + AND pe.name = 'VERDNATURA LEVANTE SL' + ) + WHERE updated = vDateStart; + SET vDateStart = DATE_ADD(vDateStart, INTERVAL 1 DAY); + +END WHILE; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `salePersonEvolutionAdd` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `salePersonEvolutionAdd`(IN vDateStart DATETIME) +BEGIN + DELETE FROM bs.salePersonEvolution + WHERE dated <= DATE_SUB(CURDATE(), INTERVAL 1 YEAR); + + + INSERT INTO bs.salePersonEvolution (dated, amount, equalizationTax, salesPersonFk) + SELECT fecha dated, + CAST(SUM(importe) AS DECIMAL(10,2) ) amount, + CAST(SUM(recargo) AS DECIMAL(10,2) ) equalizationTax , + IFNULL(salesPersonFk,0) salesPersonFk + FROM bs.ventas v + JOIN vn.client c ON v.Id_Cliente = c.id + JOIN vn.company co ON co.id = v.empresa_id + WHERE co.code = "VNL" AND fecha >= vDateStart + GROUP BY v.fecha,c.salesPersonFk + ORDER BY salesPersonFk,dated ASC; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `userSundayRole` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `userSundayRole`() +BEGIN + -- 4996 Fran Natek Echevarria + DECLARE vDay INT; + SET vDay := (SELECT DAYOFWEEK(CURDATE())); + IF vDay = 1 THEN + UPDATE account.user u + JOIN account.role r + SET u.role = r.id + WHERE u.id = 4996 AND r.name = "salesAssistant"; + ELSE + UPDATE account.user u + JOIN account.role r + SET u.role = r.id + WHERE u.id = 4996 AND r.name = "salesPerson"; + END IF; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add`(intYEAR INT, vQuarter INT) +BEGIN + + DECLARE comisionRate DOUBLE DEFAULT 0.029; + + REPLACE vendedores + SELECT c.Id_Trabajador + , intYEAR + , MONTH(v.fecha) intMONTH + , sum(importe) as importe + , sum(importe) * 0.029 as comision + , 0 as comisionCedida + , 0 as comisionArrendada + , 0 as comisionNuevos + + FROM ventas v + JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY c.Id_Trabajador, t.`month`; + + -- Ventas nuevas + UPDATE vendedores v + JOIN + ( + SELECT c.Id_Trabajador + , sum(importe) * 0.029 as comisionNueva + , t.`month` + , t.`year` + FROM ventas v + JOIN bs.clientNewBorn cnb on v.Id_Cliente = cnb.clientFk + JOIN vn2008.Clientes c ON c.Id_Cliente = v.Id_Cliente + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY c.Id_Trabajador, t.`month` + ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año + SET v.comisionNuevos = sub.comisionNueva, v.comision = v.comision - sub.comisionNueva; + + -- Ventas cedidas + UPDATE vendedores v + JOIN ( + SELECT cc.Id_Trabajador_old as Id_Trabajador + , sum(importe) * 0.029 * comision_old as cedido + , sum(importe) * 0.029 * comision_new as arrendada + , t.`month` + , t.`year` + FROM ventas v + JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente + JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY cc.Id_Trabajador_old, t.`month` + ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año + SET v.comisionCedida = sub.cedido, v.comision = v.comision - sub.cedido - sub.arrendada; + + -- Ventas arrendadas + UPDATE vendedores v + JOIN ( + SELECT cc.Id_Trabajador_new as Id_Trabajador + , sum(importe) * 0.029 * comision_new as arrendada + , t.`month` + , t.`year` + FROM ventas v + JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente + JOIN vn2008.Clientes_cedidos cc on cc.Id_Cliente = c.Id_Cliente AND v.fecha between datSTART and datEND + JOIN vn2008.`time` t on t.`date` = v.fecha + WHERE c.Id_Trabajador is not null + AND t.`year` = intYEAR AND QUARTER(v.fecha) = vQuarter + GROUP BY cc.Id_Trabajador_new, t.`month` + ) sub ON sub.Id_Trabajador = v.Id_Trabajador AND sub.`month` = v.mes AND sub.`year` = v.año + SET v.comisionArrendada = sub.arrendada; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_add_launcher`() +BEGIN + + call bs.vendedores_add(YEAR(CURDATE()),QUARTER(CURDATE())); + + call bs.vendedores_evolution_add; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vendedores_evolution_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vendedores_evolution_add`() +BEGIN +/* + +Inserta en la tabla compradores_evolution las ventas acumuladas en el ultimo mes + +*/ + +DECLARE vYear, vMonth INTEGER; +DECLARE vCurYear, vCurMonth INTEGER; +DECLARE vFirstYear INTEGER DEFAULT 2017; +DECLARE vFirstMonth INTEGER DEFAULT 1; + +DECLARE vDateFrom DATE; +DECLARE vDateTo DATE; + +SET vCurYear = year(CURDATE()); +SET vCurMonth = month(CURDATE()); + +SELECT IFNULL(max(year),vFirstYear), IFNULL(max(month),vFirstMonth) + INTO vYear, vMonth + FROM bs.vendedores_evolution; + + WHILE (vYear < vCurYear) OR (vYear = vCurYear AND vMonth < vCurMonth) DO + + SELECT max(dated), TIMESTAMPADD(DAY,-364,max(dated)) INTO vDateTo, vDateFrom + FROM vn.time + WHERE year = vYear + AND month = vMonth; + + SELECT vDateTo, vDateFrom, vYear, vMonth; + + REPLACE bs.vendedores_evolution( workerFk + , year + , month + , sales) + SELECT c.salesPersonFk + , vYear as year + , vMonth as month + , sum(v.importe) as sales + FROM bs.ventas v + JOIN vn.client c on c.id = v.Id_Cliente + WHERE v.fecha BETWEEN vDateFrom AND vDateTo + AND c.salesPersonFk is not null + GROUP BY c.salesPersonFk; + + SET vMonth = vMonth + 1; + + IF vMonth = 13 THEN + + SET vMonth = 1; + SET vYear = vYear + 1; + + END IF; + + END WHILE; + + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add`(IN datSTART DATETIME, IN datEND DATETIME) +BEGIN + + DECLARE vStartingDate DATETIME; + DECLARE vEndingDate DATETIME; + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + IF datSTART < '2015-10-01' OR datEND < '2015-10-01' THEN + CALL util.throw('fechaDemasiadoAntigua'); + END IF; + + SET datEND = util.dayEnd(datEND); + SET vStartingDate = datSTART; + SET vEndingDate = vn2008.dayend(vStartingDate); + + DELETE + FROM ventas + WHERE fecha between vStartingDate and datEND; + + WHILE vEndingDate <= datEND DO + + REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) + SELECT Id_Movimiento, + SUM(IF(base, Cantidad * Valor, 0)) as importe, + SUM(IF(base, 0, Cantidad * Valor)) as recargo, + vStartingDate, + a.tipo_id, + cs.Id_Cliente, + t.empresa_id + FROM vn2008.Movimientos_componentes mc + JOIN bi.tarifa_componentes tc using(Id_Componente) + JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) + JOIN vn2008.Movimientos m using(Id_Movimiento) + JOIN vn2008.Articles a using(Id_Article) + JOIN vn2008.Tipos tp using(tipo_id) + JOIN vn2008.reinos r on r.id = tp.reino_id + JOIN vn2008.Tickets t using(Id_Ticket) + JOIN vn2008.Consignatarios cs using(Id_Consigna) + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + WHERE t.Fecha between vStartingDate and vEndingDate + AND c.typeFk IN ('Normal','handMaking','internalUse') + AND m.Cantidad <> 0 + AND a.tipo_id != TIPO_PATRIMONIAL + AND m.Descuento <> 100 + AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) + GROUP BY mc.Id_Movimiento + HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; + + SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); + SET vEndingDate = util.dayEnd(vStartingDate); + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add_launcher`() +BEGIN + + call bs.ventas_add(timestampadd(week,-1,curdate()),curdate()); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_add__` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_add__`(IN datSTART DATETIME, IN datEND DATETIME) +BEGIN + + DECLARE vStartingDate DATETIME; + DECLARE vEndingDate DATETIME; + DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + + SET datEND = util.dayEnd(datEND); + SET vStartingDate = GREATEST('2015-10-01',datSTART); + SET vEndingDate = vn2008.dayend(vStartingDate); + + DELETE + FROM ventas + WHERE fecha between vStartingDate and datEND; + + WHILE vEndingDate <= datEND DO + + REPLACE ventas(Id_Movimiento, importe, recargo, fecha, tipo_id, Id_Cliente, empresa_id) + SELECT Id_Movimiento, + SUM(IF(base, Cantidad * Valor, 0)) as importe, + SUM(IF(base, 0, Cantidad * Valor)) as recargo, + vStartingDate, + a.tipo_id, + cs.Id_Cliente, + t.empresa_id + FROM vn2008.Movimientos_componentes mc + JOIN bi.tarifa_componentes tc using(Id_Componente) + JOIN bi.tarifa_componentes_series tcs using(tarifa_componentes_series_id) + JOIN vn2008.Movimientos m using(Id_Movimiento) + JOIN vn2008.Articles a using(Id_Article) + JOIN vn2008.Tipos tp using(tipo_id) + JOIN vn2008.reinos r on r.id = tp.reino_id + JOIN vn2008.Tickets t using(Id_Ticket) + JOIN vn2008.Consignatarios cs using(Id_Consigna) + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + WHERE t.Fecha between vStartingDate and vEndingDate + AND datEND >= '2015-10-01' + AND c.typeFk IN ('Normal','handMaking','internalUse') + AND m.Cantidad <> 0 + AND a.tipo_id != TIPO_PATRIMONIAL + AND c.Id_Trabajador IS NOT NULL + AND m.Descuento <> 100 + AND (m.Id_Article = 98 or m.Id_Article = 95 or r.mercancia != 0) + GROUP BY mc.Id_Movimiento + HAVING IFNULL(importe,0) <> 0 OR IFNULL(recargo,0) <> 0; + + SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate); + SET vEndingDate = util.dayEnd(vStartingDate); + + END WHILE; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add`(IN vYear INT, IN vMonth INT) +BEGIN +/** + * Reemplaza las ventas contables. Es el origen de datos para el balance de Entradas + * + * @param vYear Año a reemplazar + * @param vMonth Mes a reemplazar + * + * + **/ +DECLARE TIPO_PATRIMONIAL INT DEFAULT 188; + +DELETE FROM bs.ventas_contables + WHERE year = vYear + AND month = vMonth; + +DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + +CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + +INSERT INTO bs.ventas_contables(year + , month + , venta + , grupo + , reino_id + , tipo_id + , empresa_id + , gasto) + + SELECT vYear + , vMonth + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) + , if( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,if(e2.empresa_grupo,2,0) + ) as grupo + , tp.reino_id + , a.tipo_id + , t.empresa_id + , 7000000000 + + if(e.empresa_grupo = e2.empresa_grupo + ,1 + ,if(e2.empresa_grupo,2,0) + ) * 1000000 + + tp.reino_id * 10000 as Gasto + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != TIPO_PATRIMONIAL + GROUP BY grupo, reino_id, tipo_id, empresa_id, Gasto; + + +DROP TEMPORARY TABLE tmp.ticket_list; +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_add_launcher` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_add_launcher`() +BEGIN + + call bs.ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE()))); + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `ventas_contables_por_cliente` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `ventas_contables_por_cliente`(IN vYear INT, IN vMonth INT) +BEGIN + + +DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list; + +CREATE TEMPORARY TABLE tmp.ticket_list + (PRIMARY KEY (Id_Ticket)) + SELECT Id_Ticket + FROM vn2008.Tickets t + JOIN vn2008.Facturas f ON f.Id_Factura = t.Factura + WHERE year(f.Fecha) = vYear + AND month(f.Fecha) = vMonth; + + + + SELECT vYear Año + , vMonth Mes + , t.Id_Cliente + , round(sum(Cantidad * Preu * (100 - m.Descuento)/100)) Venta + , if( + e.empresa_grupo = e2.empresa_grupo + ,1 + ,if(e2.empresa_grupo,2,0) + ) as grupo + , t.empresa_id empresa + FROM vn2008.Movimientos m + JOIN vn2008.Tickets t on t.Id_Ticket = m.Id_Ticket + JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna + JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente + JOIN tmp.ticket_list tt on tt.Id_Ticket = t.Id_Ticket + JOIN vn2008.Articles a on m.Id_Article = a.Id_Article + JOIN vn2008.empresa e on e.id = t.empresa_id + LEFT JOIN vn2008.empresa e2 on e2.Id_Cliente = c.Id_Cliente + JOIN vn2008.Tipos tp on tp.tipo_id = a.tipo_id + WHERE Cantidad <> 0 + AND Preu <> 0 + AND m.Descuento <> 100 + AND a.tipo_id != 188 + GROUP BY t.Id_Cliente, grupo,t.empresa_id; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `vivosMuertos` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `vivosMuertos`() +BEGIN + +SET @datSTART = TIMESTAMPADD(YEAR,-2,CURDATE()); +SET @datEND = TIMESTAMPADD(DAY,-DAY(CURDATE()),CURDATE()); + +DROP TEMPORARY TABLE IF EXISTS tmp.VivosMuertos; + +CREATE TEMPORARY TABLE tmp.VivosMuertos +SELECT c.Id_Cliente, tm.yearMonth, f.Compra, 0 as Nuevo, 0 as Muerto +FROM vn2008.Clientes c +JOIN (SELECT DISTINCT yearMonth FROM vn2008.time WHERE date BETWEEN @datSTART AND @datEND ) tm +LEFT JOIN + (SELECT DISTINCT tm.yearMonth, f.Id_Cliente , 1 as Compra + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND) f ON f.yearMonth = tm.yearMonth AND f.Id_Cliente = c.Id_Cliente; + +UPDATE tmp.VivosMuertos vm +JOIN ( + SELECT MIN(tm.yearMonth) firstMonth, f.Id_Cliente + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND + GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente +SET Nuevo = 1; + +SELECT max(yearMonth) INTO @lastYearMonth FROM tmp.VivosMuertos; + +UPDATE tmp.VivosMuertos vm +JOIN ( + SELECT MAX(tm.yearMonth) firstMonth, f.Id_Cliente + FROM vn2008.Facturas f + JOIN vn2008.time tm ON tm.date = f.Fecha + WHERE Fecha BETWEEN @datSTART AND @datEND + GROUP BY f.Id_Cliente ) fm ON fm.firstMonth = vm.yearMonth AND fm.Id_Cliente = vm.Id_Cliente +SET Muerto = 1 +WHERE yearMonth < @lastYearMonth; + + SELECT * FROM tmp.VivosMuertos; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8 */ ; +/*!50003 SET character_set_results = utf8 */ ; +/*!50003 SET collation_connection = utf8_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed`() +BEGIN + + /* #UPDATED PAK 2019/09/02 + * #PENDING REVIEW + * + * + * + * + */ + + DECLARE vLastUpdated DATETIME; + DECLARE vSecondsDelay INT DEFAULT 300; + + SELECT IFNULL(MAX(lastUpdated),CURDATE()) INTO vLastUpdated + FROM bs.workerSpeed; + + IF TIMESTAMPDIFF(SECOND, vLastUpdated, NOW()) > vSecondsDelay THEN + + DELETE FROM bs.workerSpeed ; + -- WHERE lastUpdated < CURDATE(); + + -- Sacadores + REPLACE bs.workerSpeed + SELECT workerCode, + accion, + warehouseFk, + CAST(60 * sumaLitros / time_to_sec(timediff(finished, started)) AS DECIMAL(10,1)) as LitrosMinuto, + CAST(sumaLitrosLastHour / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, + now() as lastUpdated + FROM + ( + SELECT warehouseFk, + accion, + workerCode, + sum(litros) as sumaLitros, + min(created) as started, + max(created) as finished, + sum(IF(created >= TIMESTAMPADD(HOUR, -1, NOW()),litros, 0)) as sumaLitrosLastHour + FROM + ( + SELECT t.warehouseFk, + st.saleFk, + st.isChecked, + st.originalQuantity, + a.accion, + st.created, + e.code, + w.firstname, + w.lastName, + w.code as workerCode, + r.cm3 * s.quantity / 1000 as litros, + s.concept + FROM vn.saleTracking st + LEFT JOIN + (SELECT saleFk + FROM vn.saleTracking st + JOIN vn.state e ON e.id = st.stateFk + WHERE st.created > CURDATE() + AND e.code LIKE 'PREVIOUS_PREPARATION') prevPrepSales ON prevPrepSales.saleFk = st.saleFk + JOIN vn.sale s ON s.id = st.saleFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk + JOIN vn.worker w ON w.id = st.workerFk + JOIN vn.state e ON e.id = st.stateFk + JOIN vncontrol.accion a ON a.accion_id = st.actionFk + WHERE st.created > TIMESTAMPADD(HOUR,-1,NOW()) + AND prevPrepSales.saleFk IS NULL + ) sub + GROUP BY warehouseFk, accion, workerCode + ) sub2; + + -- Encajadores + REPLACE bs.workerSpeed + SELECT code as workerCode, + 'ENCAJAR' as accion, + warehouseFk, + CAST(60 * sum(Litros) / time_to_sec(timediff(MAX(finished), MIN(started))) AS DECIMAL(10,1)) as LitrosMinuto, + CAST(sum(litrosUltimaHora) / 60 AS DECIMAL(10,1)) as LitrosMinutoLastHour, + now() as lastUpdated + FROM ( + SELECT sv.ticketFk, + sum(sv.litros) as litros, + sum(IF(started > TIMESTAMPADD(HOUR,-1,NOW()),sv.litros,0)) as litrosUltimaHora, + code, + started, + finished, + cajas, + warehouseFk + FROM vn.saleVolume sv + JOIN + ( + SELECT ticketFk, + min(e.created) as started, + max(e.created) as finished, + max(counter) as cajas, + w.code, + t.warehouseFk + FROM vn.expedition e + JOIN vn.worker w ON w.id = e.workerFk + JOIN vn.ticket t ON t.id = e.ticketFk + WHERE e.created > CURDATE() + GROUP BY ticketFk + ) sub ON sub.ticketFk = sv.ticketFk + GROUP BY sv.ticketFk) sub2 + GROUP BY code; + + END IF; + + SELECT * FROM bs.workerSpeed; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; +/*!50003 DROP PROCEDURE IF EXISTS `workerSpeed_detail` */; +/*!50003 SET @saved_cs_client = @@character_set_client */ ; +/*!50003 SET @saved_cs_results = @@character_set_results */ ; +/*!50003 SET @saved_col_connection = @@collation_connection */ ; +/*!50003 SET character_set_client = utf8mb4 */ ; +/*!50003 SET character_set_results = utf8mb4 */ ; +/*!50003 SET collation_connection = utf8mb4_general_ci */ ; +/*!50003 SET @saved_sql_mode = @@sql_mode */ ; +/*!50003 SET sql_mode = 'NO_ENGINE_SUBSTITUTION' */ ; +DELIMITER ;; +CREATE DEFINER=`root`@`%` PROCEDURE `workerSpeed_detail`(vWorkerCode VARCHAR(3), vAction VARCHAR(25)) +BEGIN + + SELECT * FROM + ( + SELECT time_format(st.created,'%H:%i') as hora, + t.warehouseFk as Almacen, + t.id as ticketFk, + floor(sum(s.quantity * r.cm3) / 1000) as Litros + + FROM vn.saleTracking st + JOIN vn.sale s ON s.id = st.saleFk + JOIN vn.ticket t ON t.id = s.ticketFk + JOIN bi.rotacion r ON r.warehouse_id = t.warehouseFk AND r.Id_Article = s.itemFk + JOIN vn.worker w ON w.id = st.workerFk + JOIN vn.state e ON e.id = st.stateFk + JOIN vncontrol.accion a ON a.accion_id = st.actionFk + WHERE st.created > CURDATE() + AND a.accion LIKE vAction + AND w.code LIKE vWorkerCode + GROUP BY t.id) sub + ORDER BY hora; + +END ;; +DELIMITER ; +/*!50003 SET sql_mode = @saved_sql_mode */ ; +/*!50003 SET character_set_client = @saved_cs_client */ ; +/*!50003 SET character_set_results = @saved_cs_results */ ; +/*!50003 SET collation_connection = @saved_col_connection */ ; + -- -- Current Database: `cache` -- @@ -17133,6 +20583,10 @@ CREATE TABLE `botanicExport` ( `isProtectedZone` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`), KEY `Id_Paises` (`countryFk`), + KEY `botanicExport_ibfk_2_idx` (`ediGenusFk`), + KEY `botanicExport_ibfk_3_idx` (`ediSpecieFk`), + CONSTRAINT `botanicExport_ediGenusFk` FOREIGN KEY (`ediGenusFk`) REFERENCES `edi`.`genus` (`genus_id`) ON UPDATE CASCADE, + CONSTRAINT `botanicExport_ediSpecieFk` FOREIGN KEY (`ediSpecieFk`) REFERENCES `edi`.`specie` (`specie_id`) ON UPDATE CASCADE, CONSTRAINT `botanicExport_ibfk_1` FOREIGN KEY (`countryFk`) REFERENCES `country` (`id`) ) ENGINE=InnoDBDEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Especifica los generos y especies prohibidos en paises'; /*!40101 SET character_set_client = @saved_cs_client */; @@ -50911,6 +54365,156 @@ USE `bi`; /*!50001 SET character_set_results = @saved_cs_results */; /*!50001 SET collation_connection = @saved_col_connection */; +-- +-- Current Database: `bs` +-- + +USE `bs`; + +-- +-- Final view structure for view `bajasLaborales` +-- + +/*!50001 DROP VIEW IF EXISTS `bajasLaborales`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `bajasLaborales` AS select `p`.`firstname` AS `firstname`,`p`.`name` AS `name`,`b`.`business_id` AS `business_id`,max(`ce`.`date`) AS `lastDate`,max(ifnull(`b`.`date_end`,curdate())) AS `endContract`,`cs`.`type` AS `type`,cast(count(0) as decimal(10,0)) AS `dias`,`w`.`userFk` AS `userFk` from (((((`postgresql`.`calendar_employee` `ce` join `postgresql`.`business` `b` on((`b`.`business_id` = `ce`.`business_id`))) join `postgresql`.`profile` `pr` on((`pr`.`profile_id` = `b`.`client_id`))) join `postgresql`.`person` `p` on((`p`.`person_id` = `pr`.`person_id`))) join `postgresql`.`calendar_state` `cs` on((`cs`.`calendar_state_id` = `ce`.`calendar_state_id`))) join `vn`.`worker` `w` on((`w`.`id` = `p`.`id_trabajador`))) where ((`ce`.`date` >= (curdate() + interval -(1) year)) and (`cs`.`type` not in ('Vacaciones','Vacaciones 1/2 día','Compensar','Festivo'))) group by `p`.`firstname`,`p`.`name`,`cs`.`type` having (`endContract` >= curdate()) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `lastIndicators` +-- + +/*!50001 DROP VIEW IF EXISTS `lastIndicators`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `lastIndicators` AS select `i`.`updated` AS `updated`,`i`.`lastYearSales` AS `lastYearSales`,(`i`.`lastYearSales` - `yi`.`lastYearSales`) AS `incLastYearSales`,`i`.`totalGreuge` AS `totalGreuge`,(`i`.`totalGreuge` - `yi`.`totalGreuge`) AS `incTotalGreuge`,`i`.`latePaymentRate` AS `latePaymentRate`,(`i`.`latePaymentRate` - `yi`.`latePaymentRate`) AS `incLatePaymentRate`,`i`.`countEmployee` AS `countEmployee`,(`i`.`countEmployee` - `yi`.`countEmployee`) AS `incCountEmployee`,`i`.`averageMana` AS `averageMana`,(`i`.`averageMana` - `yi`.`averageMana`) AS `incAverageMana`,`i`.`bankingPool` AS `bankingPool`,(`i`.`bankingPool` - `yi`.`bankingPool`) AS `incbankingPool`,`i`.`lastMonthActiveClients` AS `lastMonthActiveClients`,(`i`.`lastMonthActiveClients` - `yi`.`lastMonthActiveClients`) AS `incLastMonthActiveClients`,`i`.`lastMonthLostClients` AS `lastMonthLostClients`,(`i`.`lastMonthLostClients` - `yi`.`lastMonthLostClients`) AS `incLastMonthLostClients`,`i`.`lastMonthNewClients` AS `lastMonthNewClients`,(`i`.`lastMonthNewClients` - `yi`.`lastMonthNewClients`) AS `incLastMonthNewClients`,`i`.`lastMonthWebBuyingRate` AS `lastMonthWebBuyingRate`,(`i`.`lastMonthWebBuyingRate` - `yi`.`lastMonthWebBuyingRate`) AS `incLastMonthWebBuyingRate`,`i`.`productionHours` AS `productionHours`,`i`.`dailyWorkersCost` AS `dailyWorkersCost`,`i`.`volumeM3` AS `volumeM3`,`i`.`salesValue` AS `salesValue`,`i`.`valueM3` AS `valueM3`,`i`.`hoursM3` AS `hoursM3`,`i`.`workerCostM3` AS `workerCostM3`,`i`.`salesWorkersCostRate` AS `salesWorkersCostRate`,`i`.`thisWeekSales` AS `thisWeekSales`,`i`.`lastYearWeekSales` AS `lastYearWeekSales` from (`indicators` `i` join `indicators` `yi` on((`yi`.`updated` = (select (max(`indicators`.`updated`) + interval -(1) day) from `indicators`)))) where (`i`.`updated` = (select max(`indicators`.`updated`) from `indicators`)) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `m3Silla` +-- + +/*!50001 DROP VIEW IF EXISTS `m3Silla`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `m3Silla` AS select `m3`.`fecha` AS `fecha`,`m3`.`year` AS `year`,`m3`.`month` AS `month`,`m3`.`week` AS `week`,`m3`.`day` AS `day`,`m3`.`dayName` AS `dayName`,cast(sum(`m3`.`m3`) as decimal(10,0)) AS `Volumen`,cast(sum(`m3`.`euros`) as decimal(10,0)) AS `Euros` from `m3` where (`m3`.`warehouseFk` in (1,44)) group by `m3`.`fecha` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `m3analisis` +-- + +/*!50001 DROP VIEW IF EXISTS `m3analisis`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `m3analisis` AS select `m`.`fecha` AS `fecha`,`m`.`year` AS `year`,`m`.`month` AS `month`,`m`.`week` AS `week`,`m`.`day` AS `day`,`m`.`dayName` AS `dayName`,`m`.`Volumen` AS `Volumen`,`m`.`Euros` AS `Euros`,`h`.`Departamento` AS `Departamento`,`h`.`Horas` AS `Horas`,`h`.`Salarios` AS `Salarios`,(`h`.`Horas` / `m`.`Volumen`) AS `tiempoM3`,(`m`.`Euros` / `m`.`Volumen`) AS `valorM3`,(`h`.`Salarios` / `m`.`Volumen`) AS `costeLaboralM3`,(`h`.`Salarios` / `m`.`Euros`) AS `costeEuros`,(`h`.`Salarios` / `h`.`Horas`) AS `precioHora` from (`bs`.`m3Silla` `m` join `bs`.`horasSilla` `h` on((`h`.`Fecha` = `m`.`fecha`))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `manaSpellersExcluded` +-- + +/*!50001 DROP VIEW IF EXISTS `manaSpellersExcluded`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `manaSpellersExcluded` AS select `m`.`Id_Trabajador` AS `workerFk` from `mana_spellers_excluded` `m` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `mana_spellers` +-- + +/*!50001 DROP VIEW IF EXISTS `mana_spellers`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mana_spellers` AS select `wm`.`workerFk` AS `Id_Trabajador`,`wm`.`size` AS `size`,`wm`.`amount` AS `used`,`wm`.`pricesModifierRate` AS `prices_modifier_rate`,`wm`.`isPricesModifierActivated` AS `prices_modifier_activated`,`wm`.`minRate` AS `minRate`,`wm`.`maxRate` AS `maxRate` from `vn`.`workerMana` `wm` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `mermas` +-- + +/*!50001 DROP VIEW IF EXISTS `mermas`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8mb4 */; +/*!50001 SET character_set_results = utf8mb4 */; +/*!50001 SET collation_connection = utf8mb4_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `mermas` AS select `w`.`code` AS `Comprador`,`it`.`name` AS `Familia`,`i`.`id` AS `Referencia`,`i`.`name` AS `Item`,`s`.`quantity` AS `Cantidad`,(((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`) AS `Coste_Unitario`,(`s`.`quantity` * (((`b`.`buyingValue` + `b`.`freightValue`) + `b`.`comissionValue`) + `b`.`packageValue`)) AS `Importe`,`c`.`name` AS `Cliente`,`s`.`ticketFk` AS `ticketFk`,`t`.`shipped` AS `Fecha` from (((((((`vn`.`worker` `w` join `vn`.`itemType` `it` on((`it`.`workerFk` = `w`.`id`))) join `vn`.`item` `i` on((`i`.`typeFk` = `it`.`id`))) join `vn`.`sale` `s` on((`s`.`itemFk` = `i`.`id`))) join `vn`.`ticket` `t` on((`t`.`id` = `s`.`ticketFk`))) join `vn`.`client` `c` on((`c`.`id` = `t`.`clientFk`))) left join `bi`.`Last_buy_id` `lb` on(((`lb`.`Id_Article` = `s`.`itemFk`) and (`lb`.`warehouse_id` = `t`.`warehouseFk`)))) left join `vn`.`buy` `b` on((`b`.`id` = `lb`.`Id_Compra`))) where ((`t`.`shipped` > '2018-01-01') and (`c`.`isRelevant` or (`c`.`id` in (200,400)))) */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + +-- +-- Final view structure for view `workerMana` +-- + +/*!50001 DROP VIEW IF EXISTS `workerMana`*/; +/*!50001 SET @saved_cs_client = @@character_set_client */; +/*!50001 SET @saved_cs_results = @@character_set_results */; +/*!50001 SET @saved_col_connection = @@collation_connection */; +/*!50001 SET character_set_client = utf8 */; +/*!50001 SET character_set_results = utf8 */; +/*!50001 SET collation_connection = utf8_general_ci */; +/*!50001 CREATE ALGORITHM=UNDEFINED */ +/*!50013 DEFINER=`root`@`%` SQL SECURITY DEFINER */ +/*!50001 VIEW `workerMana` AS select `m`.`Id_Trabajador` AS `workerFk`,`m`.`used` AS `amount` from `bs`.`mana_spellers` `m` */; +/*!50001 SET character_set_client = @saved_cs_client */; +/*!50001 SET character_set_results = @saved_cs_results */; +/*!50001 SET collation_connection = @saved_col_connection */; + -- -- Current Database: `cache` -- @@ -52738,4 +56342,4 @@ USE `vncontrol`; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; --- Dump completed on 2019-12-16 8:42:22 +-- Dump completed on 2019-12-16 9:19:16