-- MySQL dump 10.13  Distrib 5.7.17, for Win64 (x86_64)
--
-- Host: db.verdnatura.es    Database: cache
-- ------------------------------------------------------
-- Server version	5.6.25-4-log

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Current Database: `cache`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `cache` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `cache`;

--
-- Table structure for table `available`
--

DROP TABLE IF EXISTS `available`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `available` (
  `calc_id` int(10) unsigned NOT NULL,
  `item_id` int(11) NOT NULL,
  `available` int(11) NOT NULL,
  KEY `calc_id_4` (`calc_id`) USING BTREE,
  KEY `calc_id` (`item_id`,`calc_id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `barcodes`
--

DROP TABLE IF EXISTS `barcodes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `barcodes` (
  `code` varchar(22) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `Id_Article` int(11) NOT NULL DEFAULT '0',
  `Article` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Medida` int(10) unsigned DEFAULT NULL,
  `Color` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Categoria` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Producer` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cache`
--

DROP TABLE IF EXISTS `cache`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cache` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 NOT NULL,
  `lifetime` time NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cache_calc`
--

DROP TABLE IF EXISTS `cache_calc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cache_calc` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `cache_id` int(10) unsigned NOT NULL,
  `cacheName` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `params` varchar(100) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `last_refresh` datetime DEFAULT NULL,
  `expires` datetime DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `connection_id` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `cache_name` (`cache_id`,`params`),
  KEY `cache_id` (`cache_id`),
  KEY `cacheName` (`cacheName`),
  KEY `expires` (`expires`)
) ENGINE=InnoDB AUTO_INCREMENT=44716 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cache_valid`
--

DROP TABLE IF EXISTS `cache_valid`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cache_valid` (
  `valid` tinyint(3) unsigned NOT NULL
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `dailyTaskLog`
--

DROP TABLE IF EXISTS `dailyTaskLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dailyTaskLog` (
  `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `departure_limit`
--

DROP TABLE IF EXISTS `departure_limit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `departure_limit` (
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `fecha` date NOT NULL,
  `hora` int(11) NOT NULL DEFAULT '0',
  `minSpeed` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`warehouse_id`,`fecha`),
  CONSTRAINT `warehouse_departure` FOREIGN KEY (`warehouse_id`) REFERENCES `vn2008`.`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 */;

--
-- Table structure for table `equalizator`
--

DROP TABLE IF EXISTS `equalizator`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `equalizator` (
  `warehouse_id` int(11) NOT NULL,
  `Vista` int(11) NOT NULL,
  `Pedido` int(11) DEFAULT NULL,
  `Impreso` int(11) DEFAULT NULL,
  `Encajado` int(11) DEFAULT NULL,
  PRIMARY KEY (`Vista`,`warehouse_id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemTagFormat`
--

DROP TABLE IF EXISTS `itemTagFormat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTagFormat` (
  `itemFk` int(11) NOT NULL,
  `labels1` varchar(80) CHARACTER SET utf8 DEFAULT NULL,
  `values1` varchar(80) CHARACTER SET utf8 DEFAULT NULL,
  `labels2` varchar(80) CHARACTER SET utf8 DEFAULT NULL,
  `values2` varchar(80) CHARACTER SET utf8 DEFAULT NULL,
  `description` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`itemFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena el formato para los tags de los articulos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `item_range`
--

DROP TABLE IF EXISTS `item_range`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_range` (
  `calc_id` int(11) NOT NULL,
  `item_id` int(11) NOT NULL,
  `date_end` datetime DEFAULT NULL,
  KEY `calc_item` (`calc_id`,`item_id`),
  KEY `calc_id` (`calc_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `last_buy`
--

DROP TABLE IF EXISTS `last_buy`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `last_buy` (
  `item_id` int(10) unsigned NOT NULL,
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `buy_id` int(10) unsigned DEFAULT NULL,
  `landing` date DEFAULT NULL,
  KEY `buy_id` (`buy_id`),
  KEY `item_id` (`item_id`,`warehouse_id`),
  KEY `warehouse_id` (`warehouse_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `prod_graphic_source`
--

DROP TABLE IF EXISTS `prod_graphic_source`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `prod_graphic_source` (
  `m3` double NOT NULL DEFAULT '0',
  `warehouse_id` int(11) NOT NULL,
  `hora` int(11) NOT NULL,
  `order` int(11) NOT NULL DEFAULT '0',
  `alert_level` int(11) NOT NULL DEFAULT '0',
  `Agencia` varchar(45) CHARACTER SET utf8 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `stock`
--

DROP TABLE IF EXISTS `stock`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stock` (
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `item_id` int(10) unsigned NOT NULL,
  `amount` int(11) NOT NULL,
  KEY `warehouse_id` (`warehouse_id`,`item_id`),
  KEY `warehouse_id_2` (`warehouse_id`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `visible`
--

DROP TABLE IF EXISTS `visible`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visible` (
  `calc_id` int(10) unsigned NOT NULL,
  `item_id` int(11) NOT NULL,
  `visible` int(11) NOT NULL,
  KEY `id` (`calc_id`) USING BTREE,
  KEY `calc_id` (`calc_id`,`item_id`)
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `weekly_sales`
--

DROP TABLE IF EXISTS `weekly_sales`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `weekly_sales` (
  `week` int(10) unsigned NOT NULL,
  `item_id` int(10) unsigned NOT NULL,
  `warehouse_id` smallint(5) unsigned NOT NULL,
  `amount` int(11) NOT NULL,
  `price` double NOT NULL,
  KEY `item_id` (`item_id`,`warehouse_id`),
  KEY `week` (`week`) USING BTREE
) ENGINE=MEMORY DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'cache'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `barcodes_update` */;
DELIMITER ;;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `barcodes_update` ON SCHEDULE EVERY 1 HOUR STARTS '2016-08-17 00:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL barcodes_update() */ ;;
/*!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 */ ;;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;;
/*!50106 DROP EVENT IF EXISTS `cacheCalcClean` */;;
DELIMITER ;;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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  = 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' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `cacheCalcClean` ON SCHEDULE EVERY 30 MINUTE STARTS '2017-01-23 13:15:58' ON COMPLETION NOT PRESERVE ENABLE DO CALL cacheCalcClean() */ ;;
/*!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 */ ;;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;;
DELIMITER ;
/*!50106 SET TIME_ZONE= @save_time_zone */ ;

--
-- Dumping routines for database 'cache'
--
/*!50003 DROP PROCEDURE IF EXISTS `available_refresh` */;
/*!50003 SET @saved_cs_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 `available_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT, v_date DATE)
proc: BEGIN
	DECLARE v_date_ini DATE;
	DECLARE v_date_end DATETIME;
	DECLARE v_reserve_date DATETIME;
	DECLARE v_params CHAR(100);
    DECLARE v_date_inv DATE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		CALL cache_calc_unlock (v_calc);
		RESIGNAL;
	END;

	IF v_date < CURDATE()
    THEN
		LEAVE proc;
	END IF;

	CALL vn2008.item_stock (v_warehouse, v_date, NULL);

	SET v_params = CONCAT_WS('/', v_warehouse, v_date);
	CALL cache_calc_start (v_calc, v_refresh, 'available', v_params);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

    -- Limpia las caches antiguas

    DELETE a
		FROM available a
			LEFT JOIN cache_calc c ON c.id = a.calc_id
        WHERE c.id IS NULL;

    -- Calcula algunos parámetros necesarios

	SET v_date_ini = TIMESTAMP(v_date, '00:00:00');
	SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, 4, v_date), '23:59:59');

    SELECT FechaInventario INTO v_date_inv FROM vn2008.tblContadores;

	SELECT SUBTIME(NOW(), reserve_time) INTO v_reserve_date
		FROM hedera.order_config;
	
    -- Calcula el ultimo dia de vida para cada producto

	DROP TEMPORARY TABLE IF EXISTS item_range;
	CREATE TEMPORARY TABLE item_range
	(PRIMARY KEY (item_id))
	ENGINE = MEMORY
	SELECT c.item_id, IF(t.life IS NULL, NULL, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.landing), '23:59:59')) AS date_end
		FROM (
			SELECT c.Id_Article item_id, MAX(landing) landing
				FROM vn2008.Compres c
					JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada
					JOIN vn2008.travel t ON t.id = e.travel_id
					JOIN vn2008.warehouse w ON w.id = t.warehouse_id
				WHERE t.landing BETWEEN v_date_inv AND v_date_ini
					AND t.warehouse_id = v_warehouse
					AND NOT e.Inventario
					AND NOT e.Redada
				GROUP BY Id_Article
		) c
			JOIN vn2008.Articles a ON a.Id_Article = c.item_id
			JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
		HAVING date_end >= v_date_ini OR date_end IS NULL;
/*
    -- Tabla con el ultimo dia de precios fijados para cada producto que hace un replace de la anterior
    
	DROP TEMPORARY TABLE IF EXISTS item_range_copy;
	CREATE TEMPORARY TABLE item_range_copy LIKE item_range;
    INSERT INTO item_range_copy 
		SELECT * FROM item_range;

	REPLACE item_range
	SELECT item_id, TIMESTAMP(date_end, '23:59:59') date_end FROM (
			SELECT p.item_id, p.date_end
				FROM vn2008.price_fixed p
					LEFT JOIN item_range_copy i USING(item_id)
				WHERE IFNULL(i.date_end,v_date_ini) BETWEEN p.date_start AND p.date_end 
					AND warehouse_id IN (0, v_warehouse)  
				ORDER BY item_id, warehouse_id DESC, date_end DESC
		) t GROUP BY item_id;

    DROP TEMPORARY TABLE item_range_copy;
*/
    -- Replica la tabla item_range para poder usarla varias veces en la misma consulta

	DROP TEMPORARY TABLE IF EXISTS item_range_copy1;
	CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range;   
	INSERT INTO item_range_copy1 
		SELECT * FROM item_range;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy2;
	CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range;
	INSERT INTO item_range_copy2 
		SELECT * FROM item_range;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy3;
	CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range;
	INSERT INTO item_range_copy3 
		SELECT * FROM item_range;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy4;
	CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range;
	INSERT INTO item_range_copy4 
		SELECT * FROM item_range;

    -- Calcula el ATP

	DELETE FROM available WHERE calc_id = v_calc;

	INSERT INTO available (calc_id, item_id, available)
	SELECT v_calc, t.item_id, SUM(stock) amount FROM (	
		SELECT ti.item_id, stock
			FROM vn2008.tmp_item ti
				JOIN item_range ir ON ir.item_id = ti.item_id 
		UNION ALL
		SELECT t.item_id, minacum(dt, amount, v_date) AS available FROM (
			SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM (
				SELECT i.item_id, i.dat, i.amount
					FROM vn2008.item_out i
						JOIN item_range_copy1 ir ON ir.item_id = i.item_id   
					WHERE i.dat >= v_date_ini
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = v_warehouse
				UNION ALL
				SELECT i.item_id, i.dat, i.amount
					FROM vn2008.item_entry_in i
						JOIN item_range_copy2 ir ON ir.item_id = i.item_id   
					WHERE i.dat >= v_date_ini
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = v_warehouse
				UNION ALL
				SELECT i.item_id, i.dat, i.amount
					FROM vn2008.item_entry_out i
						JOIN item_range_copy3 ir ON ir.item_id = i.item_id 
					WHERE i.dat >= v_date_ini 
                        AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = v_warehouse
				UNION ALL
				SELECT r.item_id, r.shipment, -r.amount
					FROM hedera.order_row r
						JOIN hedera.`order` o ON o.id = r.order_id
						JOIN item_range_copy4 ir ON ir.item_id = r.item_id
					WHERE r.shipment >= v_date_ini
						AND (ir.date_end IS NULL OR r.shipment <= ir.date_end)
						AND r.warehouse_id = v_warehouse
						AND r.created >= v_reserve_date
						AND NOT o.confirmed
			) t
			GROUP BY item_id, dt
		) t
		GROUP BY t.item_id 
	) t GROUP BY t.item_id HAVING amount != 0;


	DROP TEMPORARY TABLE
		 vn2008.tmp_item
		,item_range
		,item_range_copy1
		,item_range_copy2
		,item_range_copy3
		,item_range_copy4;

	CALL cache_calc_end (v_calc);
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 `available_refreshtest` */;
/*!50003 SET @saved_cs_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 `available_refreshtest`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT, v_date DATE)
proc: BEGIN
	DECLARE v_date_ini DATE;
	DECLARE v_date_end DATETIME;
	DECLARE v_reserve_date DATETIME;
	DECLARE v_params CHAR(100);
    DECLARE v_date_inv DATE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		CALL cache_calc_unlock (v_calc);
		RESIGNAL;
	END;

	IF v_date < CURDATE()
    THEN
		LEAVE proc;
	END IF;

	CALL vn2008.item_stock (v_warehouse, v_date, NULL);

	SET v_params = CONCAT_WS('/', v_warehouse, v_date);
	CALL cache_calc_start (v_calc, v_refresh, 'available', v_params);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

    -- Limpia las caches antiguas
    
    IF TRUE -- GET_LOCK('available/clean', 1)
    THEN
		DELETE FROM available WHERE calc_id NOT IN (
			SELECT cc.id
				FROM `cache` c
                JOIN cache_calc cc ON c.id = cc.cache_id
					WHERE c.`name` = 'available');
                    
		-- DO RELEASE_LOCK('available/clean');
	END IF;

    -- Calcula algunos parámetros necesarios

	SET v_date_ini = TIMESTAMP(v_date, '00:00:00');
	SET v_date_end = TIMESTAMP(TIMESTAMPADD(DAY, 4, v_date), '23:59:59');

    SELECT FechaInventario INTO v_date_inv FROM vn2008.tblContadores;

	SELECT SUBTIME(NOW(), reserve_time) INTO v_reserve_date
		FROM hedera.order_config;
	
    -- Calcula el ultimo dia de vida para cada producto

	DROP TEMPORARY TABLE IF EXISTS item_range;
	CREATE TEMPORARY TABLE item_range
	(PRIMARY KEY (item_id))
	ENGINE = MEMORY
	SELECT c.item_id, IF(t.life IS NULL, NULL, TIMESTAMP(TIMESTAMPADD(DAY, t.life, c.landing), '23:59:59')) AS date_end
		FROM (
			SELECT c.Id_Article item_id, MAX(landing) landing
				FROM vn2008.Compres c
					JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada
					JOIN vn2008.travel t ON t.id = e.travel_id
					JOIN vn2008.warehouse w ON w.id = t.warehouse_id
				WHERE t.landing BETWEEN v_date_inv AND v_date_ini
					AND t.warehouse_id = v_warehouse
					AND NOT e.Inventario
					AND NOT e.Redada
				GROUP BY Id_Article
		) c
			JOIN vn2008.Articles a ON a.Id_Article = c.item_id
			JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
		HAVING date_end >= v_date_ini OR date_end IS NULL;
/*
    -- Tabla con el ultimo dia de precios fijados para cada producto que hace un replace de la anterior
    
	DROP TEMPORARY TABLE IF EXISTS item_range_copy;
	CREATE TEMPORARY TABLE item_range_copy LIKE item_range;
    INSERT INTO item_range_copy 
		SELECT * FROM item_range;

	REPLACE item_range
	SELECT item_id, TIMESTAMP(date_end, '23:59:59') date_end FROM (
			SELECT p.item_id, p.date_end
				FROM vn2008.price_fixed p
					LEFT JOIN item_range_copy i USING(item_id)
				WHERE IFNULL(i.date_end,v_date_ini) BETWEEN p.date_start AND p.date_end 
					AND warehouse_id IN (0, v_warehouse)  
				ORDER BY item_id, warehouse_id DESC, date_end DESC
		) t GROUP BY item_id;

    DROP TEMPORARY TABLE item_range_copy;
*/
    -- Replica la tabla item_range para poder usarla varias veces en la misma consulta
     
	DROP TEMPORARY TABLE IF EXISTS item_range_copy1;
	CREATE TEMPORARY TABLE item_range_copy1 LIKE item_range;   
	INSERT INTO item_range_copy1 
		SELECT * FROM item_range;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy2;
	CREATE TEMPORARY TABLE item_range_copy2 LIKE item_range;
	INSERT INTO item_range_copy2 
		SELECT * FROM item_range;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy3;
	CREATE TEMPORARY TABLE item_range_copy3 LIKE item_range;
	INSERT INTO item_range_copy3 
		SELECT * FROM item_range;
		
	DROP TEMPORARY TABLE IF EXISTS item_range_copy4;
	CREATE TEMPORARY TABLE item_range_copy4 LIKE item_range;
	INSERT INTO item_range_copy4 
		SELECT * FROM item_range;

    -- Calcula el ATP

	DELETE FROM available WHERE calc_id = v_calc;

	INSERT INTO available (calc_id, item_id, available)
	SELECT v_calc, t.item_id, SUM(stock) amount FROM (	
		SELECT ti.item_id, stock
			FROM vn2008.tmp_item ti
				JOIN item_range ir ON ir.item_id = ti.item_id 
		UNION ALL
		SELECT t.item_id, minacum(dt, amount, v_date) AS available FROM (
			SELECT item_id, DATE(dat) dt, SUM(amount) amount FROM (
				SELECT i.item_id, i.dat, i.amount
					FROM vn2008.item_out i
						JOIN item_range_copy1 ir ON ir.item_id = i.item_id   
					WHERE i.dat >= v_date_ini
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = v_warehouse
				UNION ALL
				SELECT i.item_id, i.dat, i.amount
					FROM vn2008.item_entry_in i
						JOIN item_range_copy2 ir ON ir.item_id = i.item_id   
					WHERE i.dat >= v_date_ini
						AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = v_warehouse
				UNION ALL
				SELECT i.item_id, i.dat, i.amount
					FROM vn2008.item_entry_out i
						JOIN item_range_copy3 ir ON ir.item_id = i.item_id 
					WHERE i.dat >= v_date_ini 
                        AND (ir.date_end IS NULL OR i.dat <= ir.date_end)
						AND i.warehouse_id = v_warehouse
				UNION ALL
				SELECT r.item_id, r.shipment, -r.amount
					FROM hedera.order_row r
						JOIN hedera.`order` o ON o.id = r.order_id
						JOIN item_range_copy4 ir ON ir.item_id = r.item_id
					WHERE r.shipment >= v_date_ini
						AND (ir.date_end IS NULL OR r.shipment <= ir.date_end)
						AND r.warehouse_id = v_warehouse
						AND r.created >= v_reserve_date
						AND NOT o.confirmed
			) t
			GROUP BY item_id, dt
		) t
		GROUP BY t.item_id 
	) t GROUP BY t.item_id HAVING amount != 0;

	DROP TEMPORARY TABLE
		 vn2008.tmp_item
		,item_range
		,item_range_copy1
		,item_range_copy2
		,item_range_copy3
		,item_range_copy4;

	CALL cache_calc_end (v_calc);
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 `barcodes_articles_update` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `barcodes_articles_update`()
BEGIN

REPLACE cache.barcodes

	SELECT 
        `Articles`.`Id_Article` AS `code`,
        `Articles`.`Id_Article` AS `Id_Article`,
        `Articles`.`Article` AS `Article`,
        `Articles`.`Medida` AS `Medida`,
        `Articles`.`Color` AS `Color`,
        `Articles`.`Categoria` AS `Categoria`,
        `p`.`name` AS `Producer`
    FROM
        vn2008.Articles
	LEFT JOIN vn2008.`producer` `p` using(producer_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 */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `barcodes_barcodes_update` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `barcodes_barcodes_update`()
BEGIN

REPLACE cache.barcodes

	SELECT 
        `barcodes`.`code` AS `code`,
        `barcodes`.`Id_Article` AS `Id_Article`,
        `Articles`.`Article` AS `Article`,
        `Articles`.`Medida` AS `Medida`,
        `Articles`.`Color` AS `Color`,
        `Articles`.`Categoria` AS `Categoria`,
        `p`.`name` AS `Producer`
    FROM
        vn2008.`barcodes` 
    JOIN
        vn2008.Articles using(Id_Article)
	LEFT JOIN vn2008.`producer` `p` using(producer_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 */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `barcodes_compres_update` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `barcodes_compres_update`()
BEGIN

REPLACE cache.barcodes

	SELECT 
        Compres.`Id_Compra` AS `code`,
        Compres.`Id_Article` AS `Id_Article`,
        `Articles`.`Article` AS `Article`,
        `Articles`.`Medida` AS `Medida`,
        `Articles`.`Color` AS `Color`,
        `Articles`.`Categoria` AS `Categoria`,
        producer.`name` AS `Producer`
        
        
    FROM
        vn2008.Compres
        JOIN vn2008.Articles using(Id_Article)
        LEFT JOIN vn2008.producer  using(producer_id)
        JOIN vn2008.Entradas  using(Id_Entrada)
        JOIN vn2008.travel on travel.id = travel_id
    WHERE
        landing >= TIMESTAMPADD(WEEK, -2, 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 */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `barcodes_expeditions_update` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `barcodes_expeditions_update`(IN idExpedition BIGINT)
BEGIN

REPLACE cache.barcodes

	SELECT 
        `e`.`expeditions_id` AS `code`,
        `Tickets`.`Id_Ruta` AS `Id_Article`,
        `Tickets`.`Alias` AS `Article`,
        `Tickets`.`Bultos` AS `Medida`,
        `Tickets`.`Id_Ruta` AS `Color`,
        `w`.`name` AS `Categoria`,
        `a`.`Agencia` AS `Producer`
    FROM
        vn2008.expeditions `e`
        JOIN vn2008.Tickets ON `Tickets`.`Id_Ticket` = `e`.`ticket_id`
        JOIN vn2008.warehouse `w` ON `w`.`id` = `Tickets`.`warehouse_id`
        JOIN vn2008.Rutas `r` ON `r`.`Id_Ruta` = `Tickets`.`Id_Ruta`
        JOIN vn2008.Agencias `a` ON `a`.`Id_Agencia` = `r`.`Id_Agencia`
    WHERE
		idExpedition IN (e.expeditions_id,0) 
    AND
        `Tickets`.`Fecha` >= (CURDATE() + INTERVAL -(2) DAY)  
        
   
   	;
        
        
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `barcodes_update` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `barcodes_update`()
BEGIN

		declare allExpeditions int default 0;

		call barcodes_articles_update;

		call barcodes_barcodes_update;
        
        call barcodes_compres_update;
        
        call barcodes_expeditions_update(allExpeditions);
        
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `cacheCalcClean` */;
/*!50003 SET @saved_cs_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 `cacheCalcClean`()
BEGIN
	DECLARE vCleanTime DATETIME DEFAULT TIMESTAMPADD(MINUTE, -5, NOW());

	DELETE FROM cache_calc WHERE expires < vCleanTime;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `cache_calc_end` */;
/*!50003 SET @saved_cs_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 `cache_calc_end`(v_calc INT)
BEGIN
	DECLARE v_cache_name VARCHAR(255);
	DECLARE v_params VARCHAR(255);

	-- Libera el bloqueo y actualiza la fecha de ultimo refresco.

	UPDATE cache_calc cc JOIN cache c ON c.id = cc.cache_id
		SET
			cc.last_refresh = NOW(),
            cc.expires = ADDTIME(NOW(), c.lifetime),
			cc.connection_id = NULL
				WHERE cc.id = v_calc;
    
	SELECT c.name, ca.params INTO v_cache_name, v_params
		FROM cache c
		JOIN cache_calc ca ON c.id = ca.cache_id
			WHERE ca.id = v_calc;

	DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, '')));
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 `cache_calc_start` */;
/*!50003 SET @saved_cs_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 `cache_calc_start`(OUT v_calc INT, INOUT v_refresh BOOL, v_cache_name VARCHAR(50), v_params VARCHAR(100))
proc: BEGIN
	DECLARE v_valid BOOL;
	DECLARE v_lock_id VARCHAR(100);
	DECLARE v_cache_id INT;
	DECLARE v_expires DATETIME;
	DECLARE v_clean_time DATETIME;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		DO RELEASE_LOCK(v_lock_id);
		RESIGNAL;
	END;

	SET v_params = IFNULL(v_params, '');
	
	-- Si el servidor se ha reiniciado invalida todos los calculos.
	
	SELECT COUNT(*) > 0 INTO v_valid FROM cache_valid;
	
	IF !v_valid
	THEN
		DELETE FROM cache_calc;
		INSERT INTO cache_valid (valid) VALUES (TRUE);
	END IF;

	-- Obtiene un bloqueo exclusivo para que no haya problemas de concurrencia.
    
	SET v_lock_id = CONCAT_WS('/', v_cache_name, v_params);

	IF !GET_LOCK(v_lock_id, 30)
	THEN
		SET v_calc = NULL;
		SET v_refresh = FALSE;
		LEAVE proc;
	END IF;
    
	-- Comprueba si el calculo solicitado existe y esta actualizado.

	SELECT c.id, ca.id, ca.expires
		INTO v_cache_id, v_calc, v_expires
		FROM cache c
			LEFT JOIN cache_calc ca
				ON ca.cache_id = c.id AND ca.params = v_params COLLATE 'utf8_general_ci' 
		WHERE c.name = v_cache_name COLLATE 'utf8_general_ci';
                
	-- Si existe una calculo valido libera el bloqueo y devuelve su identificador.

	IF !v_refresh AND NOW() < v_expires
	THEN
		DO RELEASE_LOCK(v_lock_id);
		SET v_refresh = FALSE;
		LEAVE proc;
	END IF;
    
    -- Si el calculo no existe le crea una entrada en la tabla de calculos.
    
	IF v_calc IS NULL
	THEN
		INSERT INTO cache_calc SET
			cache_id = v_cache_id,
            cacheName = v_cache_name,
            params = v_params,
            last_refresh = NULL,
            expires = NULL,
            connection_id = CONNECTION_ID();
			
		SET v_calc = LAST_INSERT_ID();
	ELSE
		UPDATE cache_calc
			SET
				last_refresh = NULL,
				expires = NULL,
				connection_id = CONNECTION_ID()
			WHERE id = v_calc;
	END IF;

	-- Si se debe recalcular mantiene el bloqueo y devuelve su identificador.

	SET v_refresh = TRUE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `cache_calc_unlock` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `cache_calc_unlock`(v_calc INT)
BEGIN
	DECLARE v_cache_name VARCHAR(50);
	DECLARE v_params VARCHAR(100);

	SELECT c.name, ca.params INTO v_cache_name, v_params
		FROM cache c
		JOIN cache_calc ca ON c.id = ca.cache_id
			WHERE ca.id = v_calc;
            
	DELETE FROM cache_calc WHERE id = v_calc;

	DO RELEASE_LOCK(CONCAT_WS('/', v_cache_name, IFNULL(v_params, '')));
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
/*!50003 SET @saved_cs_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 `clean`()
BEGIN
  
    DECLARE vDateShort DATETIME; 

    SET vDateShort = TIMESTAMPADD(MONTH, -1, CURDATE());

    INSERT INTO cache.dailyTaskLog(state) VALUES('clean START');

    DELETE FROM cache.departure_limit WHERE Fecha < vDateShort;

    INSERT INTO cache.dailyTaskLog(state) VALUES('clean END');
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 `departure_timing` */;
/*!50003 SET @saved_cs_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 `departure_timing`()
BEGIN

DECLARE done BOOL DEFAULT FALSE;
DECLARE rsDeparture INT;
DECLARE rsHoras DECIMAL(5,2);
DECLARE rsInicio DECIMAL(5,2);
DECLARE resto DECIMAL(5,2);
DECLARE horasProd DECIMAL(5,2);
DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00;
DECLARE myTime DECIMAL(5,2);
DECLARE departureLimit INT;
DECLARE myWarehouse INT;
DECLARE myMinSpeed DECIMAL(10,2);
DECLARE vLoadingDelay DECIMAL(5) DEFAULT 2;


DECLARE rs CURSOR FOR
	SELECT Departure
    , Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3) AS Horas
	, curDate()+(Departure + vLoadingDelay -(Sum(pb.m3)/(GREATEST(v.m3,IFNULL(minSpeed,0))/1.3))/24) AS InicioPreparacion
	FROM tmp.production_buffer pb
	JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id
	LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE()
	WHERE pb.Fecha = CURDATE()
	AND alert_level < 2
	AND IFNULL(Departure,0) > 0
	GROUP BY Departure
	ORDER BY Departure DESC;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

SET myTime = HOUR(now()) + MINUTE(now()) / 60; 

SELECT warehouse_id INTO myWarehouse
FROM  tmp.production_buffer
LIMIT 1;

OPEN rs;

FETCH rs INTO rsDeparture, rsHoras , rsInicio;

-- SELECT rsDeparture, rsHoras , rsInicio, myWarehouse;

WHILE NOT done DO

	SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0);
    
    SET inicioProd = rsDeparture - rsHoras;
    
    IF inicioProd - resto < myTime THEN
    
		SET done = TRUE;
        
	ELSE
    
		SET departureLimit = rsDeparture;
        
		FETCH rs INTO rsDeparture, rsHoras , rsInicio;
        
        -- SELECT rsDeparture, rsHoras , rsInicio;
        
    END IF;
	
END WHILE;

SET departureLimit = IFNULL(departureLimit,24);
SET departureLimit = IF(departureLimit = 0, 24, departureLimit);

	SELECT minSpeed INTO myMinSpeed
	FROM cache.departure_limit
	WHERE warehouse_id = myWarehouse
	AND fecha = CURDATE();

	REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed)
    VALUES (myWarehouse, CURDATE(), IFNULL(departureLimit,24), IFNULL(myMinSpeed,0));


CLOSE rs;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_beta` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `departure_timing_beta`()
BEGIN

DECLARE done BOOL DEFAULT FALSE;
DECLARE rsDeparture INT;
DECLARE rsHoras DECIMAL(5,2);
DECLARE rsInicio DECIMAL(5,2);
DECLARE resto DECIMAL(5,2);
DECLARE horasProd DECIMAL(5,2);
DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00;
DECLARE myTime DECIMAL(5,2);
DECLARE departureLimit INT;
DECLARE myWarehouse INT;

DECLARE rs CURSOR FOR
	SELECT Departure
	, Sum(pb.m3)/GREATEST(v.m3,IFNULL(minSpeed,0)) AS Horas
	, curDate()+(Departure-(Sum(pb.m3)/GREATEST(v.m3,IFNULL(minSpeed,0)))/24) AS InicioPreparacion
	FROM tmp.production_buffer pb
	JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id
    LEFT JOIN cache.departure_limit dp ON dp.warehouse_id = pb.warehouse_id AND dp.fecha = CURDATE()
	WHERE pb.Fecha = CURDATE()
	AND alert_level < 2
	AND IFNULL(Departure,0) > 0
	GROUP BY Departure
	ORDER BY Departure DESC;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;



SET myTime = HOUR(now()) + MINUTE(now()) / 60; 

SELECT warehouse_id INTO myWarehouse
FROM  tmp.production_buffer
LIMIT 1;

OPEN rs;

FETCH rs INTO rsDeparture, rsHoras , rsInicio;

SELECT rsDeparture, rsHoras , rsInicio,  myWarehouse, done;

WHILE NOT done DO

	SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0);
    
    SET inicioProd = rsDeparture - rsHoras;
    
    SELECT rsDeparture, rsHoras , rsInicio, resto,inicioProd;
    
    IF inicioProd - resto < myTime THEN
    
		SET done = TRUE;
        
	ELSE
    
		SET departureLimit = rsDeparture;
        
		FETCH rs INTO rsDeparture, rsHoras , rsInicio;
        
    END IF;
	
END WHILE;

SELECT rsDeparture, rsHoras , rsInicio, resto,inicioProd;
  

SET departureLimit = IFNULL(departureLimit,24);

IF departureLimit > 0 THEN

	REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed)
    VALUES (myWarehouse, CURDATE(), departureLimit, myMinSpeed);

END IF;

CLOSE rs;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `departure_timing_kk` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `departure_timing_kk`()
BEGIN

DECLARE done BOOL DEFAULT FALSE;
DECLARE rsDeparture INT;
DECLARE rsHoras DECIMAL(5,2);
DECLARE rsInicio DECIMAL(5,2);
DECLARE resto DECIMAL(5,2);
DECLARE horasProd DECIMAL(5,2);
DECLARE inicioProd DECIMAL(5,2) DEFAULT 24.00;
DECLARE myTime DECIMAL(5,2);
DECLARE departureLimit INT;
DECLARE myWarehouse INT;
DECLARE myMinSpeed DECIMAL(10,2);


DECLARE rs CURSOR FOR
	SELECT Departure
	, Sum(pb.m3)/(GREATEST(v.m3, 100)/1.3) AS Horas
	, curDate()+(Departure-Sum(pb.m3)/(GREATEST(v.m3, 100)/1.3))/24 AS InicioPreparacion
	FROM tmp.production_buffer pb
	JOIN vn2008.v_encajado_ultima_hora v ON v.warehouse_id = pb.warehouse_id
	WHERE Fecha = CURDATE()
	AND alert_level < 2
	AND IFNULL(Departure,0) > 0
	GROUP BY Departure
	ORDER BY Departure DESC;

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

SELECT IFNULL(minSpeed,0) INTO myMinSpeed
FROM cache.departure_limit
WHERE warehouse_id = myWarehouse
AND fecha = CURDATE();

SET myTime = HOUR(now()) + MINUTE(now()) / 60; 

SELECT warehouse_id INTO myWarehouse
FROM  tmp.production_buffer
LIMIT 1;

OPEN rs;

FETCH rs INTO rsDeparture, rsHoras , rsInicio;

WHILE NOT done DO

	SET resto = IF(inicioProd < rsDeparture, rsDeparture - inicioProd,0);
    
    SET inicioProd = rsDeparture - rsHoras;
    
    IF inicioProd - resto < myTime THEN
    
		SET done = TRUE;
        
	ELSE
    
		SET departureLimit = rsDeparture;
        
		FETCH rs INTO rsDeparture, rsHoras , rsInicio;
        
    END IF;
	
END WHILE;

IF departureLimit > 0 THEN

	REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed)
    VALUES (myWarehouse, CURDATE(), departureLimit, myMinSpeed);

END IF;

CLOSE rs;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `equaliza` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `equaliza`(wh_id INT)
BEGIN
	-- DEPRECATED usar equalizator_refesh
    
    
    
	CALL equalizator_refresh (FALSE, wh_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 */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `equalizator_refresh` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `equalizator_refresh`(v_refresh BOOL, wh_id INT)
proc: BEGIN
	DECLARE datEQ DATETIME;
	DECLARE timDIF TIME;
    DECLARE v_calc INT;
    /* JGF 2017-03-20 cuelga el sistema
    CALL cache_calc_start (v_calc, v_refresh, 'equalizator', wh_id);
    
    IF !v_refresh
    THEN
		LEAVE proc;
	END IF;

	REPLACE equalizator (warehouse_id, Vista, Encajado, Impreso, Pedido)
	SELECT
		t.warehouse_id,
		Vista,
		sum(IF(t.Factura IS NOT NULL
				OR t.Etiquetasemitidas
				OR IFNULL(ticket_id,0), Cantidad  * r.cm3, 0)) as encajado,
		sum(IF(PedidoImpreso, Cantidad  * r.cm3,0))  as impreso,
		sum(Cantidad  * r.cm3 )  as Pedido
	FROM
		vn2008.Movimientos m
			JOIN
		vn2008.Tickets t USING (Id_Ticket)
			JOIN 
		bi.rotacion r on r.warehouse_id = t.warehouse_id and r.Id_Article = m.Id_Article
			JOIN
		vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia
			JOIN
		vn2008.Clientes C USING (Id_Cliente)
			LEFT JOIN
		(SELECT distinct
			ticket_id
		FROM
			vn2008.expeditions e JOIN vn2008.Tickets t
				ON t.Id_Ticket = e.ticket_id
		WHERE Fecha >= curDate()
		) exp ON ticket_id = Id_Ticket
	WHERE
		invoice And Fecha >= curDate()
			AND wh_id in (0,t.warehouse_id)
			AND fecha < (TIMESTAMPADD(DAY, 1, CURDATE()))
	GROUP BY t.warehouse_id, Vista;

	-- Reducimos las cantidades para que el grafico tenga sentido

	UPDATE equalizator SET
		pedido = (pedido - (impreso - encajado) - encajado) / 1000000,
		impreso = (impreso - encajado) / 1000000,
        encajado = encajado / 1000000
			WHERE wh_id in (0,warehouse_id);

    CALL cache_calc_end (v_calc);
    */
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `item_range_refresh` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `item_range_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT, v_date DATE)
proc: BEGIN
	DECLARE v_params CHAR(100);
	DECLARE v_date_inv DATE;

	IF v_date < CURDATE()
	THEN
		LEAVE proc;
	END IF;

	SET v_params = CONCAT_WS('/', v_warehouse, v_date);
	CALL cache_calc_start (v_calc, v_refresh, 'item_range', v_params);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

	-- Limpia las caches antiguas

	DELETE FROM item_range WHERE calc_id NOT IN (
		SELECT cc.id
			FROM `cache` c
			JOIN cache_calc cc ON c.id = cc.cache_id
				WHERE c.`name` = 'item_range');

    -- Calculos previos

    CALL last_buy_refresh (FALSE);

	SET v_date_inv = vn2008.date_inv();

	-- Calcula el ultimo dia de vida para cada producto

	DROP TEMPORARY TABLE IF EXISTS tmp.item_range;
	CREATE TEMPORARY TABLE tmp.item_range
    (INDEX (item_id))
	ENGINE = MEMORY
	SELECT c.item_id, IF(t.life IS NULL, NULL, TIMESTAMPADD(DAY, t.life + 1, GREATEST(c.landing, b.landing))) AS date_end
		FROM last_buy b
			JOIN (
				SELECT c.Id_Article item_id, MAX(landing) landing
					FROM vn2008.Compres c
						JOIN vn2008.Entradas e ON c.Id_Entrada = e.Id_Entrada
						JOIN vn2008.travel t ON t.id = e.travel_id
						JOIN vn2008.warehouse w ON w.id = t.warehouse_id
					WHERE t.landing BETWEEN v_date_inv AND v_date
						AND t.warehouse_id = v_warehouse
						AND NOT e.Inventario
						AND NOT e.Redada
					GROUP BY item_id
			) c ON c.item_id = b.item_id
			JOIN vn2008.Articles a ON a.Id_Article = b.item_id
			JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
		WHERE b.warehouse_id = v_warehouse
		HAVING date_end >= v_date OR date_end IS NULL;

	-- Tabla con el ultimo dia de precios fijados para cada producto

	DROP TEMPORARY TABLE IF EXISTS tmp.fix_range;
	CREATE TEMPORARY TABLE tmp.fix_range
	ENGINE = MEMORY
	SELECT item_id, date_end FROM (
			SELECT p.item_id, p.date_end
				FROM vn2008.price_fixed p
					LEFT JOIN tmp.item_range i USING(item_id)
				WHERE IFNULL(i.date_end, v_date) BETWEEN p.date_start AND p.date_end 
					AND warehouse_id IN (0, v_warehouse)  
				ORDER BY item_id, warehouse_id DESC, date_end DESC
		) t GROUP BY item_id;

	-- Calcula los rangos

	DELETE FROM item_range WHERE calc_id = v_calc;

	INSERT INTO item_range (calc_id, item_id, date_end)
	SELECT v_calc, item_id, date_end
		FROM (
			SELECT * FROM tmp.fix_range
			UNION ALL
			SELECT * FROM tmp.item_range
		) t
		GROUP BY item_id;

	-- Limpieza

	DROP TEMPORARY TABLE tmp.item_range;
 	DROP TEMPORARY TABLE tmp.fix_range;

	CALL cache_calc_end (v_calc);
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `last_buy_refresh` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `last_buy_refresh`(v_refresh BOOL)
proc: BEGIN
/**
 * Crea o actualiza la cache con la última compra y fecha de cada
 * artículo hasta ayer. Para obtener la última compra hasta una fecha
 * determinada utilizar el procedimiento vn2008.item_last_buy_().
 *
 * @param v_refresh %TRUE para forzar el recálculo de la cache
 **/
	DECLARE v_calc INT;
    DECLARE v_date_ini DATE;
    DECLARE v_date_end DATE;
    DECLARE v_last_refresh DATE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		CALL cache_calc_unlock (v_calc);
		RESIGNAL;
	END;

    CALL cache_calc_start (v_calc, v_refresh, 'last_buy', NULL);

    IF !v_refresh
    THEN
		LEAVE proc;
	END IF;

	-- TODO: ¿Se puede usar la fecha del ultimo inventario?
	SET v_date_ini = vn2008.date_inv();-- TIMESTAMPADD(DAY, -90, CURDATE());
	SET v_date_end = CURDATE(); -- TIMESTAMPADD(DAY, -1, CURDATE());

	CALL vn2008.item_last_buy_from_interval (NULL, v_date_ini, v_date_end);

	DELETE FROM last_buy;

	INSERT INTO last_buy (item_id, warehouse_id, buy_id, landing)
		SELECT item_id, warehouse_id, buy_id, landing
			FROM tmp.item_last_buy_from_interval;

	DROP TEMPORARY TABLE tmp.item_last_buy_from_interval;

    CALL cache_calc_end (v_calc);
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `prod_graphic_refresh` */;
/*!50003 SET @saved_cs_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 `prod_graphic_refresh`(v_refresh BOOL, wh_id INT)
proc: BEGIN
	DECLARE datEQ DATETIME;
	DECLARE timDIF TIME;
    DECLARE v_calc INT;
    
    CALL cache_calc_start (v_calc, v_refresh, 'prod_graphic', wh_id);
    
    IF !v_refresh
    THEN
		LEAVE proc;
	END IF;
    
    CALL vn2008.production_control_source(wh_id, 0);

	DELETE FROM prod_graphic_source;

	INSERT INTO prod_graphic_source (warehouse_id,  alert_level, m3, hora, `order`, Agencia)
	SELECT
		wh_id,
        pb.alert_level,
        m3,
        pb.Hora,
        pb.state_order,
        pb.Agencia
	FROM tmp.production_buffer pb
    WHERE Fecha = CURDATE()
    ;
    
    
    CALL cache_calc_end (v_calc);
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 `sales_refresh` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `sales_refresh`()
proc:BEGIN

  DECLARE v_calc INT;
  DECLARE v_refresh BOOL DEFAULT TRUE;
  DECLARE datMONTH INT;
  DECLARE datYEAR INT;

	CALL cache_calc_start (v_calc, v_refresh, 'sales', NULL);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

    
  SELECT MONTH(CURDATE()) INTO datMONTH;
  SELECT YEAR(CURDATE()) INTO datYEAR; 
  
  -- preparamos una tabla con los meses y años que interesan
  DROP TEMPORARY TABLE IF EXISTS tmp.periods;
  CREATE TEMPORARY TABLE tmp.periods
  select distinct month, year(date) as year
  from vn2008.time
  where date <= CURDATE()
  order by year desc, month desc
  limit 3;

  -- borramos los datos para evitar flecos
  DELETE s.* 
  FROM bi.sales s
  join tmp.periods using(year,month);
  
  -- insertamos las ventas de cada comercial
	REPLACE bi.sales(Id_Trabajador, year, month, weight, boss_id)
	select v.Id_Trabajador, year, month, round(sum(total)) as weight,  IFNULL(j.boss_id,20)
	from bi.v_ticket_total v
    join tmp.periods using(year,month)
    left join (SELECT jerarquia.boss_id, jerarquia.worker_id
                FROM vn2008.jerarquia
            ) j on j.worker_id = v.Id_Trabajador
	group by v.Id_Trabajador, year, month;
  
  

 -- caso especial: Claudi ajuda a Josep a llegar a los 1200 euros de comision
 /*
 update bi.sales
 set boss_aid = 34285 - weight
 where Id_Trabajador = 378
 and year >= 2015 
    and month > datmonth -2;
 
 update bi.sales s
 join
      (select year, month, boss_aid
       from bi.sales
       where Id_Trabajador = 378 
       and year >= 2015 
       and month > datmonth -2) sub using(year,month)
 set s.boss_aid = s.boss_aid - sub.boss_aid
 where Id_Trabajador = 208
 and year >= 2015 
 and month > datmonth -2;
 */
 
 
 
 
-- ahora, las comisiones

update bi.sales s
set comision = weight   * 0.029;

    DROP TEMPORARY TABLE IF EXISTS tmp.periods;

	CALL cache_calc_end (v_calc);
    
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `stock_refresh` */;
/*!50003 SET @saved_cs_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 `stock_refresh`(v_refresh BOOL)
proc: BEGIN
/**
 * Crea o actualiza la cache con el disponible hasta el día de 
 * ayer. Esta cache es usada como base para otros procedimientos
 * como el cáculo del visible o del ATP.
 *
 * @param v_refresh %TRUE para forzar el recálculo de la cache
 **/
	DECLARE v_calc INT;
	DECLARE v_date_inv DATE;
	DECLARE v_curdate DATE;
	DECLARE v_last_refresh DATETIME;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		CALL cache_calc_unlock (v_calc);
		RESIGNAL;
	END;

	CALL cache_calc_start (v_calc, v_refresh, 'stock', NULL);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

	SET v_date_inv = (SELECT FechaInventario FROM vn2008.tblContadores LIMIT 1);
	SET v_curdate = CURDATE();
	
	DELETE FROM stock;
	
	INSERT INTO stock (item_id, warehouse_id, amount)
	SELECT item_id, warehouse_id, SUM(amount) amount FROM
	(
		SELECT item_id, warehouse_id, amount FROM vn2008.item_out
			WHERE dat >= v_date_inv AND dat < v_curdate
		UNION ALL
		SELECT item_id, warehouse_id, amount FROM vn2008.item_entry_in
			WHERE dat >= v_date_inv AND dat < v_curdate
		UNION ALL
		SELECT item_id ,warehouse_id, amount FROM vn2008.item_entry_out
			WHERE dat >= v_date_inv AND dat < v_curdate
	) t
	GROUP BY item_id, warehouse_id HAVING amount != 0;

    CALL cache_calc_end (v_calc);
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 `visible_refresh` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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 `visible_refresh`(OUT v_calc INT, v_refresh BOOL, v_warehouse INT)
proc: BEGIN
	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		CALL cache_calc_unlock (v_calc);
		RESIGNAL;
	END;

    CALL cache_calc_start (v_calc, v_refresh, 'visible', v_warehouse);

	IF !v_refresh
	THEN
		LEAVE proc;
	END IF;

    -- Limpia las caches antiguas
    
    IF TRUE -- GET_LOCK('visible/clean', 1)
    THEN
		DELETE FROM visible WHERE calc_id NOT IN (
			SELECT cc.id
				FROM `cache` c
					JOIN cache_calc cc ON c.id = cc.cache_id
				WHERE c.`name` = 'visible');
                    
		-- DO RELEASE_LOCK('visible/clean');
	END IF;
	
	  -- Calculamos el stock hasta ayer
    
    CALL `cache`.stock_refresh(false);
    
	DROP TEMPORARY TABLE IF EXISTS vn2008.tmp_item;
	CREATE TEMPORARY TABLE vn2008.tmp_item
		(PRIMARY KEY (item_id))
		ENGINE = MEMORY
		SELECT item_id, amount stock, amount visible FROM `cache`.stock
			WHERE warehouse_id = v_warehouse;

	-- Calculamos los movimientos confirmados de hoy

	CALL vn2008.item_stock_visible(v_warehouse, NULL);

	DELETE FROM visible WHERE calc_id = v_calc;
    
	INSERT INTO visible (calc_id, item_id,visible)
		SELECT v_calc, item_id, visible FROM vn2008.tmp_item;

    CALL cache_calc_end (v_calc);

	DROP TEMPORARY TABLE vn2008.tmp_item;
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 `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `weekly_sales_refresh` */;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_general_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `weekly_sales_refresh`(v_refresh BOOL)
BEGIN

    DECLARE v_week_ini INT;

    DECLARE v_week_end INT;

    DECLARE v_date_ini DATE;

    DECLARE v_date_end DATE;

    DECLARE v_last_refresh DATE;



    IF GET_LOCK('weekly_sales', 300)

    THEN

        SELECT last_refresh INTO v_last_refresh FROM weekly_sales_info;



        IF v_last_refresh IS NULL THEN

            SET v_refresh = TRUE;

        END IF;



        IF v_refresh || v_last_refresh < CURDATE()

        THEN

            SET v_date_ini = TIMESTAMPADD(DAY, -(366 * 1.5), CURDATE());

            SET v_date_end = TIMESTAMPADD(DAY, -1, CURDATE());



            IF v_refresh

            THEN

                TRUNCATE TABLE weekly_sales;

            ELSE

                SET v_week_ini = vn2008.to_weeks (v_date_ini);

                SET v_date_ini = TIMESTAMPADD(DAY, -WEEKDAY(v_last_refresh) - 7, v_last_refresh);

                SET v_week_end = vn2008.to_weeks (v_date_ini);



                DELETE FROM weekly_sales

                    WHERE week < v_week_ini OR week >= v_week_end;

            END IF;



            CALL vn2008.weekly_sales_new (0, v_date_ini, v_date_end);



            INSERT INTO weekly_sales (item_id, week, warehouse_id, amount, price)

                SELECT item_id, week, warehouse_id, amount, price FROM vn2008.weekly_sales;



            DROP TEMPORARY TABLE vn2008.weekly_sales;



            TRUNCATE TABLE weekly_sales_info;

            INSERT INTO weekly_sales_info (last_refresh) VALUES (CURDATE());

        END IF;



        DO RELEASE_LOCK('weekly_sales');

    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 */ ;
ALTER DATABASE `cache` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Current Database: `vncontrol`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `vncontrol` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `vncontrol`;

--
-- Table structure for table `accion`
--

DROP TABLE IF EXISTS `accion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accion` (
  `accion_id` int(11) NOT NULL AUTO_INCREMENT,
  `accion` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`accion_id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientes_match`
--

DROP TABLE IF EXISTS `clientes_match`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientes_match` (
  `Id_cliente` int(11) NOT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `dailyTaskLog`
--

DROP TABLE IF EXISTS `dailyTaskLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dailyTaskLog` (
  `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `fallo`
--

DROP TABLE IF EXISTS `fallo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `fallo` (
  `queja_id` int(10) unsigned NOT NULL,
  `accion_id` int(11) NOT NULL,
  PRIMARY KEY (`queja_id`,`accion_id`),
  KEY `accion` (`accion_id`,`queja_id`),
  KEY `fallo` (`queja_id`),
  CONSTRAINT `accion` FOREIGN KEY (`accion_id`) REFERENCES `accion` (`accion_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `inter`
--

DROP TABLE IF EXISTS `inter`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inter` (
  `inter_id` int(11) NOT NULL AUTO_INCREMENT,
  `state_id` tinyint(3) unsigned NOT NULL,
  `fallo_id` int(10) unsigned NOT NULL DEFAULT '21',
  `nota` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `Id_Ticket` int(11) DEFAULT NULL,
  `Id_Trabajador` int(11) DEFAULT NULL,
  `Id_Supervisor` int(11) DEFAULT NULL,
  PRIMARY KEY (`inter_id`),
  KEY `currante` (`Id_Trabajador`),
  KEY `responsable` (`Id_Supervisor`),
  KEY `ticket` (`Id_Ticket`),
  KEY `inter_state` (`state_id`),
  CONSTRAINT `currante` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `inter_ibfk_1` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `inter_state` FOREIGN KEY (`state_id`) REFERENCES `vn2008`.`state` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `responsable` FOREIGN KEY (`Id_Supervisor`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=8428388 DEFAULT 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 `interBeforeInsert`
BEFORE INSERT ON `inter` FOR EACH ROW
BEGIN

	DECLARE contados INT;
	DECLARE vSupervisor INT;
    
	SELECT Id_Trabajador INTO vSupervisor FROM vn2008.Trabajadores WHERE user_id = account.userGetId();
    
    SET NEW.Id_Supervisor = IFNULL(vSupervisor,20);

	IF NEW.state_id = 5
    THEN 
		SELECT count(Id_Ticket) INTO contados
			FROM vncontrol.inter 
				WHERE state_id = 5
                AND Id_Ticket = NEW.Id_Ticket
                AND IFNULL(Id_Supervisor,-1) <> vSupervisor
                AND TIMESTAMPADD(SECOND, 60, odbc_date) >= NOW();
            
		IF contados <> 0 THEN
			CALL util.throw ('FALLO_AL_INSERTAR');
		END IF;
	END IF;
    
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_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 `vncontrol`.`interAfterInsert`
AFTER INSERT ON `inter` FOR EACH ROW
BEGIN
 REPLACE vn2008.Tickets_state(Id_Ticket, inter_id,state_name)
    SELECT NEW.Id_Ticket, NEW.inter_id, s.`name` FROM vn2008.state s WHERE s.id = NEW.state_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 SET @saved_cs_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 `vncontrol`.`interAfterUpdate`
AFTER UPDATE ON `inter` FOR EACH ROW
BEGIN
	DECLARE intIdTicket INT;
    DECLARE intInterId INT;
    DECLARE strName VARCHAR(15);
    
	IF (NEW.state_id <> OLD.state_id)  THEN
		REPLACE INTO vn2008.Tickets_state(Id_Ticket, inter_id,state_name)
			SELECT NEW.Id_Ticket, NEW.inter_id, s.`name` 
				FROM vn2008.state s WHERE s.id = NEW.state_id;
    END IF;
    IF (NEW.Id_Ticket <> OLD.Id_Ticket) THEN
	
		SELECT i.Id_Ticket, i.inter_id, s.`name`
		INTO intIdTicket, intInterId, strName 
			FROM vncontrol.inter i 
				JOIN vn2008.state s ON i.state_id = s.id 
			WHERE Id_Ticket = NEW.Id_Ticket 
			ORDER BY odbc_date DESC 
			LIMIT 1;
		IF intIdTicket > 0 THEN
			REPLACE INTO vn2008.Tickets_state(Id_Ticket, inter_id,state_name)
				VALUES(intIdTicket, intInterId, strName);
		END IF;
	END IF;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 SET @saved_cs_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 `vncontrol`.`interAfterDelete`
AFTER DELETE ON `inter` FOR EACH ROW
BEGIN
	DECLARE intIdTicket INT;
	DECLARE intInterId INT;
	DECLARE strName VARCHAR(15);

	DECLARE CONTINUE HANDLER FOR SQLSTATE '23000'
	BEGIN
		DELETE FROM vn2008.Tickets_state
			WHERE Id_Ticket = OLD.Id_Ticket;
	END;

	IF OLD.odbc_date > TIMESTAMPADD(WEEK, -1, CURDATE()) THEN
    
		SELECT i.Id_Ticket, i.inter_id, s.`name`
			INTO intIdTicket, intInterId, strName 
			FROM vncontrol.inter i 
				JOIN vn2008.state s ON i.state_id = s.id 
			WHERE Id_Ticket = OLD.Id_Ticket 
			ORDER BY odbc_date DESC 
			LIMIT 1;

		IF intIdTicket > 0 THEN
			REPLACE INTO vn2008.Tickets_state(Id_Ticket, inter_id,state_name)
				VALUES (intIdTicket, intInterId, strName);
		END IF;
        
	END IF;

END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Dumping events for database 'vncontrol'
--

--
-- Dumping routines for database 'vncontrol'
--
/*!50003 DROP PROCEDURE IF EXISTS `clean` */;
/*!50003 SET @saved_cs_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 `clean`()
BEGIN
	
	DECLARE v_date2 DATETIME DEFAULT TIMESTAMPADD(MONTH, -2,CURDATE());

    INSERT INTO vncontrol.dailyTaskLog(state) VALUES('clean START');

    DELETE FROM vncontrol.inter WHERE odbc_date <= v_date2;
        
    INSERT INTO vncontrol.dailyTaskLog(state) VALUES('clean END');
    
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 `ResumenKK` */;
/*!50003 SET @saved_cs_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 `ResumenKK`()
BEGIN

select accion, CodigoTrabajador, semana, Pedidos, Lineas
from accion
join
(   
    SELECT * FROM
    (
    select count(*) as Pedidos, semana, Id_Trabajador, accion_id
    from
        (select distinct *
            from
            (
            select vn2008.semana(odbc_date) as semana
                    ,Id_Trabajador
                    ,accion_id
                    ,Id_Ticket
            from vncontrol.inter 
            ) sub
        ) sub2
        group by semana, Id_Trabajador, accion_id
     ) subpedidos
     
     inner join
     (

        select semana, Id_Trabajador, accion_id, count(*) as Lineas 
        from vn2008.Movimientos 
        inner join 
            (
                select distinct vn2008.semana(odbc_date) as semana, Id_Ticket, Id_Trabajador, accion_id from vncontrol.inter
            ) vnc using(Id_Ticket)
        group by semana, Id_Trabajador, accion_id
        
     ) sublineas using(semana, Id_Trabajador, accion_id)
    
) sub3 using(accion_id)

join vn2008.Trabajadores using(Id_Trabajador)
;

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: `edi`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `edi` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `edi`;

--
-- Table structure for table `batch`
--

DROP TABLE IF EXISTS `batch`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `batch` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `message_id` int(10) unsigned NOT NULL,
  `type_id` smallint(5) unsigned NOT NULL,
  `buy_edi_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `type_id` (`type_id`,`buy_edi_id`),
  KEY `message_id` (`message_id`),
  KEY `buy_edi_id` (`buy_edi_id`),
  CONSTRAINT `batch_ibfk_1` FOREIGN KEY (`message_id`) REFERENCES `message` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `batch_ibfk_2` FOREIGN KEY (`buy_edi_id`) REFERENCES `vn2008`.`buy_edi` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=266998 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `batch_type`
--

DROP TABLE IF EXISTS `batch_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `batch_type` (
  `id` mediumint(8) unsigned NOT NULL,
  `description` varchar(50) COLLATE utf8_unicode_ci NOT 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 `bucket`
--

DROP TABLE IF EXISTS `bucket`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bucket` (
  `bucket_id` int(11) unsigned NOT NULL,
  `bucket_type_id` mediumint(8) unsigned NOT NULL,
  `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `x_size` mediumint(8) unsigned NOT NULL,
  `y_size` mediumint(8) unsigned NOT NULL,
  `z_size` mediumint(8) unsigned NOT NULL,
  `entry_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`bucket_id`),
  KEY `group_id` (`y_size`),
  KEY `plant_id` (`x_size`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/CK090916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `bucket_type`
--

DROP TABLE IF EXISTS `bucket_type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bucket_type` (
  `bucket_type_id` mediumint(8) unsigned NOT NULL,
  `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`bucket_type_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/VBN020101/FB090916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `config`
--

DROP TABLE IF EXISTS `config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `log_mail` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Mail where the log information is sent',
  `presale_id` mediumint(8) unsigned DEFAULT NULL,
  `default_kop` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `presale_id` (`presale_id`),
  CONSTRAINT `config_ibfk_1` FOREIGN KEY (`presale_id`) REFERENCES `batch_type` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `deliveryInformation`
--

DROP TABLE IF EXISTS `deliveryInformation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deliveryInformation` (
  `ID` int(11) NOT NULL,
  `DeliveryType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `DeliveryPrice` decimal(10,2) DEFAULT NULL,
  `ChargeAmount` decimal(10,2) DEFAULT NULL,
  `BasisQuantitiy` int(11) DEFAULT NULL,
  `MinimumQuantity` int(11) DEFAULT NULL,
  `MaximumQuantity Integer` int(11) DEFAULT NULL,
  `LatestDeliveryDateTime` datetime DEFAULT NULL,
  `EarliestDespatchDateTime` datetime DEFAULT NULL,
  `FirstOrderDateTime` datetime DEFAULT NULL,
  `LatestOrderDateTime` datetime 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 `feature`
--

DROP TABLE IF EXISTS `feature`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `feature` (
  `item_id` int(11) unsigned NOT NULL,
  `feature_type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `feature_value` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date NOT NULL,
  `expiry_date` date NOT NULL,
  `change_date_time` datetime NOT NULL,
  PRIMARY KEY (`item_id`,`feature_type_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FF130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `file_config`
--

DROP TABLE IF EXISTS `file_config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `file_config` (
  `file_name` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `to_table` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `file` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `updated` date DEFAULT NULL,
  PRIMARY KEY (`file_name`),
  UNIQUE KEY `to_table` (`to_table`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ftp_config`
--

DROP TABLE IF EXISTS `ftp_config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ftp_config` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `host` varchar(255) CHARACTER SET utf8 NOT NULL,
  `user` varchar(50) CHARACTER SET utf8 NOT NULL,
  `password` varchar(50) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `genus`
--

DROP TABLE IF EXISTS `genus`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `genus` (
  `genus_id` mediumint(8) unsigned NOT NULL,
  `latin_genus_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`genus_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FG130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `goodCharacteristic`
--

DROP TABLE IF EXISTS `goodCharacteristic`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `goodCharacteristic` (
  `supplyResponse` varchar(26) COLLATE utf8_unicode_ci NOT NULL,
  `type` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'edi.type',
  `value` varchar(3) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'edi.value',
  PRIMARY KEY (`supplyResponse`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `imap_config`
--

DROP TABLE IF EXISTS `imap_config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imap_config` (
  `id` tinyint(3) unsigned NOT NULL,
  `host` varchar(150) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'localhost',
  `user` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `pass` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `clean_period` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'How long the old mails are preserved',
  `success_folder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `error_folder` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='IMAP configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `item`
--

DROP TABLE IF EXISTS `item`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item` (
  `id` int(11) unsigned NOT NULL,
  `product_name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `plant_id` mediumint(8) unsigned DEFAULT NULL,
  `group_id` int(11) DEFAULT NULL,
  `entry_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `group_id` (`group_id`),
  KEY `plant_id` (`plant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FP130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `item_feature`
--

DROP TABLE IF EXISTS `item_feature`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_feature` (
  `item_id` int(11) NOT NULL,
  `presentation_order` tinyint(11) unsigned NOT NULL,
  `feature` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `regulation_type` tinyint(3) unsigned NOT NULL,
  `entry_date` date NOT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime NOT NULL,
  PRIMARY KEY (`item_id`,`presentation_order`,`entry_date`,`change_date_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FY130916.txt';
/*!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              = '' */ ;
DELIMITER ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `item_feature_bi` BEFORE INSERT ON `item_feature` FOR EACH ROW
BEGIN
	IF NEW.expiry_date = '0000-00-00' THEN
		SET NEW.expiry_date = NULL;
	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 `item_group`
--

DROP TABLE IF EXISTS `item_group`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_group` (
  `group_code` int(11) unsigned NOT NULL,
  `dutch_group_description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date NOT NULL,
  `expiry_date` date NOT NULL,
  `change_date_time` datetime NOT NULL,
  PRIMARY KEY (`group_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FO130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `item_track`
--

DROP TABLE IF EXISTS `item_track`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `item_track` (
  `item_id` int(10) unsigned NOT NULL,
  `s1` tinyint(3) NOT NULL DEFAULT '0',
  `s2` tinyint(3) NOT NULL DEFAULT '0',
  `s3` tinyint(3) NOT NULL DEFAULT '0',
  `s4` tinyint(3) NOT NULL DEFAULT '0',
  `pac` tinyint(3) NOT NULL DEFAULT '0',
  `cat` tinyint(3) NOT NULL DEFAULT '0',
  `ori` tinyint(3) NOT NULL DEFAULT '0',
  `pro` tinyint(3) NOT NULL DEFAULT '0',
  `package` tinyint(3) NOT NULL DEFAULT '0',
  `s5` tinyint(3) NOT NULL DEFAULT '0',
  `s6` tinyint(3) NOT NULL DEFAULT '0',
  `kop` tinyint(3) NOT NULL DEFAULT '0',
  `sub` tinyint(3) NOT NULL DEFAULT '0',
  PRIMARY KEY (`item_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mail`
--

DROP TABLE IF EXISTS `mail`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mail` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `mail` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `kop` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail` (`mail`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of allowed mailers';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `message`
--

DROP TABLE IF EXISTS `message`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `sender_id` int(10) unsigned DEFAULT NULL,
  `mail_id` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `mail_id` (`mail_id`),
  KEY `sender_id` (`sender_id`),
  CONSTRAINT `message_ibfk_2` FOREIGN KEY (`sender_id`) REFERENCES `mail` (`id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=285868 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `param`
--

DROP TABLE IF EXISTS `param`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `param` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `code` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `name` varchar(5) COLLATE utf8_unicode_ci NOT NULL,
  `subname` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `position` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `type` enum('INTEGER','DOUBLE','STRING','DATE','TIME') COLLATE utf8_unicode_ci NOT NULL,
  `required` tinyint(3) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`,`subname`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Parameters to capture of every exchange';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `plant`
--

DROP TABLE IF EXISTS `plant`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `plant` (
  `plant_id` mediumint(8) unsigned NOT NULL,
  `genus_id` mediumint(8) unsigned NOT NULL,
  `specie_id` mediumint(8) unsigned DEFAULT NULL,
  `entry_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`plant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FT130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `specie`
--

DROP TABLE IF EXISTS `specie`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `specie` (
  `specie_id` mediumint(8) unsigned NOT NULL,
  `genus_id` mediumint(8) unsigned NOT NULL,
  `latin_species_name` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date DEFAULT NULL,
  `expiry_date` date DEFAULT NULL,
  `change_date_time` datetime DEFAULT NULL,
  PRIMARY KEY (`specie_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FS130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `supplier`
--

DROP TABLE IF EXISTS `supplier`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplier` (
  `supplier_id` int(10) unsigned NOT NULL COMMENT 'FHRegistrationNr',
  `glnAddressCode` varchar(13) CHARACTER SET utf8 DEFAULT NULL,
  `company_name` varchar(70) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date NOT NULL,
  `expiry_date` date NOT NULL,
  `change_date_time` datetime NOT NULL,
  PRIMARY KEY (`supplier_id`),
  KEY `glnaddressCodeidx` (`glnAddressCode`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/FEC010104/CC090916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `supplyResponse`
--

DROP TABLE IF EXISTS `supplyResponse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `supplyResponse` (
  `ID` int(11) NOT NULL,
  `NumberBunchesPerCask` int(11) DEFAULT NULL,
  `SupplierGLN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NewItem` tinyint(1) DEFAULT NULL,
  `SendererID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ItemSupplierID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TransactionDate` datetime DEFAULT NULL,
  `TransactionNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `AuctionClockNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `SupplierID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FLA` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ItemDatesupplyResponsecol` datetime DEFAULT NULL,
  `Item_ArticleCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `VBNOmschrijving` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ExtraRemark` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ArtCodeType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `VBNGroupCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `VBNGroupDescription` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `TransactionTime` time DEFAULT NULL,
  `SupplierNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CountryOfOrigin` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `SerialNumber` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NumberOfItemsPerCask` int(11) DEFAULT NULL,
  `NumberOfLayersPerTrolley` int(11) DEFAULT NULL,
  `NumberOfUnits` int(11) DEFAULT NULL,
  `MinimumNumberToOrder` int(11) DEFAULT NULL,
  `MinimumOrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Price` decimal(10,2) DEFAULT NULL,
  `PotSize` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Height` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Length` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Weight` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Quality` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NumberOfBuds` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `NumberOfBudsPerStem` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ExaminiationCode1` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `ExaminiationCode2` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Diameter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `PlantDiameter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Potshape` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FlowerShape` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `FlowerColor` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `PotColor` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `PotMaterial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `MaterialHeight` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `MaterialDiameter` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `OtherMaterial` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `OrderUnitType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `EmbalageCode` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `PictureReference` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID_UNIQUE` (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `type`
--

DROP TABLE IF EXISTS `type`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `type` (
  `type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `type_group_id` tinyint(3) unsigned NOT NULL,
  `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date NOT NULL,
  `expiry_date` date NOT NULL,
  `change_date_time` datetime NOT NULL,
  PRIMARY KEY (`type_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FE130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `value`
--

DROP TABLE IF EXISTS `value`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `value` (
  `type_id` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `type_value` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `type_description` varchar(70) COLLATE utf8_unicode_ci NOT NULL,
  `entry_date` date NOT NULL,
  `expiry_date` date NOT NULL,
  `change_date_time` datetime NOT NULL,
  PRIMARY KEY (`type_id`,`type_value`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='/tmp/floricode/florecompc2/FV130916.txt';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'edi'
--

--
-- Dumping routines for database 'edi'
--
/*!50003 DROP PROCEDURE IF EXISTS `batchNew` */;
/*!50003 SET @saved_cs_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 `batchNew`(
	 vMessage INT
	,vItem VARCHAR(255)
	,vType MEDIUMINT
	,vDeliveryNumber BIGINT
	,vDate DATE
	,vHour TIME
	,vRef INT
	,vAgj INT
	,vCat VARCHAR(2)
	,vPac INT
	,vSub MEDIUMINT
	,vKop INT
	,vPtd VARCHAR(6)
	,vPro MEDIUMINT
	,vOrigin VARCHAR(3)
	,vPtj MEDIUMINT
	,vQuantiy INT
	,vPrice DOUBLE
	,vClock SMALLINT
	,vS1 VARCHAR(3)
	,vS2 VARCHAR(3)
	,vS3 VARCHAR(3)
	,vS4 VARCHAR(4)
	,vS5 VARCHAR(3)
	,vS6 VARCHAR(3)
	,vK1 SMALLINT
	,vK2 SMALLINT
	,vP1 TINYINT
	,vP2 TINYINT
	,vAuction SMALLINT
	,vPackage INT
)
BEGIN
/**
 * Añade un nuevo lote, genera su código de barras y
 * inserta/actualiza el registro en la tabla #vn2008.buy_edi
 */
	DECLARE vEdi INT;
	DECLARE vRewriteKop INT DEFAULT NULL;
	DECLARE vBarcode CHAR(15) DEFAULT NULL;
	DECLARE vIsDuplicated BOOLEAN DEFAULT FALSE;
	DECLARE vUpdateExistent BOOLEAN DEFAULT FALSE;

	DECLARE CONTINUE HANDLER FOR 1062 -- ER_DUP_KEY
		SET vIsDuplicated = TRUE;

	-- Genera el código de barras

	IF vAgj != 0 AND vAgj IS NOT NULL 
	THEN
		SET vBarcode = CONCAT(
			LPAD(vAuction, 2, 0),
			LPAD(IFNULL(vClock, 99), 2, 0),
			LPAD(DAYOFYEAR(vDate), 3, 0),
			IF(vClock IS NULL OR vClock = 99,
				LPAD(vAgj, 7, 0),
				CONCAT(LPAD(vAgj, 5, 0), '01')
			),
			'0'
		);
	END IF;

	-- Reescribe el parámetro kop

	IF vKop IS NULL
	THEN
		SELECT default_kop INTO vKop FROM config;
	END IF;

	SELECT e.kop INTO vRewriteKop
		FROM mail e
			JOIN message m ON m.sender_id = e.id
		WHERE m.id = vMessage;

	SET vKop = IFNULL(vRewriteKop, vKop);

	-- Inserta el nuevo EKT

	INSERT INTO vn2008.buy_edi SET
		 barcode = IFNULL(vBarcode, barcode)
		,delivery_number = vDeliveryNumber
		,entry_year = YEAR(vDate)
		,fec = vDate
		,hor = vHour
		,ref = vRef
		,item = vItem
		,agj = vAgj
		,cat = vCat
		,pac = vPac
		,sub = vSub
		,kop = vKop
		,ptd = vPtd
		,pro = vPro
		,ori = vOrigin
		,ptj = vPtj
		,qty = vQuantiy
		,pri = vPrice
		,klo = vClock
		,s1 = vS1
		,s2 = vS2
		,s3 = vS3
		,s4 = vS4
		,s5 = vS5
		,s6 = vS6
		,k01 = vK1
		,k02 = vK2
		,k03 = vP1
		,k04 = vP2
		,auction = vAuction
		,package = vPackage;


	-- Si el EKT está duplicado y el que habia en la tabla era uno
	-- provisional, lo actualiza con los nuevos valores.

	IF NOT vIsDuplicated 
	THEN
		SET vEdi = LAST_INSERT_ID();
		CALL ediLoad (vEdi);

	ELSEIF vDeliveryNumber != 0
	AND vDeliveryNumber IS NOT NULL
	THEN
		SELECT id INTO vEdi
			FROM vn2008.buy_edi
			WHERE delivery_number = vDeliveryNumber;

		SELECT COUNT(*) = 0 INTO vUpdateExistent
			FROM vn2008.buy_edi e
				JOIN batch b ON b.buy_edi_id = e.id
				JOIN config c
			WHERE e.delivery_number = vDeliveryNumber
				AND b.type_id != c.presale_id;
	END IF;

	IF vUpdateExistent
	THEN
		UPDATE vn2008.buy_edi SET
			 barcode = IFNULL(vBarcode, barcode)
			,fec = vDate
			,hor = vHour
			,ref = vRef
			,item = vItem
			,agj = vAgj
			,cat = vCat
			,pac = vPac
			,sub = vSub
			,kop = vKop
			,ptd = vPtd
			,pro = vPro
			,ori = vOrigin
			,ptj = vPtj
			,qty = vQuantiy
			,pri = vPrice
			,klo = vClock
			,s1 = vS1
			,s2 = vS2
			,s3 = vS3
			,s4 = vS4
			,s5 = vS5
			,s6 = vS6
			,k01 = vK1
			,k02 = vK2
			,k03 = vP1
			,k04 = vP2
			,auction = vAuction
			,package = vPackage
		WHERE id = vEdi;
	END IF;

	-- Registra el lote

	INSERT INTO batch SET
		 message_id = vMessage
		,type_id = vType
		,buy_edi_id = vEdi;
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 `ediLoad` */;
/*!50003 SET @saved_cs_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 `ediLoad`(vEdi INT)
BEGIN
	DECLARE vRef INT;
	DECLARE vBuy INT;
	DECLARE vItem INT;
	DECLARE vQty INT;
	DECLARE vPackage INT;
	DECLARE vIsLot BOOLEAN;

	-- Carga los datos necesarios del EKT

	SELECT ref, qty, package INTO vRef, vQty, vPackage
		FROM vn2008.buy_edi e
			LEFT JOIN item i ON e.ref = i.id
		WHERE e.id = vEdi;

	-- Inserta el cubo si no existe

	IF vPackage = 800 
	THEN
		SET vPackage = 800 + vQty;

		INSERT IGNORE INTO vn2008.Cubos SET
			Id_Cubo = vPackage,
			x = 7200 / vQty,
			y = 1;
	ELSE
		INSERT IGNORE INTO vn2008.Cubos (Id_Cubo, X, Y, Z)
			SELECT bucket_id, ROUND(x_size/10), ROUND(y_size/10), ROUND(z_size/10)
				FROM bucket WHERE bucket_id = vPackage;
		
		IF ROW_COUNT() > 0
		THEN
			INSERT INTO vn2008.mail SET
				`subject` = 'Cubo añadido',
				`text` = CONCAT('Se ha añadido el cubo: ', vPackage),
				`to` = 'ekt@verdnatura.es';
		END IF;
	END IF;

	-- Intenta obtener el artículo en base a los atributos holandeses

	INSERT IGNORE INTO item_track SET
		item_id = vRef;

	SELECT c.Id_Compra, c.Id_Article INTO vBuy, vItem
		FROM vn2008.buy_edi e 
			JOIN item_track t ON t.item_id = e.ref
			LEFT JOIN vn2008.buy_edi l ON l.ref = e.ref
			LEFT JOIN vn2008.Compres c ON c.buy_edi_id = l.id
			JOIN vn2008.config cfg
		WHERE e.id = vEdi
			AND l.id != vEdi
			AND c.Id_Article != cfg.generic_item
			AND IF(t.s1, l.s1 = e.s1, TRUE)
			AND IF(t.s2, l.s2 = e.s2, TRUE)
			AND IF(t.s3, l.s3 = e.s3, TRUE)
			AND IF(t.s4, l.s4 = e.s4, TRUE)
			AND IF(t.s5, l.s5 = e.s5, TRUE)
			AND IF(t.s6, l.s6 = e.s6, TRUE)
			AND IF(t.kop, l.kop = e.kop, TRUE)
			AND IF(t.pac, l.pac = e.pac, TRUE)
			AND IF(t.cat, l.cat = e.cat, TRUE)
			AND IF(t.ori, l.ori = e.ori, TRUE)
			AND IF(t.pro, l.pro = e.pro, TRUE)
			AND IF(t.sub, l.sub = e.sub, TRUE)
			AND IF(t.package, l.package = e.package, TRUE)
			AND c.Id_Article < 170000
		ORDER BY l.now DESC, c.Id_Compra ASC LIMIT 1;

	-- Determina si el articulo se vende por lotes

	IF vItem
	THEN
		SELECT COUNT(*) > 0 INTO vIsLot
			FROM vn2008.Articles a
				LEFT JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
			WHERE a.Id_Article = vItem
				AND t.`transaction`;

		-- Si el articulo se vende por lotes se inserta un nuevo artículo

		IF vIsLot
		THEN
			INSERT INTO vn2008.Articles (
				 Article
				,Medida
				,Categoria
				,Id_Origen
				,iva_group_id
				,Foto
				,Color
				,Codintrastat
				,tipo_id
				,Tallos
			)
			SELECT
				 i.`name`
				,IFNULL(e.s1, e.pac)
				,e.cat
				,IFNULL(o.id, 17)
				,IFNULL(a.iva_group_id, 1)
				,a.Foto
				,a.Color
				,a.Codintrastat
				,IFNULL(a.tipo_id, 10)
				,IF(a.tipo_id = 15, 0, 1)
				FROM vn2008.buy_edi e
					LEFT JOIN item i ON i.id = e.ref
					LEFT JOIN vn2008.Origen o ON o.Abreviatura = e.ori
					LEFT JOIN vn2008.Articles a ON a.Id_Article = vItem
				WHERE e.id = vEdi;
					
			SET vItem = LAST_INSERT_ID();
		END IF;
	END IF;

	-- Inserta la compra asociada al EKT

	INSERT INTO vn2008.Compres
	(
		 Id_Entrada
		,buy_edi_id
		,Costefijo
		,Id_Article
		,grouping
		,caja
		,Packing
		,Cantidad
		,Productor
		,Etiquetas
		,Id_Cubo
	)
	SELECT
		 cfg.edi_entry
		,vEdi
		,(@t := IF(a.Tallos, a.Tallos, 1)) * e.pri
		,IFNULL(vItem, cfg.generic_item)
		,IFNULL(c.grouping, e.pac)
		,IFNULL(c.caja, TRUE)
		,@pac := e.pac / @t
		,@pac * e.qty
		,s.company_name
		,e.qty
		,IFNULL(c.Id_Cubo, e.package)
		FROM vn2008.buy_edi e 
			LEFT JOIN vn2008.Compres c ON c.Id_Compra = vBuy
			LEFT JOIN vn2008.Articles a ON a.Id_Article = c.Id_Article
			LEFT JOIN supplier s ON e.pro = s.supplier_id
			JOIN vn2008.config cfg
		WHERE e.id = vEdi
		LIMIT 1;
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 `messageNew` */;
/*!50003 SET @saved_cs_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 `messageNew`(
	 vMailId VARCHAR(100)
	,vSender VARCHAR(150)
    ,OUT vMessageId INT
)
BEGIN
/**
 * Registra un correo electronico.
 *
 * @param vMailId Message-ID del correo electrónico
 * @param vSender Id del correo electrónio del remitente
 */
	DECLARE vSenderId INT;

	SELECT id INTO vSenderId FROM mail
		WHERE mail = vSender;

	INSERT IGNORE INTO message SET
		 sender_id = vSenderId
		,mail_id = vMailId;
		
	SET vMessageId = LAST_INSERT_ID();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Current Database: `bi`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bi` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `bi`;

--
-- Table structure for table `Equalizator`
--

DROP TABLE IF EXISTS `Equalizator`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Equalizator` (
  `Vista` int(11) NOT NULL,
  `Pedido` int(11) DEFAULT NULL,
  `Impreso` int(11) DEFAULT NULL,
  `Encajado` int(11) DEFAULT NULL,
  PRIMARY KEY (`Vista`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Greuge_Evolution`
--

DROP TABLE IF EXISTS `Greuge_Evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Greuge_Evolution` (
  `Id_Cliente` int(11) NOT NULL,
  `Fecha` date NOT NULL,
  `Greuge` decimal(10,2) NOT NULL DEFAULT '0.00',
  `Ventas` decimal(10,2) NOT NULL DEFAULT '0.00',
  `Fosil` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'greuge fósil, correspondiente a los clientes muertos',
  `Recobro` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`Id_Cliente`,`Fecha`),
  KEY `greuge_evolution_idx1` (`Fecha`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacenamos la evolucion del greuge de los ultimos dias ';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Greuge_comercial_recobro`
--

DROP TABLE IF EXISTS `Greuge_comercial_recobro`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Greuge_comercial_recobro` (
  `Id_Trabajador` int(11) NOT NULL,
  `recobro` decimal(10,2) NOT NULL DEFAULT '0.00',
  `peso_cartera` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`Id_Trabajador`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Greuges_comercial_detail`
--

DROP TABLE IF EXISTS `Greuges_comercial_detail`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Greuges_comercial_detail` (
  `Id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `Id_Trabajador` int(10) unsigned NOT NULL,
  `Comentario` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Importe` decimal(10,2) NOT NULL,
  `Fecha` datetime DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci ROW_FORMAT=FIXED;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Last_buy_id`
--

DROP TABLE IF EXISTS `Last_buy_id`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Last_buy_id` (
  `Id_Article` int(11) NOT NULL DEFAULT '90',
  `Id_Compra` int(11) NOT NULL DEFAULT '0',
  `warehouse_id` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`warehouse_id`,`Id_Article`),
  UNIQUE KEY `Id_Compra_UNIQUE` (`Id_Compra`),
  CONSTRAINT `Id_CompraFK` FOREIGN KEY (`Id_Compra`) REFERENCES `vn2008`.`Compres` (`Id_Compra`) 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 `Last_buy_idBackUp`
--

DROP TABLE IF EXISTS `Last_buy_idBackUp`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Last_buy_idBackUp` (
  `Id_Article` int(11) NOT NULL DEFAULT '90',
  `Id_Compra` int(11) NOT NULL DEFAULT '0',
  `warehouse_id` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`Id_Article`,`warehouse_id`),
  UNIQUE KEY `Id_Compra_UNIQUE` (`Id_Compra`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Radar`
--

DROP TABLE IF EXISTS `Radar`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Radar` (
  `Propio` int(1) NOT NULL DEFAULT '0',
  `Credito` double NOT NULL DEFAULT '0',
  `Riesgo` double(19,2) DEFAULT NULL,
  `Greuge` double DEFAULT NULL,
  `Id_Ticket` int(11) NOT NULL DEFAULT '0',
  `wh` smallint(6) unsigned NOT NULL DEFAULT '1',
  `Fecha` datetime NOT NULL,
  `Alias` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Vista` int(11) DEFAULT '0',
  `Tipo` varchar(50) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'RECOGIDA',
  `Id_Trabajador` int(11) DEFAULT '20',
  `Solucion` varchar(5) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Localizacion` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Estado` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `Fecha_Simple` date DEFAULT NULL,
  `Id_Comercial` int(11) DEFAULT '20',
  `Risk` double NOT NULL DEFAULT '0',
  `Rojo` bigint(21) DEFAULT '0',
  `Naranja` bigint(21) DEFAULT '0',
  `Amarillo` bigint(21) DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Ticket_Portes`
--

DROP TABLE IF EXISTS `Ticket_Portes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Ticket_Portes` (
  `Id_Ticket` int(11) NOT NULL,
  `rate` tinyint(4) NOT NULL COMMENT 'Tarifa',
  `real_amount` double NOT NULL COMMENT 'Cantidad pactada con la agencia',
  `payed_amount` double NOT NULL COMMENT 'Cantidad reflejada en el Ticket',
  PRIMARY KEY (`Id_Ticket`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `VelocityKK`
--

DROP TABLE IF EXISTS `VelocityKK`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `VelocityKK` (
  `tipo_id` int(11) NOT NULL,
  `Fecha` datetime NOT NULL,
  `Disponible` int(11) DEFAULT NULL,
  `Visible` int(11) DEFAULT NULL,
  `velocity_id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`velocity_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `XDiario_ALL`
--

DROP TABLE IF EXISTS `XDiario_ALL`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `XDiario_ALL` (
  `empresa_id` int(5) NOT NULL,
  `SUBCTA` varchar(11) COLLATE utf8_unicode_ci NOT NULL,
  `Eurodebe` double DEFAULT NULL,
  `Eurohaber` double DEFAULT NULL,
  `Fecha` date DEFAULT NULL,
  `FECHA_EX` date DEFAULT NULL,
  KEY `Cuenta` (`SUBCTA`),
  KEY `empresa` (`empresa_id`),
  KEY `Fecha` (`Fecha`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_grafico_simple`
--

DROP TABLE IF EXISTS `analisis_grafico_simple`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_grafico_simple` (
  `Año` smallint(5) unsigned NOT NULL,
  `Semana` tinyint(3) unsigned NOT NULL,
  `Importe` double DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `analisis_grafico_ventas`
--

DROP TABLE IF EXISTS `analisis_grafico_ventas`;
/*!50001 DROP VIEW IF EXISTS `analisis_grafico_ventas`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `analisis_grafico_ventas` AS SELECT 
 1 AS `Año`,
 1 AS `Semana`,
 1 AS `Importe`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `analisis_ventas`
--

DROP TABLE IF EXISTS `analisis_ventas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas` (
  `Familia` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `Reino` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `Comercial` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `Provincia` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `almacen` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `Año` smallint(5) unsigned NOT NULL,
  `Mes` tinyint(3) unsigned NOT NULL,
  `Semana` tinyint(3) unsigned NOT NULL,
  `Vista` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Importe` double NOT NULL,
  KEY `Año` (`Año`,`Semana`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_ventas_almacen_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_almacen_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_almacen_evolution` (
  `Semana` int(11) NOT NULL,
  `Almacen` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `Ventas` int(11) NOT NULL,
  `Año` int(11) NOT NULL,
  `Periodo` int(11) NOT NULL,
  KEY `Almacen` (`Almacen`,`Periodo`),
  KEY `Periodo` (`Periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_ventas_comprador_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_comprador_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_comprador_evolution` (
  `semana` int(11) NOT NULL,
  `comprador` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `ventas` int(11) NOT NULL,
  `año` int(11) NOT NULL,
  `periodo` int(11) NOT NULL,
  UNIQUE KEY `comprador` (`comprador`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_ventas_familia_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_familia_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_familia_evolution` (
  `semana` int(11) NOT NULL,
  `familia` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `ventas` int(11) NOT NULL,
  `año` int(11) NOT NULL,
  `periodo` int(11) NOT NULL,
  KEY `familia` (`familia`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_ventas_provincia_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_provincia_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_provincia_evolution` (
  `semana` int(11) NOT NULL,
  `provincia` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `ventas` int(11) NOT NULL,
  `año` int(11) NOT NULL,
  `periodo` int(11) NOT NULL,
  UNIQUE KEY `provincia` (`provincia`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_ventas_reino_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_reino_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_reino_evolution` (
  `semana` int(11) NOT NULL,
  `reino` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `ventas` int(11) NOT NULL,
  `año` int(11) NOT NULL,
  `periodo` int(11) NOT NULL,
  UNIQUE KEY `reino` (`reino`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `analisis_ventas_simple`
--

DROP TABLE IF EXISTS `analisis_ventas_simple`;
/*!50001 DROP VIEW IF EXISTS `analisis_ventas_simple`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `analisis_ventas_simple` AS SELECT 
 1 AS `Año`,
 1 AS `Semana`,
 1 AS `Importe`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `analisis_ventas_vendedor_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_vendedor_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_vendedor_evolution` (
  `semana` int(11) NOT NULL,
  `vendedor` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `ventas` int(11) NOT NULL,
  `año` int(11) NOT NULL,
  `periodo` int(11) NOT NULL,
  UNIQUE KEY `vendedor` (`vendedor`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `analisis_ventas_vista_evolution`
--

DROP TABLE IF EXISTS `analisis_ventas_vista_evolution`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `analisis_ventas_vista_evolution` (
  `semana` int(11) NOT NULL,
  `vista` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `ventas` int(11) NOT NULL,
  `año` int(11) NOT NULL,
  `periodo` int(11) NOT NULL,
  UNIQUE KEY `vista` (`vista`,`periodo`),
  KEY `periodo` (`periodo`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calidad_detalle`
--

DROP TABLE IF EXISTS `calidad_detalle`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calidad_detalle` (
  `Id_Cliente` int(11) NOT NULL,
  `calidad_parametros_id` int(2) NOT NULL,
  `valor` int(3) DEFAULT NULL,
  PRIMARY KEY (`Id_Cliente`,`calidad_parametros_id`),
  KEY `calidad_parametros_detalle_idx` (`calidad_parametros_id`),
  CONSTRAINT `calidad_parametros_detalle` FOREIGN KEY (`calidad_parametros_id`) REFERENCES `calidad_parametros` (`calidad_parametros_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calidad_parametros`
--

DROP TABLE IF EXISTS `calidad_parametros`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calidad_parametros` (
  `calidad_parametros_id` int(2) NOT NULL,
  `descripcion` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`calidad_parametros_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `claims_ratio`
--

DROP TABLE IF EXISTS `claims_ratio`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `claims_ratio` (
  `Id_Cliente` int(11) NOT NULL DEFAULT '0',
  `Consumo` decimal(10,2) DEFAULT NULL,
  `Reclamaciones` decimal(10,2) DEFAULT NULL,
  `Ratio` decimal(5,2) DEFAULT NULL,
  `recobro` decimal(5,2) DEFAULT NULL,
  `inflacion` decimal(5,2) NOT NULL DEFAULT '1.00',
  PRIMARY KEY (`Id_Cliente`),
  CONSTRAINT `claims_ratio_ibfk_1` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) 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 `comparativa_clientes`
--

DROP TABLE IF EXISTS `comparativa_clientes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `comparativa_clientes` (
  `Fecha` date NOT NULL DEFAULT '0000-00-00',
  `Id_Cliente` int(11) NOT NULL DEFAULT '0',
  `Propietario` int(11) DEFAULT NULL,
  `titular` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `suplente` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  `trabajador` int(11) DEFAULT NULL,
  `actual` double DEFAULT NULL,
  `pasado` double DEFAULT NULL,
  `concepto` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '',
  KEY `cc_data_indez` (`Fecha`),
  KEY `cc_Id_Cliente_index` (`Id_Cliente`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `customerDebtInventory`
--

DROP TABLE IF EXISTS `customerDebtInventory`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `customerDebtInventory` (
  `Id_Cliente` int(11) NOT NULL,
  `Debt` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT 'CREATE TABLE bi.customerDebtInventory\n\nSELECT Id_Cliente, sum(Euros) as Debt\n\nFROM \n(\nSELECT Id_Cliente, Entregado as Euros\n\nFROM Recibos \n\nWHERE Fechacobro < ''2017-01-01\n''\nUNION ALL\n\nSELECT Id_Cliente,  - Importe \nFROM Facturas\nWHERE Fecha < ''2017-01-01''\n) sub \nGROUP BY Id_Cliente',
  PRIMARY KEY (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `customerRiskOverdue`
--

DROP TABLE IF EXISTS `customerRiskOverdue`;
/*!50001 DROP VIEW IF EXISTS `customerRiskOverdue`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `customerRiskOverdue` AS SELECT 
 1 AS `customer_id`,
 1 AS `amount`,
 1 AS `company_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `customer_risk`
--

DROP TABLE IF EXISTS `customer_risk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `customer_risk` (
  `customer_id` int(11) NOT NULL DEFAULT '0',
  `company_id` smallint(6) unsigned NOT NULL DEFAULT '0',
  `amount` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`customer_id`,`company_id`),
  KEY `company_id` (`company_id`),
  CONSTRAINT `customer_risk_ibfk_1` FOREIGN KEY (`customer_id`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `customer_risk_ibfk_2` FOREIGN KEY (`company_id`) REFERENCES `vn2008`.`empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Saldo de apertura < 2015-01-01';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `dailyTaskLog`
--

DROP TABLE IF EXISTS `dailyTaskLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `dailyTaskLog` (
  `state` varchar(250) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='No he encontrado el lugar en el que vicente almacena la hora en que se ejecutan las daily tasks, asi que he hecho esta tabla, a eliminar cuando se considere oportuno';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `defaulters`
--

DROP TABLE IF EXISTS `defaulters`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `defaulters` (
  `client` int(11) NOT NULL,
  `date` date NOT NULL,
  `amount` double NOT NULL DEFAULT '0',
  `defaulterSince` date DEFAULT NULL,
  `hasChanged` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`client`,`date`),
  KEY `client` (`client`),
  KEY `date` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `defaulting`
--

DROP TABLE IF EXISTS `defaulting`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `defaulting` (
  `date` date NOT NULL,
  `amount` double NOT NULL,
  PRIMARY KEY (`date`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `f_tvc`
--

DROP TABLE IF EXISTS `f_tvc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `f_tvc` (
  `Id_Ticket` int(11) NOT NULL,
  PRIMARY KEY (`Id_Ticket`),
  CONSTRAINT `id_ticket_to_comisionantes` FOREIGN KEY (`Id_Ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacenamos la lista de tickets para agilizar la consulta. Corresponde a los clientes REAL y en los almacenes COMISIONANTES';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `facturacion_media_anual`
--

DROP TABLE IF EXISTS `facturacion_media_anual`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `facturacion_media_anual` (
  `Id_Cliente` int(11) NOT NULL,
  `Consumo` double(17,0) DEFAULT NULL,
  PRIMARY KEY (`Id_Cliente`),
  CONSTRAINT `fmaId_Cliente` FOREIGN KEY (`Id_Cliente`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `last_Id_Cubo`
--

DROP TABLE IF EXISTS `last_Id_Cubo`;
/*!50001 DROP VIEW IF EXISTS `last_Id_Cubo`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `last_Id_Cubo` AS SELECT 
 1 AS `Id_Compra`,
 1 AS `Id_Article`,
 1 AS `warehouse_id`,
 1 AS `Id_Cubo`,
 1 AS `Packing`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `lastaction`
--

DROP TABLE IF EXISTS `lastaction`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `lastaction` (
  `Id_Cliente` int(11) unsigned NOT NULL,
  `Cliente` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `Ultima_accion` date DEFAULT NULL,
  `Comercial` varchar(3) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `live_counter`
--

DROP TABLE IF EXISTS `live_counter`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `live_counter` (
  `odbc_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `amount` double NOT NULL,
  PRIMARY KEY (`odbc_date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mana_inventory_kk`
--

DROP TABLE IF EXISTS `mana_inventory_kk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mana_inventory_kk` (
  `Id_Trabajador` int(11) NOT NULL,
  `mana` double NOT NULL DEFAULT '0',
  `dated` date NOT NULL,
  PRIMARY KEY (`Id_Trabajador`,`dated`),
  CONSTRAINT `fk_trabajador_mana_inventory` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) 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 `movimientos_log`
--

DROP TABLE IF EXISTS `movimientos_log`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `movimientos_log` (
  `idmovimientos_log` int(11) NOT NULL AUTO_INCREMENT,
  `Id_Movimiento` int(11) NOT NULL,
  `odbc_date` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `Id_Trabajador` int(11) NOT NULL,
  `field_name` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `new_value` double DEFAULT NULL,
  PRIMARY KEY (`idmovimientos_log`)
) ENGINE=InnoDB AUTO_INCREMENT=13371133 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `partitioning_information`
--

DROP TABLE IF EXISTS `partitioning_information`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `partitioning_information` (
  `schema_name` varchar(10) CHARACTER SET utf8 NOT NULL,
  `table_name` varchar(20) CHARACTER SET utf8 NOT NULL,
  `date_field` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  `table_depending` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `execution_order` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`schema_name`,`table_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `primer_pedido`
--

DROP TABLE IF EXISTS `primer_pedido`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `primer_pedido` (
  `Id_Cliente` int(11) NOT NULL,
  `Id_Ticket` int(11) NOT NULL,
  `month` tinyint(1) NOT NULL,
  `year` smallint(2) NOT NULL,
  `total` decimal(10,2) NOT NULL DEFAULT '0.00',
  PRIMARY KEY (`Id_Cliente`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `rotacion`
--

DROP TABLE IF EXISTS `rotacion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `rotacion` (
  `Id_Article` int(11) NOT NULL,
  `warehouse_id` smallint(6) unsigned NOT NULL,
  `total` int(10) NOT NULL DEFAULT '0',
  `rotacion` decimal(10,4) NOT NULL DEFAULT '0.0000',
  `cm3` int(11) NOT NULL DEFAULT '0',
  `almacenaje` decimal(10,4) NOT NULL DEFAULT '0.0000',
  `manipulacion` decimal(10,4) NOT NULL DEFAULT '0.0000',
  `auxiliar` decimal(10,4) NOT NULL DEFAULT '0.0000',
  `mermas` decimal(10,4) NOT NULL DEFAULT '0.0000',
  PRIMARY KEY (`Id_Article`,`warehouse_id`),
  KEY `id_article_rotacion_idx` (`Id_Article`),
  KEY `warehouse_id_rotacion_idx` (`warehouse_id`),
  CONSTRAINT `id_article_rotaci` FOREIGN KEY (`Id_Article`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `warehouse_id_rotaci` FOREIGN KEY (`warehouse_id`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de rotacion en los ultimos 365 dias';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `saldos_bancos`
--

DROP TABLE IF EXISTS `saldos_bancos`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saldos_bancos` (
  `Semana` int(2) NOT NULL,
  `Mes` int(2) NOT NULL,
  `Año` int(4) NOT NULL,
  `Entrada` double DEFAULT NULL,
  `Salida` decimal(32,2) DEFAULT NULL,
  `Saldo` double DEFAULT NULL,
  `Id_Banco` int(11) NOT NULL DEFAULT '0',
  `empresa_id` int(5) unsigned NOT NULL DEFAULT '0',
  `Empresa` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT ''
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `saldos_bancos_pordia`
--

DROP TABLE IF EXISTS `saldos_bancos_pordia`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `saldos_bancos_pordia` (
  `Fecha` date NOT NULL,
  `Entrada` double DEFAULT NULL,
  `Salida` decimal(32,2) DEFAULT NULL,
  `Saldo` double DEFAULT NULL,
  `Id_Banco` int(11) NOT NULL DEFAULT '0',
  `empresa_id` int(5) unsigned NOT NULL DEFAULT '0',
  `Empresa` varchar(3) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `Año` int(4) NOT NULL,
  `Mes` int(2) NOT NULL,
  `Dia` int(2) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sales`
--

DROP TABLE IF EXISTS `sales`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sales` (
  `Id_Trabajador` int(10) unsigned NOT NULL,
  `year` int(10) unsigned NOT NULL,
  `month` int(10) unsigned NOT NULL,
  `weight` int(11) NOT NULL DEFAULT '0',
  `boss_aid` int(10) NOT NULL DEFAULT '0',
  `boss_id` int(10) NOT NULL DEFAULT '0',
  `comision` int(11) DEFAULT NULL,
  PRIMARY KEY (`Id_Trabajador`,`year`,`month`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tarifa_componentes`
--

DROP TABLE IF EXISTS `tarifa_componentes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tarifa_componentes` (
  `Id_Componente` int(11) NOT NULL AUTO_INCREMENT,
  `Componente` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `tarifa_componentes_series_id` int(11) NOT NULL,
  `tarifa_class` smallint(6) DEFAULT NULL,
  `tax` double DEFAULT NULL,
  `is_renewable` tinyint(2) NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id_Componente`),
  KEY `series_componentes_idx` (`tarifa_componentes_series_id`),
  KEY `comp` (`tarifa_class`),
  CONSTRAINT `serie_componente` FOREIGN KEY (`tarifa_componentes_series_id`) REFERENCES `tarifa_componentes_series` (`tarifa_componentes_series_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=42 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tarifa_componentes_series`
--

DROP TABLE IF EXISTS `tarifa_componentes_series`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tarifa_componentes_series` (
  `tarifa_componentes_series_id` int(11) NOT NULL AUTO_INCREMENT,
  `Serie` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `base` tinyint(4) NOT NULL DEFAULT '0' COMMENT 'Marca aquellas series que se utilizan para calcular el precio base de las ventas, a efectos estadisticos',
  `margen` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`tarifa_componentes_series_id`),
  UNIQUE KEY `Serie_UNIQUE` (`Serie`)
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Permite organizar de forma ordenada los distintos componentes';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tarifa_premisas`
--

DROP TABLE IF EXISTS `tarifa_premisas`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tarifa_premisas` (
  `Id_Premisa` int(11) NOT NULL AUTO_INCREMENT,
  `premisa` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`Id_Premisa`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tarifa_warehouse`
--

DROP TABLE IF EXISTS `tarifa_warehouse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tarifa_warehouse` (
  `Id_Tarifa_Warehouse` int(11) NOT NULL AUTO_INCREMENT,
  `warehouse_id` int(11) NOT NULL,
  `Id_Premisa` int(11) NOT NULL,
  `Valor` double NOT NULL,
  PRIMARY KEY (`Id_Tarifa_Warehouse`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena los valores de gasto por almacen';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `v_clientes_jerarquia`
--

DROP TABLE IF EXISTS `v_clientes_jerarquia`;
/*!50001 DROP VIEW IF EXISTS `v_clientes_jerarquia`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_clientes_jerarquia` AS SELECT 
 1 AS `Id_Cliente`,
 1 AS `Cliente`,
 1 AS `Comercial`,
 1 AS `Jefe`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `v_ventas_contables`
--

DROP TABLE IF EXISTS `v_ventas_contables`;
/*!50001 DROP VIEW IF EXISTS `v_ventas_contables`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_ventas_contables` AS SELECT 
 1 AS `year`,
 1 AS `month`,
 1 AS `importe`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `variablesKK`
--

DROP TABLE IF EXISTS `variablesKK`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `variablesKK` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `variable` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `value` double DEFAULT NULL,
  `date` datetime DEFAULT NULL,
  `text` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'bi'
--

--
-- Dumping routines for database 'bi'
--
/*!50003 DROP FUNCTION IF EXISTS `nz` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `nz`(dblCANTIDAD DOUBLE) RETURNS double
BEGIN

DECLARE dblRESULT  DOUBLE;

SET dblRESULT = IFNULL(dblCANTIDAD,0);

RETURN dblRESULT;

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 `analisis_ventas_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 `analisis_ventas_evolution_add`()
BEGIN
	DECLARE vPreviousPeriod INT;
	DECLARE vCurrentPeriod INT;
    DECLARE vLastPeriod INT;
    DECLARE vMinPeriod INT DEFAULT 201400;
    DECLARE vMaxPeriod INT DEFAULT vn2008.vnperiod(CURDATE());

	DECLARE vYear INT;
	DECLARE vWeek INT;

	-- Almacen

	SET vCurrentPeriod = IFNULL(vLastPeriod, vMinPeriod);

	WHILE vCurrentPeriod < vMaxPeriod
    DO
		SELECT MAX(Periodo) INTO vPreviousPeriod
			FROM bi.analisis_ventas_almacen_evolution
			WHERE Periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);

		DELETE FROM bi.analisis_ventas_almacen_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_almacen_evolution(Almacen, Ventas, Semana,Año, Periodo)
			SELECT  Almacen, sum(Ventas) AS Ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT almacen, sum(Importe) AS Ventas
						FROM bi.analisis_ventas
						WHERE vYear = Año 
						AND vWeek = Semana
						GROUP BY almacen
					UNION ALL
					SELECT almacen, - sum(Importe) AS Ventas
						FROM bi.analisis_ventas
						WHERE vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY almacen
					UNION ALL
					SELECT Almacen, Ventas
						FROM bi.analisis_ventas_almacen_evolution
						WHERE Periodo = vPreviousPeriod
				) sub
				GROUP BY Almacen;
	END WHILE;

	-- Reino

	SET vCurrentPeriod = vMinPeriod;

	WHILE vCurrentPeriod < vMaxPeriod
    DO
		SELECT MAX(periodo) INTO vPreviousPeriod
			FROM bi.analisis_ventas_reino_evolution
			WHERE periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);

		DELETE FROM bi.analisis_ventas_reino_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_reino_evolution(reino, ventas, semana,año, periodo)
			SELECT  reino, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Reino, sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear = Año 
						AND vWeek = Semana
						GROUP BY Reino
					UNION ALL
					SELECT Reino, - sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY Reino
					UNION ALL
					SELECT reino, ventas
						FROM bi.analisis_ventas_reino_evolution
						WHERE Periodo = vPreviousPeriod
				) sub
				GROUP BY reino;
	END WHILE;

	-- Familia

	SET vCurrentPeriod = vMinPeriod;

	WHILE vCurrentPeriod < vMaxPeriod
    DO
		SELECT MAX(periodo) INTO vPreviousPeriod
			FROM bi.analisis_ventas_familia_evolution
			WHERE periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);

		DELETE FROM bi.analisis_ventas_familia_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_familia_evolution(familia, ventas, semana,año, periodo)
			SELECT  Familia, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Familia, sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear = Año 
						AND vWeek = Semana
						GROUP BY familia
					UNION ALL
					SELECT Familia, - sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY familia
					UNION ALL
					SELECT familia, ventas
						FROM bi.analisis_ventas_familia_evolution
						WHERE Periodo = vPreviousPeriod
					) sub
				GROUP BY Familia;
	END WHILE;

	-- Comprador
	-- FIXME: Bucle infinito porque la tabla está vacía
/*
	SET vCurrentPeriod = vMinPeriod;

	WHILE vCurrentPeriod < vMaxPeriod
    DO
		SELECT IFNULL(MAX(periodo),vMinPeriod) INTO vPreviousPeriod
			FROM bi.analisis_ventas_comprador_evolution
			WHERE periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);

		DELETE FROM bi.analisis_ventas_comprador_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_comprador_evolution(comprador, ventas, semana,año, periodo)
			SELECT  Comprador, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Comprador, sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear = Año 
						AND vWeek = Semana
						GROUP BY Comprador
					UNION ALL
					SELECT Comprador, - sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY Comprador
					UNION ALL
					SELECT comprador, IFNULL(ventas,0)
						FROM bi.analisis_ventas_comprador_evolution
						WHERE Periodo = vPreviousPeriod
					) sub
				GROUP BY Comprador;
	END WHILE;
*/
	-- Provincia

	SET vCurrentPeriod = vMinPeriod;

	WHILE vCurrentPeriod < vMaxPeriod
    DO	
		SELECT MAX(periodo) INTO vPreviousPeriod
			FROM bi.analisis_ventas_provincia_evolution
			WHERE periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);

		DELETE FROM bi.analisis_ventas_provincia_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_provincia_evolution(provincia, ventas, semana,año, periodo)
			SELECT  Provincia, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Provincia, sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear = Año 
						AND vWeek = Semana
						GROUP BY Provincia
					UNION ALL
					SELECT Provincia, - sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY Provincia
					UNION ALL
					SELECT provincia, ventas
						FROM bi.analisis_ventas_provincia_evolution
						WHERE Periodo = vPreviousPeriod
					) sub
				GROUP BY Provincia;
	END WHILE;

	-- Vista

	SET vCurrentPeriod = vMinPeriod;

	WHILE vCurrentPeriod < vMaxPeriod
    DO
		SELECT MAX(periodo) INTO vPreviousPeriod
			FROM bi.analisis_ventas_vista_evolution
			WHERE periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);

		DELETE FROM bi.analisis_ventas_vista_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_vista_evolution(vista, ventas, semana,año, periodo)
			SELECT  vista, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Vista, sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE  vYear = Año 
						AND vWeek = Semana
						GROUP BY Vista
					UNION ALL
					SELECT Vista, - sum(Importe) AS ventas
						FROM bi.analisis_ventas
						WHERE  vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY Vista
					UNION ALL
					SELECT vista, ventas
						FROM bi.analisis_ventas_vista_evolution
						WHERE Periodo = vPreviousPeriod
				) sub
				GROUP BY Vista;
	END WHILE;

	-- Vendedor

	SET vCurrentPeriod = vMinPeriod;

	WHILE vCurrentPeriod < vMaxPeriod
    DO
		SELECT MAX(periodo) INTO vPreviousPeriod
			FROM bi.analisis_ventas_vendedor_evolution
			WHERE periodo < vMaxPeriod;

		SELECT MIN(period) INTO vCurrentPeriod
			FROM vn2008.time
			WHERE period > vPreviousPeriod;

		SET vYear = FLOOR(vCurrentPeriod / 100);
		SET vWeek = vCurrentPeriod - (vYear * 100);
		
		DELETE FROM bi.analisis_ventas_vendedor_evolution
			WHERE Periodo = vCurrentPeriod;

		REPLACE bi.analisis_ventas_vendedor_evolution(vendedor, ventas, semana,año, periodo)
			SELECT  Comercial AS vendedor, sum(ventas) AS ventas, vWeek, vYear, vCurrentPeriod
				FROM (
					SELECT Comercial, sum(Importe) AS ventas
						from bi.analisis_ventas
						WHERE  vYear = Año 
						AND vWeek = Semana
						GROUP BY Comercial
					UNION ALL
					SELECT Comercial, - sum(Importe) AS ventas
						from bi.analisis_ventas
						WHERE  vYear - 1 = Año 
						AND vWeek = Semana
						GROUP BY Comercial
					UNION ALL
					SELECT vendedor, ventas
						FROM bi.analisis_ventas_vendedor_evolution
						WHERE Periodo = vPreviousPeriod
				) sub
				GROUP BY vendedor;
	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 `analisis_ventas_simple` */;
/*!50003 SET @saved_cs_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 `analisis_ventas_simple`()
BEGIN

TRUNCATE bi.analisis_grafico_simple;

INSERT INTO bi.analisis_grafico_simple SELECT * FROM bi.analisis_grafico_ventas;

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 `analisis_ventas_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 `analisis_ventas_update`()
BEGIN

	DECLARE vLastMonth DATE;

	SET vLastMonth = util.firstDayOfMonth(TIMESTAMPADD(MONTH, -1, CURDATE()));

	DELETE FROM bi.analisis_ventas
		WHERE Año > YEAR(vLastMonth)
			OR (Año = YEAR(vLastMonth) AND Mes >= MONTH(vLastMonth));

	INSERT INTO bi.analisis_ventas

		SELECT 
			`tp`.`Tipo` AS `Familia`,
			`r`.`reino` AS `Reino`,
			`tr`.`CodigoTrabajador` AS `Comercial`,
			`tr2`.`CodigoTrabajador` AS `Comprador`,
			`p`.`name` AS `Provincia`,
			`w`.`name` AS `almacen`,
			`time`.`year` AS `Año`,
			`time`.`month` AS `Mes`,
			`time`.`week` AS `Semana`,
			`v`.`vista` AS `Vista`,
			`bt`.`importe` AS `Importe`
		FROM
				(((((((((`bs`.`ventas` `bt`
				LEFT JOIN `vn2008`.`Tipos` `tp` ON ((`tp`.`tipo_id` = `bt`.`tipo_id`)))
				LEFT JOIN `vn2008`.`reinos` `r` ON ((`r`.`id` = `tp`.`reino_id`)))
				LEFT JOIN `vn2008`.`Clientes` c on c.Id_Cliente = bt.Id_Cliente
				LEFT JOIN `vn2008`.`Trabajadores` `tr` ON ((`tr`.`Id_Trabajador` = `c`.`Id_Trabajador`)))
				LEFT JOIN `vn2008`.`Trabajadores` `tr2` ON ((`tr2`.`Id_Trabajador` = `tp`.`Id_Trabajador`)))
				JOIN vn2008.time on time.date = bt.fecha
				JOIN vn2008.Movimientos m on m.Id_Movimiento = bt.Id_Movimiento
				LEFT JOIN `vn2008`.`Tickets` `t` ON ((`t`.`Id_Ticket` = `m`.`Id_Ticket`)))
				JOIN vn2008.Agencias a on a.Id_Agencia = t.Id_Agencia
				LEFT JOIN `vn2008`.`Vistas` `v` ON ((`v`.`vista_id` = `a`.`Vista`)))
				LEFT JOIN `vn2008`.`Consignatarios` `cs` ON ((`cs`.`Id_Consigna` = `t`.`Id_Consigna`)))
				LEFT JOIN `vn2008`.`province` `p` ON ((`p`.`province_id` = `cs`.`province_id`)))
				LEFT JOIN `vn2008`.`warehouse` `w` ON ((`w`.`id` = `t`.`warehouse_id`)))
			WHERE bt.fecha >= vLastMonth AND r.mercancia;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `call_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 `call_add`()
BEGIN

DECLARE datSTART DATETIME DEFAULT '2012-03-01'/*CURDATE()*/;
-- control
INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.call_add');

-- Seleccionamos la ultima fecha introducida
SELECT MAX(Fecha) INTO datSTART FROM `call`;


-- Borramos todas las entradas del dia datSTART por si hubiese registros nuevos 
DELETE FROM `call` WHERE Fecha = datSTART;

INSERT INTO bi.`call`(CodTrabajadorCartera,CodTrabajadorTelefono,dur_in,dur_out,Fecha,`year`,`month`,`week`,`hour`,phone)
SELECT vn2008.Averiguar_ComercialCliente(pb.Id_Cliente,Fecha) CodTrabajadorCartera,ll.CodigoTrabajador,  dur_in, 
 dur_out, ll.Fecha,YEAR(ll.Fecha) `year`, MONTH(ll.Fecha) `month`,WEEK(ll.Fecha,7) `week`, Hora,phone
FROM
(
SELECT Id_Trabajador,CodigoTrabajador, IFNULL(billsec,0) dur_in, 0 dur_out, 1 as Recibidas, NULL as Emitidas, calldate as Fecha, 
    hour(calldate) as Hora,src as phone
FROM vn2008.Trabajadores T
INNER JOIN vn2008.cdr C ON C.dstchannel LIKE CONCAT('%', T.extension, '%')
WHERE calldate >= datSTART AND LENGTH(C.src) >=9 AND disposition = 'ANSWERED' AND duration
UNION ALL
SELECT Id_Trabajador,CodigoTrabajador,0 dur_in, IFNULL(billsec,0)  dur_out, NULL as Recibidas, 1 as Emitidas, date(calldate), hour(calldate),dst
FROM vn2008.Trabajadores T
INNER JOIN vn2008.cdr C ON C.src = T.extension
WHERE calldate >= datSTART AND LENGTH(C.dst) >=9 AND disposition = 'ANSWERED' AND duration
) ll
INNER JOIN vn2008.Permisos USING(Id_Trabajador)
LEFT JOIN vn2008.v_phonebook pb ON pb.Telefono = ll.phone
WHERE Id_Grupo = 6;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!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 `claim_ratio_routine` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = 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 `claim_ratio_routine`()
BEGIN

DECLARE vMonthToRefund INT DEFAULT 4;

-- control
INSERT INTO vn2008.daily_task_log(consulta) 
        VALUES('bi.claim_ratio_routine START');

/* 
*	PAK 2015-11-20
*   Se trata de añadir a la tabla Greuges todos los 
*   cargos que luego vamos a utilizar para calcular el recobro
*/

-- descuentos comerciales COD 11

INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario, Importe, Id_Ticket)
    SELECT Fecha, Id_Cliente, Concat('COD11 : ',Concepte), - round(Cantidad * 
            Preu * (100 - Descuento) / 100 ,2) AS Importe, t.Id_Ticket
        FROM vn2008.Tickets t
            JOIN vn2008.Movimientos m ON m.Id_Ticket = t.Id_Ticket
        WHERE Id_Article = 11
            AND Concepte NOT LIKE '$%'
            AND Fecha > '2014-01-01'
        HAVING nz(Importe) <> 0;

DELETE mc.* 
	    FROM vn2008.Movimientos_componentes mc
		    JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
		    JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
	    WHERE m.Id_Article = 11
		    AND m.Concepte NOT LIKE '$%'
    		AND t.Fecha > '2017-01-01';
        
INSERT INTO vn2008.Movimientos_componentes(Id_Movimiento, Id_Componente, Valor)
	SELECT m.Id_Movimiento, 34, round(m.Preu * (100 - m.Descuento)/100,4)
		FROM vn2008.Movimientos m 
	    	JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
	    WHERE m.Id_Article = 11
		    AND m.Concepte NOT LIKE '$%'
		    AND t.Fecha > '2017-01-01';

UPDATE vn2008.Movimientos m
            JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket 
        SET Concepte = CONCAT('$ ',Concepte)
        WHERE Id_Article = 11
            AND Concepte NOT LIKE '$%'
            AND Fecha > '2014-01-01';

-- Reclamaciones demasiado sensibles

INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario,
                 Importe, Greuges_type_id,Id_Ticket)
    SELECT cm.Fecha
         , cm.Id_Cliente
         , concat('Claim ',cm.id,' : ', m.Concepte)
         ,round( -1 * ((sensib -1)/4) * Cantidad * 
            Preu * (100 - Descuento) / 100, 2) AS Reclamaciones
         , 4
         , m.Id_Ticket
        FROM vn2008.Movimientos m
            JOIN vn2008.cl_act ca USING(Id_Movimiento)
            JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
        WHERE ca.cl_sol_id  NOT IN (1,5)
            AND ca.greuge = 0
             AND cm.cl_est_id = 3;
  
  -- Reclamaciones que pasan a Maná
  
INSERT INTO vn2008.Greuges(Fecha, Id_Cliente, Comentario,
                Importe , Greuges_type_id,Id_Ticket)
    SELECT cm.Fecha
        , cm.Id_Cliente
        , concat('Claim_mana ',cm.id,' : ', m.Concepte)
        ,round( ((sensib -1)/4) * Cantidad * Preu * (100 - Descuento) / 100, 2) 
            AS Reclamaciones
        ,3
        ,m.Id_Ticket
        FROM vn2008.Movimientos m
            JOIN vn2008.cl_act ca USING(Id_Movimiento)
            JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
        WHERE ca.cl_sol_id  NOT IN (1,5)
            AND ca.greuge = 0
            AND cm.cl_est_id = 3
            AND cm.mana;
  
  -- Marcamos para no repetir
UPDATE vn2008.cl_act ca
            JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
        SET greuge = 1 
        WHERE ca.cl_sol_id  NOT IN (1,5)
            AND ca.greuge = 0
            AND cm.cl_est_id = 3;



-- Recobros

DROP TEMPORARY TABLE IF EXISTS tmp.ticket_list;
CREATE TEMPORARY TABLE tmp.ticket_list
(PRIMARY KEY (Id_Ticket))
SELECT DISTINCT t.Id_Ticket
        FROM vn2008.Movimientos_componentes mc
            JOIN vn2008.Movimientos m ON mc.Id_Movimiento = m.Id_Movimiento
            JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket 
            JOIN vn2008.Tickets_state ts ON ts.Id_Ticket = t.Id_Ticket
            JOIN vncontrol.inter i ON i.inter_id = ts.inter_id
            JOIN vn2008.state s ON s.id = i.state_id
        WHERE mc.Id_Componente = 17
            AND mc.greuge = 0
            AND t.Fecha >= '2016-10-01'
            AND t.Fecha < CURDATE()
            AND t.warehouse_id <> 41
            AND s.alert_level >= 3;

DELETE g.*
        FROM vn2008.Greuges g
            JOIN tmp.ticket_list t ON g.Id_Ticket = t.Id_Ticket
        WHERE Greuges_type_id = 2;

INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, 
                            Greuges_type_id, Id_Ticket)
    SELECT Id_Cliente
            ,concat('recobro ', m.Id_Ticket), - round(SUM(mc.Valor*Cantidad),2) 
                AS dif
            ,date(t.Fecha)
            , 2
            ,tt.Id_Ticket
        FROM vn2008.Movimientos m 
            JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket 
            JOIN tmp.ticket_list tt ON tt.Id_Ticket = t.Id_Ticket
            JOIN vn2008.Movimientos_componentes mc 
                ON mc.Id_Movimiento = m.Id_Movimiento AND mc.Id_Componente = 17
        GROUP BY t.Id_Ticket
            HAVING ABS(dif) > 1;

UPDATE vn2008.Movimientos_componentes mc
            JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
            JOIN tmp.ticket_list tt ON tt.Id_Ticket = m.Id_Ticket
        SET greuge = 1
        WHERE Id_Componente = 17;

/*
* Recalculamos la ratio de las reclamaciones, que luego 
* se va a utilizar en el recobro
*/

DELETE FROM bi.claims_ratio;

REPLACE bi.claims_ratio(Id_Cliente, Consumo, Reclamaciones, Ratio, recobro)
    SELECT fm.Id_Cliente, 12 * fm.Consumo, Reclamaciones, 
            round(Reclamaciones / (12*fm.Consumo),4) AS Ratio, 0
        FROM bi.facturacion_media_anual fm
            LEFT JOIN(
                SELECT cm.Id_Cliente, round(sum(-1 * ((sensib -1)/4) * 
                        Cantidad * Preu * (100 - Descuento) / 100)) 
                        AS Reclamaciones
                    FROM vn2008.Movimientos m
                        JOIN vn2008.cl_act ca  
                            ON ca.Id_Movimiento = m.Id_Movimiento
                        JOIN vn2008.cl_main cm ON cm.id = ca.cl_main_id
                    WHERE ca.cl_sol_id  NOT IN (1,5)
                        AND cm.cl_est_id = 3
                        AND cm.Fecha >= TIMESTAMPADD(YEAR, -1, CURDATE())
                    GROUP BY cm.Id_Cliente
                    ) claims ON claims.Id_Cliente = fm.Id_Cliente;


-- Calculamos el porcentaje del recobro para añadirlo al precio de venta
UPDATE bi.claims_ratio cr
            JOIN (
	            SELECT Id_Cliente, nz(SUM(Importe)) AS Greuge
			        FROM vn2008.Greuges
                    WHERE Fecha <= CURDATE()
			        GROUP BY Id_Cliente
                ) g ON g.Id_Cliente = cr.Id_Cliente                
        SET recobro = GREATEST(0,round(nz(Greuge) / 
            (nz(Consumo) * vMonthToRefund / 12 ) ,3)); 

-- control
INSERT INTO vn2008.daily_task_log(consulta) 
        VALUES('bi.claim_ratio_routine END');
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 `clean` */;
/*!50003 SET @saved_cs_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 `clean`()
BEGIN
DECLARE vDateShort DATETIME;
DECLARE vDateLong DATETIME;

SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE());

INSERT INTO bi.dailyTaskLog(state) VALUES('clean START');

DELETE FROM bi.comparativa_clientes WHERE Fecha < vDateLong;
DELETE FROM bi.Greuge_Evolution WHERE Fecha < vDateShort AND weekday(Fecha) != 1;

INSERT INTO bi.dailyTaskLog(state) VALUES('clean END');
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 `clean_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 `clean_launcher`()
BEGIN

	call vn2008.clean(0);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `comparativa_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 `comparativa_add`()
BEGIN
    DECLARE lastCOMP INT;  # Se trata de una variable para almacenar el ultimo valor del Periodo

    SELECT MAX(Periodo) INTO lastCOMP FROM vn2008.Comparativa;
    -- Fijaremos las ventas con más de un mes de antiguedad en la tabla Comparativa

    IF lastCOMP < vn2008.vnperiod(CURDATE())- 3 AND vn2008.vnweek(CURDATE()) > 3 THEN
    
		REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price)
			SELECT tm.period as Periodo, m.Id_Article, t.warehouse_id, sum(m.Cantidad), sum(v.importe)
            FROM bs.ventas v
            JOIN vn2008.time tm ON tm.date = v.fecha
            JOIN vn2008.Movimientos m ON m.Id_Movimiento = v.Id_Movimiento
            JOIN vn2008.Articles a ON a.Id_Article = m.Id_Article
            JOIN vn2008.Tipos tp ON tp.tipo_id = a.tipo_id
            JOIN vn2008.reinos r ON r.id = tp.reino_id
            JOIN vn2008.Tickets t ON t.Id_Ticket = m.Id_Ticket
            WHERE tm.period BETWEEN lastCOMP AND vn2008.vnperiod(CURDATE())- 3
            AND t.Id_Cliente NOT IN(400,200)
            AND r.display <> 0
            AND t.warehouse_id NOT IN (0,13)		
            GROUP BY Id_Article, Periodo,  warehouse_id;
            
		
/*
        REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price)
			SELECT vn2008.vnperiod(T.Fecha) AS Periodo
				 , Id_Article
				 , warehouse_id
				 , SUM(Cantidad) AS Total
				 , SUM(Cantidad * Preu * (100 - Descuento) / 100) precio
					FROM vn2008.Movimientos M			
					JOIN vn2008.Tickets T USING (Id_Ticket)			
					JOIN vn2008.Articles A USING (Id_Article)	
					LEFT JOIN vn2008.Tipos ti ON ti.tipo_id = A.tipo_id
                    LEFT JOIN vn2008.reinos r ON r.id = ti.reino_id
					WHERE T.Fecha BETWEEN TIMESTAMPADD(DAY,-60,CURDATE()) AND TIMESTAMPADD(DAY,-30,CURDATE())
					AND T.Id_Cliente NOT IN(400,200)
					AND display <> 0 AND warehouse_id NOT IN (0,13)			
					GROUP BY Id_Article, Periodo,  warehouse_id;
*/

    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 `comparativa_add_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 `comparativa_add_manual`(IN dat_START DATE, IN dat_END DATE)
BEGIN

        DECLARE datINI DATETIME;
        DECLARE datFIN DATETIME;
		
        -- Seleccionamos la fecha minima/maxima del periodo que vamos a consultar
        SELECT MIN(`date`) INTO datINI FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_START);
        SELECT TIMESTAMP(MAX(`date`),'23:59:59') INTO datFIN FROM vn2008.`time` WHERE period = vn2008.vnperiod(dat_END);
        
		DELETE FROM vn2008.Comparativa WHERE Periodo BETWEEN vn2008.vnperiod(dat_START) and vn2008.vnperiod(dat_END);

        REPLACE vn2008.Comparativa(Periodo, Id_Article, warehouse_id, Cantidad,price)
			SELECT tm.period AS Periodo
				 , M.Id_Article
				 , t.warehouse_id
				 , SUM(Cantidad) AS Total
				 , sum(v.importe) AS precio
					FROM vn2008.Movimientos M
                    JOIN vn2008.Tickets t on t.Id_Ticket = M.Id_Ticket
                    JOIN bs.ventas v on v.Id_Movimiento = M.Id_Movimiento
                    JOIN vn2008.time tm on tm.date = v.fecha
					JOIN vn2008.Tipos tp on v.tipo_id = tp.tipo_id
					LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
					WHERE v.fecha BETWEEN datINI and datFIN
					AND r.display <> 0 AND t.warehouse_id NOT IN (0,13)			
					GROUP BY Id_Article, Periodo,  t.warehouse_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 `customer_risk_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 `customer_risk_update`(v_customer INT, v_company INT, v_amount DECIMAL(10,2))
BEGIN
	IF v_amount IS NOT NULL
	THEN
		INSERT INTO bi.customer_risk
			SET
				customer_id = v_customer,
				company_id = v_company,
				amount = v_amount
			ON DUPLICATE KEY UPDATE
				amount = amount + VALUES(amount);
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `defaultersFromDate` */;
/*!50003 SET @saved_cs_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 `defaultersFromDate`(IN vDate DATE)
BEGIN

SELECT t1.*, c.Cliente, w.workerCode, c.pay_met_id,c.Vencimiento
FROM (
-- Filtramos aquellos clientes cuyo saldo se ha incrementado de ayer a hoy
	select * from(
		select today.client, today.amount todayAmount, yesterday.amount yesterdayAmount, round(yesterday.amount - today.amount,2) as difference, defaulterSince
		from
			(select client, amount, defaulterSince
			from defaulters
			where date = vDate and hasChanged) today
		join
			 (select client, amount
			 from defaulters
			 where date = TIMESTAMPADD(DAY,-1,vDate)) yesterday using(client)
		
		having today.amount > 0 and difference <> 0
	) newDefaulters
)t1 left join vn2008.Clientes c ON t1.client = c.Id_Cliente
	left join vn.worker w ON w.id = c.Id_Trabajador;
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 `defaulting` */;
/*!50003 SET @saved_cs_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 `defaulting`(IN vDate DATE)
BEGIN
	DECLARE vDone BOOLEAN;
    DECLARE vClient INT;
    DECLARE vAmount INT;
    DECLARE vDateInvoice DATE;
    DECLARE vAmountInvoice DECIMAL(10,2);
    DECLARE vDueDay INT;
    DECLARE vGraceDays INT;
	DECLARE defaulters CURSOR FOR
		SELECT client, amount, Vencimiento, graceDays FROM bi.defaulters d 
				JOIN vn2008.Clientes c ON c.Id_Cliente = d.client
                JOIN vn2008.pay_met pm ON pm.id = c.pay_met_id
                WHERE hasChanged AND date = vDate;
        
	DECLARE invoices CURSOR FOR
		SELECT Fecha, importe FROM vn2008.Facturas f 
			WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC;
        
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	-- Control

	INSERT INTO vn2008.daily_task_log(consulta) VALUES('defaulting');

	DELETE FROM bi.defaulters WHERE date = vDate;

	INSERT INTO bi.defaulters(client, date, amount)
	SELECT customer_id,	vDate, FLOOR(SUM(amount)) AS amount
	FROM bi.customerRiskOverdue
	GROUP BY customer_id;
    
	-- marcamos si ha cambiado y heredamos la fecha defaulterSince
	UPDATE bi.defaulters d
	JOIN (
			SELECT * FROM(
			SELECT client, amount , defaulterSince FROM bi.defaulters
			WHERE date <= TIMESTAMPADD(DAY,-1, vDate)
			ORDER BY date DESC) t GROUP BY client
		  ) yesterday using(client)
	SET d.hasChanged = IF(d.amount <> yesterday.amount, 1, 0),
		d.defaulterSince = yesterday.defaulterSince
	WHERE d.date = vDate ;

    OPEN defaulters;
	defaulters: LOOP
		SET vDone = FALSE;
        SET vAmount = 0;
		FETCH defaulters INTO vClient,vAmount, vDueDay, vGraceDays;
		IF vDone THEN
			LEAVE defaulters;
		END IF;
		OPEN invoices;
		invoices:LOOP
			
			FETCH invoices INTO vDateInvoice, vAmountInvoice;
			IF vDone THEN
				LEAVE invoices;
			END IF;
			
			IF TIMESTAMPADD(DAY, vGraceDays, vn2008.paymentday(vDateInvoice, vDueDay))  <= vDate THEN
				SET vAmount = vAmount - vAmountInvoice;
				IF vAmount <= 0 THEN
					UPDATE defaulters SET defaulterSince = vn2008.paymentday(vDateInvoice, vDueDay)
						WHERE client = vClient and date = vDate;
						
					SET vAmount = 0;
					LEAVE invoices;
				END IF;
			END IF;
		END LOOP;
		CLOSE invoices;     
	END LOOP;
		CLOSE defaulters;
	DELETE FROM bi.defaulting WHERE date = vDate;

	INSERT INTO bi.defaulting(date, amount)
	SELECT vDate, SUM(amount)
	FROM bi.defaulters
	WHERE date = vDate and amount > 0;
    
    CALL vn.clientFreeze();
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 `defaultingkk` */;
/*!50003 SET @saved_cs_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 `defaultingkk`(IN vDate DATE)
BEGIN
	DECLARE done BIT DEFAULT 0;
    DECLARE vClient INT;
    DECLARE vAmount INT;
    DECLARE vDateInvoice DATE;
    DECLARE vAmountInvoice DECIMAL(10,2);
    DECLARE vDueDay INT;
    DECLARE vGraceDays INT;
	DECLARE defaulters CURSOR FOR
		SELECT client, amount, Vencimiento, graceDays FROM bi.defaulters d 
				JOIN vn2008.Clientes c ON c.Id_Cliente = d.client
                JOIN vn2008.pay_met pm ON pm.id = c.pay_met_id
                WHERE hasChanged AND date = vDate;
        
	DECLARE invoices CURSOR FOR
		SELECT Fecha, importe FROM vn2008.Facturas f 
			WHERE f.Fecha >= '2016-01-01' AND f.Id_Cliente = vClient ORDER BY f.Fecha DESC;
        
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
	-- Control

	INSERT INTO vn2008.daily_task_log(consulta) VALUES('defaulting');

	DELETE FROM bi.defaulters WHERE date = vDate;

	INSERT INTO bi.defaulters(client, date, amount)
	SELECT customer_id,	vDate, FLOOR(SUM(amount)) AS amount
	FROM bi.customerRiskOverdue
	GROUP BY customer_id;
    
	-- marcamos si ha cambiado y heredamos la fecha defaulterSince
	UPDATE bi.defaulters d
	JOIN (
			SELECT client, amount , defaulterSince FROM bi.defaulters
			WHERE date = TIMESTAMPADD(DAY,-1, vDate)
			GROUP BY client
		  ) yesterday using(client)
	SET d.hasChanged = IF(d.amount <> yesterday.amount, 1, 0),
		d.defaulterSince = yesterday.defaulterSince
	WHERE d.date = vDate ;

    OPEN defaulters;
		defaulters: BEGIN
		REPEAT
			FETCH defaulters INTO vClient,vAmount, vDueDay, vGraceDays;
			OPEN invoices;
				invoices:BEGIN
				REPEAT
                
					FETCH invoices INTO vDateInvoice, vAmountInvoice;
						IF TIMESTAMPADD(DAY, vGraceDays, vn2008.paymentday(vDateInvoice, vDueDay))  <= vDate THEN
							SET vAmount = vAmount - vAmountInvoice;
							IF vAmount < 0 THEN
								UPDATE defaulters SET defaulterSince = vn2008.paymentday(vDateInvoice, vDueDay)
									WHERE client = vClient and date = vDate;
								SET vAmount = 0;
								LEAVE invoices;
							END IF;
						END IF;
				UNTIL done END REPEAT;
				END invoices;
				CLOSE invoices;     
			UNTIL done OR vClient IS NULL END REPEAT;
		END defaulters;
		CLOSE defaulters;
	DELETE FROM bi.defaulting WHERE date = vDate;

	INSERT INTO bi.defaulting(date, amount)
	SELECT vDate, SUM(amount)
	FROM bi.defaulters
	WHERE date = vDate and amount > 0;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `defaulting_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 `defaulting_launcher`()
BEGIN

	CALL bi.defaulting(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 `equaliza` */;
/*!50003 SET @saved_cs_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 `equaliza`(IN wh_id INT)
BEGIN

DECLARE datEQ DATETIME;
/*  JGF 2017-03-20 cuelga el sistema

SELECT  `date` INTO datEQ FROM bi.variables WHERE variable = IF(wh_id = 17,'eq_mcf','equalizator');


IF TIMEDIFF(now(), datEQ) > '00:05:00' THEN

		UPDATE bi.Equalizator e
		JOIN
		(
		SELECT 
			Vista,
			sum(1) as pedido,
			sum(PedidoImpreso) as impreso,
			sum(t.Factura IS NOT NULL
				    OR t.Etiquetasemitidas
				    OR nz(ticket_id) <> 0) as encajado
		FROM
			vn2008.Movimientos
				JOIN
			vn2008.Tickets t USING (Id_Ticket)
				JOIN
			vn2008.Agencias a ON t.Id_Agencia = a.Id_Agencia
				JOIN
			vn2008.Clientes C USING (Id_Cliente)
				LEFT JOIN
			(SELECT distinct
				ticket_id
			FROM
				vn2008.expeditions e JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id WHERE Fecha >= curDate()) exp ON ticket_id = Id_Ticket
		WHERE
			invoice And Fecha >= curDate()
				AND t.warehouse_id = wh_id
				AND fecha < (TIMESTAMPADD(DAY, 1, CURDATE()))
		GROUP BY Vista) sub using(Vista)
		SET e.Pedido = sub.pedido, e.Impreso = sub.impreso, e.Encajado = sub.encajado;

		UPDATE bi.variables SET `date`= now() WHERE variable = IF(wh_id = 17,'eq_mcf','equalizator');
		

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 `facturacion_media_anual_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 `facturacion_media_anual_update`()
BEGIN

-- control
INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.facturacion_media_anual_update');

TRUNCATE TABLE bi.facturacion_media_anual;

REPLACE bi.facturacion_media_anual(Id_Cliente, Consumo)
select Id_Cliente, avg(Consumo)
from (
     Select Id_Cliente, YEAR(fecha) year, MONTH(fecha) month, sum(importe) as Consumo
     from bs.ventas
     where fecha >= TIMESTAMPADD(YEAR,-1,CURDATE())
     group by Id_Cliente, year, month
) vol  
group by Id_Cliente;

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 `greuge_dif_porte_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 `greuge_dif_porte_add`()
BEGIN

DECLARE datSTART DATETIME DEFAULT TIMESTAMPADD(DAY,-10,CURDATE());
DECLARE datEND DATETIME DEFAULT TIMESTAMPADD(DAY,-1,CURDATE());


DROP TEMPORARY TABLE IF EXISTS tmp.dp;

CREATE TEMPORARY TABLE tmp.dp
	(PRIMARY KEY (Id_Ticket))
    ENGINE = MEMORY
     SELECT 
        t.Id_Ticket,
        SUM(az.price * IF(
								e.EsBulto = 71
								AND ISNULL(e.Id_Article)
								AND a.Vista = 2,
								0.75,
								1
							)
			) AS teorico,
            00000.00 as practico,
            00000.00 as greuge
    FROM
        vn2008.Tickets t
        JOIN vn2008.Clientes cli ON cli.Id_cliente = t.Id_Cliente
        LEFT JOIN vn2008.expeditions e ON e.ticket_id = t.Id_Ticket
        JOIN vn2008.Consignatarios c ON c.Id_Consigna = t.Id_Consigna
        JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
        JOIN vn2008.Agencias_province ap ON t.warehouse_id = ap.warehouse_id
            AND ap.province_id = c.province_id
            AND ap.agency_id = a.agency_id
        JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = t.Id_Agencia
            AND az.zona = ap.zona
            AND t.warehouse_id = az.warehouse_id
            AND az.Id_Article = e.EsBulto
    WHERE
        t.Fecha between datSTART AND datEND
            AND cli.`real`
            AND t.empresa_id IN (442 , 567)
    GROUP BY t.Id_Ticket;

DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux;

CREATE TEMPORARY TABLE tmp.dp_aux
	(PRIMARY KEY (Id_Ticket))
    ENGINE = MEMORY
	SELECT t.Id_Ticket, sum(freight) as porte
	FROM tmp.dp
	JOIN vn2008.Tickets t ON t.Id_Ticket = dp.Id_Ticket
	JOIN vn2008.Rutas r on r.Id_Ruta = t.Id_Ruta
	JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
	JOIN (
		SELECT 
			M.Id_Ticket,
			(M.Cantidad * r.cm3 / cb.Volumen ) * az.price  AS freight
		FROM
			vn2008.Movimientos M
			JOIN vn2008.Tickets t ON t.Id_Ticket = M.Id_Ticket
			JOIN vn2008.Consignatarios c ON c.Id_Consigna = t.Id_Consigna
			JOIN bi.rotacion r  ON M.Id_Article = r.Id_Article
				AND t.warehouse_id = r.warehouse_id
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
			JOIN vn2008.Agencias_province ap ON t.warehouse_id = ap.warehouse_id
				AND ap.province_id = c.province_id
				AND ap.agency_id = a.agency_id
			JOIN vn2008.Agencias_zonas az ON az.Id_Agencia = t.Id_Agencia
				AND az.zona = ap.zona
				AND t.warehouse_id = az.warehouse_id
				AND az.Id_Article = 71
			JOIN vn2008.Cubos cb ON Id_Cubo = 94
		WHERE t.Fecha between datSTART AND datEND
		) vmv ON vmv.Id_Ticket = t.Id_Ticket
	WHERE a.is_volumetric
	GROUP BY t.Id_Ticket;

  UPDATE tmp.dp
	JOIN tmp.dp_aux using(Id_Ticket)
	SET teorico = porte;

DROP TEMPORARY TABLE IF EXISTS tmp.dp_aux;

CREATE TEMPORARY TABLE tmp.dp_aux
	(PRIMARY KEY (Id_Ticket))
    ENGINE = MEMORY
	SELECT dp.Id_Ticket, sum(Cantidad * Valor) as valor
	FROM tmp.dp
	JOIN vn2008.Movimientos m using(Id_Ticket)
	JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento)
	WHERE mc.Id_Componente = 15
	GROUP BY m.Id_Ticket;

UPDATE tmp.dp
	JOIN tmp.dp_aux using(Id_Ticket)
	SET practico = valor;

DROP TEMPORARY TABLE tmp.dp_aux;

CREATE TEMPORARY TABLE tmp.dp_aux
	(PRIMARY KEY (Id_Ticket))
    ENGINE = MEMORY
	SELECT dp.Id_Ticket, sum(Importe) Importe
		FROM tmp.dp
		JOIN vn2008.Greuges g using(Id_Ticket)
			WHERE Greuges_type_id = 1
            GROUP BY Id_Ticket;

UPDATE tmp.dp
	JOIN tmp.dp_aux using(Id_Ticket)
	SET greuge = Importe;


INSERT INTO vn2008.Greuges (Id_Cliente,Comentario,Importe,Fecha, Greuges_type_id, Id_Ticket)
SELECT t.Id_Cliente
      , concat('dif_porte ', dp.Id_Ticket)
      , round(teorico - practico - greuge,2) as Importe
      , date(t.Fecha)
      , 1
      ,t.Id_Ticket
	FROM tmp.dp
    JOIN vn2008.Tickets t on dp.Id_Ticket = t.Id_Ticket
    WHERE ABS(teorico - practico - greuge) > 1;




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 `Greuge_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 `Greuge_Evolution_Add`()
BEGIN

	/*

	Inserta en la tabla Greuge_Evolution el saldo acumulado de cada cliente, así como las ventas acumuladas en los ultimos 365 dias
	, para poder controlar su evolucion

	*/
 
	DECLARE datFEC DATE;
	DECLARE datFEC_TOMORROW DATE;
	DECLARE datFEC_LASTYEAR DATE;
   
    DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN 
  	
		GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
		SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'));
		INSERT INTO vn2008.mail (`to`,`subject`,`text`)  VALUES ('jgallego@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')));
		INSERT INTO vn2008.mail (`to`,`subject`,`text`)  VALUES ('pako@verdnatura.es', 'Greuge_Evolution_Add' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')));
		
	END;
  
	SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;
        
    INSERT INTO vn2008.daily_task_log(consulta) VALUES('Greuge Evolution Add START');

	SELECT 	TIMESTAMPADD(DAY,1,MAX(Fecha)),
			TIMESTAMPADD(DAY,2,MAX(Fecha))
		INTO 	datFEC,
				datFEC_TOMORROW
		FROM bi.Greuge_Evolution;

	SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC);

	DELETE FROM bi.Greuge_Evolution WHERE Fecha >= datFEC;
    
	DROP TEMPORARY TABLE IF EXISTS maxInvoice;
    
	CREATE TEMPORARY TABLE maxInvoice
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT DISTINCT Id_Cliente, max(Fecha) as maxFecha
			   FROM vn2008.Facturas
			   GROUP BY Id_Cliente
			   HAVING maxFecha < timestampadd(month,-2,datFEC);
               
	INSERT INTO vn2008.daily_task_log(consulta) VALUES('Greuge Evolution Add MIDDLE');	
    
	WHILE datFEC < CURDATE() DO

		REPLACE bi.Greuge_Evolution(Id_Cliente, Fecha, Greuge, Ventas)

		SELECT Id_Cliente, datFEC as Fecha, Greuge, Ventas
		
		FROM
		
		(
			SELECT Id_Cliente, sum(Importe) as Greuge
			FROM vn2008.Greuges
			where Fecha <= datFEC
			group by Id_Cliente
			
		) sub
		
		RIGHT JOIN
		
			(
			
				SELECT Id_Cliente, sum(Ventas) as Ventas
				FROM
				(
				
					SELECT Id_Cliente, IF (fecha != datFEC, -1,1) * (importe + recargo) as Ventas
					FROM bs.ventas
					WHERE fecha = datFEC or fecha = datFEC_LASTYEAR
					
					UNION ALL
					
					SELECT Id_Cliente, Ventas
					FROM bi.Greuge_Evolution
					WHERE Fecha = TIMESTAMPADD(DAY, -1, datFEC)
					
				) sub
				group by Id_Cliente
				
			) v using(Id_Cliente) 
		;
		
		
		-- Ahora calcularemos el greuge muerto
		
		-- 
		UPDATE bi.Greuge_Evolution ge 
			JOIN maxInvoice m using(Id_Cliente)
		SET FOSIL = GREUGE
		WHERE m.maxFecha < TIMESTAMPADD(MONTH,-2,ge.Fecha);
		
		
		-- Recobro
		
		UPDATE bi.Greuge_Evolution ge 
		JOIN (
			   SELECT cs.Id_Cliente, sum(Valor * Cantidad) as Importe
			   FROM vn2008.Tickets t
			   JOIN vn2008.Consignatarios cs on cs.Id_Consigna = t.Id_Consigna
			   JOIN vn2008.Movimientos m on m.Id_Ticket = t.Id_Ticket
			   JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = m.Id_Movimiento
			   WHERE t.Fecha >= datFEC 
			   AND t.Fecha < datFEC_TOMORROW
			   AND mc.Id_Componente = 17 -- Recobro
			   GROUP BY cs.Id_Cliente
			 ) sub using(Id_Cliente)
		SET Recobro = Importe
		WHERE ge.Fecha = datFEC;
		
		INSERT INTO vn2008.daily_task_log(consulta) VALUES(CONCAT('Greuge Evolution ',datFEC));
        
		SET datFEC = datFEC_TOMORROW;
		SET datFEC_TOMORROW = TIMESTAMPADD(DAY,1,datFEC_TOMORROW);
		SET datFEC_LASTYEAR = TIMESTAMPADD(YEAR,-1,datFEC);

        
	END WHILE;

	DROP TEMPORARY TABLE IF EXISTS maxInvoice;
    
    INSERT INTO vn2008.daily_task_log(consulta) VALUES('Greuge Evolution Add END');

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 `last_buy_id_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 `last_buy_id_add`()
BEGIN

-- control
-- INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.last_buy_id_add');

-- DELETE FROM bi.Last_buy_id;
TRUNCATE TABLE bi.Last_buy_id;


-- Primero metemos las del futuro, por si no hay en el presente

INSERT INTO bi.Last_buy_id SELECT * FROM
   (SELECT 
       Id_Article, Id_Compra, warehouse_id
   FROM
       vn2008.Compres c
   JOIN vn2008.Entradas e USING (Id_Entrada)
   JOIN vn2008.travel tr ON tr.id = e.travel_id
   WHERE
       Novincular = FALSE AND tarifa2 > 0 AND NOT Redada
           AND landing > curdate()
   ORDER BY landing DESC) t1
GROUP BY Id_Article , warehouse_id;

-- Ahora el presente machaca al futuro

REPLACE bi.Last_buy_id SELECT * FROM
   (SELECT 
       Id_Article, Id_Compra, warehouse_id
   FROM
       vn2008.Compres c
   JOIN vn2008.Entradas e USING (Id_Entrada)
   JOIN vn2008.travel tr ON tr.id = e.travel_id
   WHERE
       Novincular = FALSE AND tarifa2 > 0 AND NOT Redada
           AND landing BETWEEN vn2008.date_inv() AND curdate()
   ORDER BY landing DESC) t1
GROUP BY Id_Article , warehouse_id;

    TRUNCATE TABLE bi.Last_buy_idBackUp;
    INSERT INTO bi.Last_buy_idBackUp
    SELECT * FROM Last_buy_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 `margenes` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `margenes`()
BEGIN

TRUNCATE TABLE bi.margenes;

INSERT INTO bi.margenes
SELECT Id_Article, Cantidad as Unidades, Cantidad * round(nz(Costefijo) + nz(Embalajefijo) + nz(Comisionfija) + nz(Portefijo),3) as Coste , w.name as almacen,  month(landing) as Mes, year(landing) as Year, 0 as Venta
FROM vn2008.Compres C
JOIN vn2008.Entradas E using(Id_Entrada)
JOIN vn2008.travel tr on tr.id = travel_id
JOIN vn2008.warehouse w on w.id = tr.warehouse_id
LEFT JOIN vn2008.Articles A using(Id_Article)
JOIN vn2008.Tipos TP using(tipo_id)
WHERE landing  between '2013-01-01' and ' 2013-12-31'
AND E.Id_Proveedor <> 4
AND not redada
AND not inventario
union all
SELECT Id_Article, Cantidad as Unidades, 0 as Coste , w.name, month(Fecha) as Mes, year(Fecha) as Year,  Cantidad * round(Preu * (100 - M.Descuento) / 100,2) as Venta
FROM vn2008.Movimientos M
JOIN vn2008.Articles A using(Id_Article)
JOIN vn2008.Tipos TP using(tipo_id)
JOIN vn2008.Tickets T using(Id_Ticket)
JOIN vn2008.Clientes C using(Id_Cliente)
JOIN vn2008.warehouse w on w.id = warehouse_id
WHERE Fecha  between '2013-01-01' and ' 2013-12-31'
AND (Id_Cliente = 31 or invoice)
AND Id_Cliente NOT IN (2066,2067,2068);

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 `nightly_tasks` */;
/*!50003 SET @saved_cs_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 `nightly_tasks`()
BEGIN

call bi.analisis_ventas_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 `nigthlyAnalisisVentas` */;
/*!50003 SET @saved_cs_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 `nigthlyAnalisisVentas`()
BEGIN

	INSERT INTO vn2008.daily_task_log(consulta) VALUES('analisis ventas START');
    
	CALL bi.analisis_ventas_update;
    CALL bi.analisis_ventas_simple;
    CALL bi.analisis_ventas_evolution_add;
    
    INSERT INTO vn2008.daily_task_log(consulta) VALUES('analisis ventas END');

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 `partitioning` */;
/*!50003 SET @saved_cs_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 `partitioning`(IN intyear INT)
BEGIN
	
    DECLARE v_sql TEXT;
	DECLARE strSquemaName VARCHAR(10);
	DECLARE strTableName VARCHAR(20);
	DECLARE strFieldName VARCHAR(20);
	DECLARE strDateField VARCHAR(20);
	DECLARE strTableDependingOn VARCHAR(20);
	DECLARE strFieldDependingOn VARCHAR(20);
	DECLARE done BIT DEFAULT 0;
	DECLARE strCacheSchema VARCHAR(5);
	DECLARE dat_start,dat_end DATE;
    DECLARE cur1 CURSOR FOR
		SELECT `schema_name`,`table_name` FROM `cache`.partitioning_information ORDER BY execution_order;
	DECLARE cur2 CURSOR FOR
		SELECT `schema_name`,`table_name`,`date_field` FROM `cache`.partitioning_information WHERE date_field > '' ORDER BY execution_order;
	DECLARE cur3 CURSOR FOR
		SELECT `schema_name`,`table_name`,`table_depending` FROM `cache`.partitioning_information WHERE table_depending > '' ORDER BY execution_order;
	DECLARE cur4 CURSOR FOR
		SELECT `schema_name`,`table_name`,`table_depending` FROM `cache`.partitioning_information WHERE table_depending > '' ORDER BY execution_order DESC;     
	DECLARE cur5 CURSOR FOR
		SELECT `schema_name`,`table_name`,`date_field` FROM `cache`.partitioning_information WHERE date_field > '' ORDER BY execution_order DESC;
    
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

	SET FOREIGN_KEY_CHECKS=0;
	IF LENGTH(intyear) <> 4 THEN
		CALL el_año_debe_contener_4_caracteres_yyyy();
	END IF;
	SET dat_start = STR_TO_DATE(CONCAT('01,01,',intyear),'%d,%m,%Y');
	SET dat_end = STR_TO_DATE(CONCAT('31,12,',intyear),'%d,%m,%Y');
	SET strCacheSchema = CONCAT('vn_',right(intyear,2));
	SET v_sql = sql_printf ('CREATE SCHEMA IF NOT EXISTS %t',strCacheSchema);
	CALL util.exec (v_sql);
    
     -- Insertamos en las tablas del cur1
    OPEN cur1;
	FETCH cur1 INTO strSquemaName,strTableName;
	WHILE NOT done DO
		SET v_sql = sql_printf ('CREATE TABLE IF NOT EXISTS %t.%t LIKE %t.%t',
			strCacheSchema,
			strTableName,
			strSquemaName,
			strTableName);
		            
		CALL util.exec (v_sql);
 
	FETCH cur1 INTO strSquemaName,strTableName;
  
    END WHILE;
	CLOSE cur1;
    
    -- Insertamos en las tablas del cur2
    OPEN cur2;
	FETCH cur2 INTO strSquemaName,strTableName,strDateField;
	WHILE NOT done DO
		SET v_sql = sql_printf ('REPLACE INTO %t.%t SELECT * FROM %t.%t WHERE %t BETWEEN %v AND %v',
			strCacheSchema,
			strTableName,
			strSquemaName,
			strTableName,
			strDateField,
			dat_start,
			dat_end);
		            
		SELECT v_sql;
		CALL util.exec (v_sql);
 
	FETCH cur2 INTO strSquemaName,strTableName,strDateField;
  
    END WHILE;
	CLOSE cur2;
    
    -- Insertamos en las tablas del cur3
	OPEN cur3;
    SET done = 0;
	FETCH cur3 INTO strSquemaName,strTableName,strTableDependingOn;
	WHILE NOT done DO


		-- Torna la columna per la qual vincular amb el seu pare
		SELECT kcu.column_name INTO strFieldName
		FROM information_schema.key_column_usage kcu
		WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci
			AND REFERENCED_TABLE_NAME = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci
			AND table_name = CONVERT(strTableName USING utf8) COLLATE utf8_general_ci;
            
				-- Torna la columna per la qual vincular amb el seu fill
		SELECT kcu.column_name INTO strFieldDependingOn
			FROM information_schema.key_column_usage kcu
			WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci -- FIX mirar l'esquema del pare
			AND constraint_name = 'PRIMARY'        
			AND table_name =  CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci;

		SET v_sql = sql_printf ('REPLACE INTO %t.%t SELECT a.* FROM %t.%t a JOIN %t.%t b ON a.%t = b.%t',
			strCacheSchema,
			strTableName,
			strSquemaName,
			strTableName,
			strCacheSchema,
			strTableDependingOn,
			strFieldName,
			strFieldDependingOn);
		select v_sql;
		CALL util.exec (v_sql);

	FETCH cur3 INTO strSquemaName,strTableName,strTableDependingOn;
    END WHILE;

	CLOSE cur3;

		-- Borramos en las tablas del cur4 que es igual que el dos pero en sentido descendente 
		-- para evitar errores con las foreign key
	OPEN cur4;
    SET done = 0;
	FETCH cur4 INTO strSquemaName,strTableName,strTableDependingOn;
	WHILE NOT done DO

        
		-- Torna la columna per la qual vincular amb el seu pare
		SELECT kcu.column_name INTO strFieldName
		FROM information_schema.key_column_usage kcu
		WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci
			AND REFERENCED_TABLE_NAME = CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci
			AND table_name =  CONVERT(strTableName USING utf8) COLLATE utf8_general_ci;

				-- Torna la columna per la qual vincular amb el seu fill
		SELECT kcu.column_name INTO strFieldDependingOn
			FROM information_schema.key_column_usage kcu
			WHERE table_schema = CONVERT(strSquemaName USING utf8) COLLATE utf8_general_ci
			AND constraint_name = 'PRIMARY'        
			AND table_name =  CONVERT(strTableDependingOn USING utf8) COLLATE utf8_general_ci;
        
        SELECT v_sql;
		SET v_sql = sql_printf ('DELETE a.* FROM %t.%t a JOIN %t.%t b ON a.%t = b.%t',
			strSquemaName,
			strTableName,
			strCacheSchema,
			strTableDependingOn,
			strFieldName,
			strFieldDependingOn);
		CALL util.exec (v_sql);

	FETCH cur4 INTO strSquemaName,strTableName,strTableDependingOn;
    END WHILE;

	CLOSE cur4;

	-- Borramos en las tablas del cur5
	OPEN cur5;
	SET done = 0;
	FETCH cur5 INTO strSquemaName,strTableName,strDateField;
	WHILE NOT done DO
		
		SET v_sql = sql_printf ('DELETE FROM %t WHERE %t BETWEEN %v AND %v',
			strTableName,
			strDateField,
			dat_start,
			dat_end);
		CALL util.exec (v_sql);

	FETCH cur5 INTO strSquemaName,strTableName,strDateField;

    END WHILE;
	CLOSE cur5;
	SET FOREIGN_KEY_CHECKS=1;
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 `primer_pedido_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 `primer_pedido_add`()
BEGIN
	INSERT IGNORE INTO bi.primer_pedido(Id_Ticket, Id_Cliente, month, year, total)
		SELECT *
		FROM
			(SELECT 
				`m`.`Id_Ticket` ,
				`v`.`Id_Cliente` ,
				`t`.`month`,
				`t`.`year`,
				v.importe + v.recargo as total
			FROM
				 bs.ventas v
			JOIN 
				vn2008.Movimientos m on m.Id_Movimiento = v.Id_Movimiento
			JOIN
				vn2008.time t on t.date = v.fecha 
			WHERE
				fecha > CURDATE() + INTERVAL -(1) YEAR
			ORDER BY fecha) `s`
		GROUP BY `s`.`Id_Cliente`;
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 `regularidad` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `regularidad`()
BEGIN

select Id_Cliente, Meses, IF(Antiguedad = 13,12,Antiguedad) , Meses / IF(Antiguedad = 13,12,Antiguedad) as Regularidad from (
SELECT Id_Cliente, count(*) as Meses, FLOOR(DATEDIFF('2012-07-31', IF(Created < '2011-08-01','2011-08-01', Created)) / 30) +1 as Antiguedad  from
(

SELECT DISTINCT Id_Cliente, Periodo(Fecha) as periodo from Facturas
where Fecha between '2011-08-01' AND '2012-07-31'

) sub

join Clientes using(Id_Cliente)
where Created <= '2012-07-31'

group by Id_Cliente
having Antiguedad > 0

) sub44
order by Antiguedad ;


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 `rotacion_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 `rotacion_update`()
BEGIN

-- control
INSERT INTO vn2008.daily_task_log(consulta) VALUES('bi.rotation_update');

-- Sólo hace la consulta gorda los sábados de madrugada. Necesita casi dos horas.

		call rotacion_update_manual(1, 999999, 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 `rotacion_update_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 `rotacion_update_manual`(IN intART_DESDE INT, IN intART_HASTA INT, IN datSTART DATE, IN datEND DATE)
BEGIN


DECLARE intLAPSO INT DEFAULT DATEDIFF(datEND,datSTART );




		REPLACE bi.rotacion(Id_Article,warehouse_id,total,rotacion)
		SELECT Id_Article,  warehouse_id, Total,  round((sum(Saldo_Ponderado)/Total),2) as rotacion -- round(avg(Saldo_Ponderado)  / (Total / intLAPSO),1) as Rotacion
		FROM
		(
		SELECT Id_Article,  warehouse_id,
			@intervalo:= IF(warehouse_id = @wh AND Id_Article = @art ,   DATEDIFF(Fecha, @fec),1) as Dias,
	        IF(warehouse_id = @wh AND Id_Article = @art , IF(@sd < 0,0,@sd) * @intervalo, IF(Unidades<0,0,Unidades)) as Saldo_Ponderado,
			IF(warehouse_id = @wh AND Id_Article = @art , @sd:= @sd + Unidades, @sd:= Unidades) as Saldo

		, @fec:= Fecha, @art:= Id_Article, @wh:= warehouse_id
		FROM
		(
		SELECT Id_Article, landing as Fecha, sum(Cantidad) as Unidades, warehouse_id, @fec:= datSTART, @art := 0, @d := 0, @sd:= 0, @wh := 0, @intervalo := 0
		FROM
		(
		SELECT Id_Article, landing, Cantidad, warehouse_id
		FROM vn2008.Compres C
		JOIN vn2008.Entradas E using(Id_Entrada)
		JOIN vn2008.Articles A using(Id_Article)
		JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
		JOIN vn2008.travel tr on tr.id = travel_id
		JOIN vn2008.warehouse w on w.id = tr.warehouse_id
		WHERE landing between datSTART and datEND
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Proveedor <> 4
		AND r.display <> 0 
		AND NOT E.Inventario
		AND NOT fuente
		AND NOT redada
		UNION ALL
		SELECT Id_Article, shipment, -Cantidad, warehouse_id_out
		FROM vn2008.Compres C
		JOIN vn2008.Entradas E using(Id_Entrada)
		JOIN vn2008.Articles A using(Id_Article)
        JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
		JOIN vn2008.travel tr on tr.id = travel_id
		JOIN vn2008.warehouse w on w.id = tr.warehouse_id_out
		WHERE shipment between datSTART and datEND
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Proveedor <> 4
		AND r.display <> 0 
		AND NOT fuente
		AND NOT E.Inventario
		AND NOT redada
		UNION ALL
		SELECT Id_Article, date(Fecha), -Cantidad, warehouse_id
		FROM vn2008.Movimientos M
		JOIN vn2008.Articles A using(Id_Article)
        JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
		JOIN vn2008.Tickets t using(Id_Ticket)
		JOIN vn2008.warehouse w on w.id = t.warehouse_id
		WHERE Fecha between datSTART and datEND
		AND r.display <> 0 
        AND NOT fuente
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Cliente NOT IN (2066,2067,2068)
		) sub 
		GROUP BY Id_Article, warehouse_id, Fecha
		) sub2
		) sub4
		JOIN 
		(
		SELECT Id_Article, sum(Cantidad) as Total, warehouse_id
		FROM vn2008.Compres C
		JOIN vn2008.Entradas E using(Id_Entrada)
		JOIN vn2008.Articles A using(Id_Article)
        JOIN vn2008.Tipos tp ON tp.tipo_id = A.tipo_id
        LEFT JOIN vn2008.reinos r ON r.id = tp.reino_id
		JOIN vn2008.travel tr on tr.id = travel_id
		JOIN vn2008.warehouse w on w.id = tr.warehouse_id
		WHERE landing between datSTART and datEND
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Proveedor <> 4
		AND NOT E.Inventario
		AND r.display <> 0 
		AND NOT redada
        AND NOT fuente
		GROUP BY Id_Article, warehouse_id
		) sub3 using(Id_Article, warehouse_id)

		GROUP BY Id_Article, warehouse_id;



		CALL vn2008.item_last_buy_(NULL,datSTART);
	
		-- Añadimos el volumen por unidad de venta
		update bi.rotacion r
		JOIN vn2008.t_item_last_buy b ON r.Id_Article = b.item_id AND r.warehouse_id = b.warehouse_id
		join vn2008.Compres ON Id_Compra = b.buy_id
		set cm3 = vn2008.cm3_2(Id_Cubo, r.Id_Article) / Packing
        where r.Id_Article between intART_DESDE and intART_HASTA;

-- Añadimos el coste de almacenamiento y manipulacion
UPDATE bi.rotacion
JOIN (
			SELECT warehouse_id, sum(total*rotacion*cm3)  as Operacion
			FROM bi.rotacion
            WHERE Id_Article between intART_DESDE and intART_HASTA
			GROUP BY warehouse_id 
          ) sub using(warehouse_id)

JOIN (
			SELECT warehouse_id, sum(Valor) as Coste_Auxiliar
			FROM bi.tarifa_warehouse 
			WHERE Id_Premisa = 1 
			GROUP BY warehouse_id
			) sub2 using(warehouse_id)

JOIN (
			SELECT warehouse_id, sum(Valor) as Coste_Operativo 
			FROM bi.tarifa_warehouse 
			WHERE Id_Premisa IN (2,3) 
			GROUP BY warehouse_id
			) sub3 using(warehouse_id)

JOIN (
			SELECT warehouse_id, sum(Valor) as Coste_Manipulacion
			FROM bi.tarifa_warehouse 
			WHERE Id_Premisa = 4
			GROUP BY warehouse_id
			) sub4 using(warehouse_id)

SET auxiliar = if(rotacion < 0,0,round(rotacion *cm3 * Coste_Auxiliar / Operacion,4))
       ,almacenaje = if(rotacion < 0,0,round(rotacion *cm3 * Coste_Operativo / Operacion,4))
      ,  manipulacion = if(rotacion < 0,0,round(rotacion *cm3 * Coste_Manipulacion / Operacion,4))
      WHERE Id_Article between intART_DESDE and intART_HASTA;


-- Añadimos todos los productos de los que no tenemos histórico, con la media de su familia como valor por defecto

INSERT INTO bi.rotacion(Id_Article, warehouse_id, rotacion, cm3, almacenaje, manipulacion, auxiliar, mermas)
SELECT a.Id_Article,  warehouse_id, rotacion_m, cm3_m, alm_m, man_m, aux_m, merm_m
FROM vn2008.Articles a
JOIN (SELECT tipo_id, warehouse_id, Id_Tipo, avg(rotacion) rotacion_m, avg(cm3) cm3_m, avg(almacenaje) alm_m, avg(manipulacion) man_m
                           , avg(auxiliar) aux_m, avg(mermas) merm_m
			from bi.rotacion
			join vn2008.Articles a using(Id_Article)
			join vn2008.Tipos tp using(tipo_id)
			group by tipo_id, warehouse_id) sub using(tipo_id)
            
WHERE a.Id_Article between intART_DESDE and intART_HASTA
ON DUPLICATE KEY UPDATE rotacion = rotacion;

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 `rotacion_update_manual_PCA` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `rotacion_update_manual_PCA`(IN datSTART DATE, IN datEND DATE)
BEGIN


DECLARE intLAPSO INT DEFAULT DATEDIFF(datEND,datSTART );
DECLARE intART_DESDE BIGINT DEFAULT 1;
DECLARE intART_HASTA BIGINT DEFAULT 100;

WHILE intART_HASTA < 999999 DO

		IF intART_HASTA MOD 1000 = 0 THEN
        
			SELECT intART_HASTA;
        
        END IF;

		REPLACE bi.rotacion(Id_Article,warehouse_id,total,rotacion)
		SELECT Id_Article,  warehouse_id, Total,  round((sum(Saldo_Ponderado)/Total),2) as rotacion -- round(avg(Saldo_Ponderado)  / (Total / intLAPSO),1) as Rotacion
		FROM
		(
		SELECT Id_Article,  warehouse_id,
			@intervalo:= IF(warehouse_id = @wh AND Id_Article = @art ,   DATEDIFF(Fecha, @fec),1) as Dias,
	        IF(warehouse_id = @wh AND Id_Article = @art , IF(@sd < 0,0,@sd) * @intervalo, IF(Unidades<0,0,Unidades)) as Saldo_Ponderado,
			IF(warehouse_id = @wh AND Id_Article = @art , @sd:= @sd + Unidades, @sd:= Unidades) as Saldo

		, @fec:= Fecha, @art:= Id_Article, @wh:= warehouse_id
		FROM
		(
		SELECT Id_Article, landing as Fecha, sum(Cantidad) as Unidades, warehouse_id, @fec:= datSTART, @art := 0, @d := 0, @sd:= 0, @wh := 0, @intervalo := 0
		FROM
		(
		SELECT Id_Article, landing, Cantidad, warehouse_id
		FROM vn2008.Compres C
		JOIN vn2008.Entradas E using(Id_Entrada)
		JOIN vn2008.Articles A using(Id_Article)
		JOIN vn2008.Tipos using(tipo_id)
		JOIN vn2008.travel tr on tr.id = travel_id
		JOIN vn2008.warehouse w on w.id = tr.warehouse_id
		WHERE landing between datSTART and datEND
        AND warehouse_id = 44
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Proveedor <> 4
		AND reino_id IN (3,4)
		AND NOT E.Inventario
		AND NOT fuente
		AND NOT redada
		UNION ALL
		SELECT Id_Article, shipment, -Cantidad, warehouse_id_out
		FROM vn2008.Compres C
		JOIN vn2008.Entradas E using(Id_Entrada)
		JOIN vn2008.Articles A using(Id_Article)
        JOIN vn2008.Tipos using(tipo_id)
		JOIN vn2008.travel tr on tr.id = travel_id
		JOIN vn2008.warehouse w on w.id = tr.warehouse_id_out
		WHERE shipment between datSTART and datEND
        AND warehouse_id_out = 44
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Proveedor <> 4
		AND reino_id IN (3,4)
		AND NOT fuente
		AND NOT E.Inventario
		AND NOT redada
		UNION ALL
		SELECT Id_Article, date(Fecha), -Cantidad, warehouse_id
		FROM vn2008.Movimientos M
		JOIN vn2008.Articles A using(Id_Article)
        JOIN vn2008.Tipos using(tipo_id)
		JOIN vn2008.Tickets t using(Id_Ticket)
		JOIN vn2008.warehouse w on w.id = t.warehouse_id
		WHERE Fecha between datSTART and datEND
        AND t.warehouse_id = 44
		AND reino_id IN (3,4)
        AND NOT fuente
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Cliente NOT IN (2066,2067,2068)
		) sub 
		GROUP BY Id_Article, warehouse_id, Fecha
		) sub2
		) sub4
		JOIN 
		(
		SELECT Id_Article, sum(Cantidad) as Total, warehouse_id
		FROM vn2008.Compres C
		JOIN vn2008.Entradas E using(Id_Entrada)
		JOIN vn2008.Articles A using(Id_Article)
        JOIN vn2008.Tipos using(tipo_id)
		JOIN vn2008.travel tr on tr.id = travel_id
		JOIN vn2008.warehouse w on w.id = tr.warehouse_id
		WHERE landing between datSTART and datEND
        AND warehouse_id = 44
		AND Id_Article between intART_DESDE and intART_HASTA
		AND Id_Proveedor <> 4
		AND NOT E.Inventario
		AND reino_id IN (3,4)
		AND NOT redada
        AND NOT fuente
		GROUP BY Id_Article, warehouse_id
		) sub3 using(Id_Article, warehouse_id)
		GROUP BY Id_Article, warehouse_id;

SET intART_DESDE = intART_DESDE + 100;
SET intART_DESDE = intART_HASTA + 100;

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 `rotacion_volumen_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=`z-developer`@`%` PROCEDURE `rotacion_volumen_update`()
BEGIN

		CALL vn2008.item_last_buy_(NULL,curdate());
	
		-- Añadimos el volumen por unidad de venta
		update bi.rotacion r
		JOIN vn2008.t_item_last_buy b ON r.Id_Article = b.item_id AND r.warehouse_id = b.warehouse_id
		join vn2008.Compres ON Id_Compra = b.buy_id
		set cm3 = vn2008.cm3_2(Id_Cubo, r.Id_Article) / Packing;

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 `rutas_m3_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 `rutas_m3_add`()
BEGIN

	DECLARE datSTART DATE DEFAULT TIMESTAMPADD(DAY,-90,CURDATE());
	DECLARE datEND DATE DEFAULT CURDATE();
	DECLARE datFEC DATE;
    
	IF hour(now()) between 5 and 24 then 

		SET datSTART = CURDATE();
		SET datEND = TIMESTAMPADD(DAY,1,CURDATE());

	end if;

	SET datFEC = datSTART;
	
    CALL vn2008.item_last_buy_(NULL,CURDATE());
	WHILE datFEC <= datEND DO

		UPDATE vn2008.Rutas R
			JOIN (SELECT R.Id_Ruta, sum(Cantidad * vn2008.cm3_unidad(b.buy_id)) / 1000000 as m3 
				  from vn2008.Rutas R
				  join vn2008.Tickets t using(Id_Ruta) 
				  join vn2008.Movimientos m using(Id_Ticket) 
				  join vn2008.t_item_last_buy b ON Id_Article = b.item_id AND b.warehouse_id = t.warehouse_id
				  where R.Fecha = datFEC AND R.m3 IS NULL
				  group by R.Id_Ruta
			) t using(Id_Ruta) 
		SET R.m3 = t.m3
        WHERE R.m3 IS NULL;

		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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_add2kk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_add2kk`(intNUMDAYS INTEGER)
BEGIN

DECLARE datSTART,datEND DATETIME;
-- Seleccionamos los tickets a tratar añadiendolos a la tabla bi.ticket 

    SET @@session.max_sp_recursion_depth=250;  -- Habilito la recursión en mysql hasta un límite de 250.
    SET datSTART = TIMESTAMPADD(DAY, -intNUMDAYS, CURDATE());


    SET datEND = vn2008.DAYEND(datSTART);
 


   
   -- Actualiza el valor de costfixat en Movimientos a efectos estadisticos
update vn2008.Movimientos m
join
(
select Id_Movimiento, round(IFNULL(sum(Valor) , IFNULL(     Preu * (100 - m.Descuento)   /100,0       )    ),2) as Cost
from vn2008.Tickets t
join vn2008.Movimientos m using(Id_Ticket)
left join vn2008.Movimientos_componentes mc using(Id_Movimiento)
join bi.tarifa_componentes tc using(Id_Componente)
join bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base
where t.Fecha between datSTART AND datEND
group by Id_Movimiento
) sub using(Id_Movimiento)
set CostFixat = Cost;


   
    
    REPLACE INTO bi.ticket(Id_Ticket,Id_Cliente,`date`, tipo_id, `year`,`week`,`month`,`day`,`view`,amount,Id_Trabajador,Id_propietario )
    SELECT t.Id_Ticket,c.Id_Cliente,t.Fecha `date`,tipo_id, year(Fecha) as `year`, vn2008.vnweek(Fecha) as `week`, 
    month(Fecha) as `month`,vn2008.vnday(Fecha) as `day`, A.Vista `view`,
    IFNULL(   round(     sum(cantidad * Preu * (100 - m.Descuento)/100)     ,2)    ,0) as amount,
    c.Id_Trabajador, c.Id_Trabajador
    FROM vn2008.Tickets t 
		JOIN vn2008.Consignatarios cs using(Id_Consigna)
        JOIN vn2008.warehouse W ON W.id = t.warehouse_id
        INNER JOIN vn2008.Clientes c on cs.Id_Cliente = c.Id_Cliente
        INNER JOIN vn2008.Movimientos m USING(Id_Ticket)
	    INNER JOIN vn2008.Articles USING(Id_Article)
        INNER JOIN vn2008.Agencias A on A.Id_Agencia = t.Id_Agencia
        INNER JOIN vn2008.Tipos TP USING(tipo_id)
        WHERE Fecha BETWEEN datSTART AND datEND
        AND NOT W.fuente
        AND c.`Real`
        AND (reino_id <> 6 OR m.Id_Article IN (95,98)) 
    GROUP BY t.Id_Ticket,tipo_id    ;
    
    /*
    UPDATE bi.ticket
    JOIN vn2008.Tickets using(Id_Ticket)
    JOIN vn2008.Agencias using(Id_Agencia)
    JOIN vn2008.agency_warehouse aw using(agency_id,warehouse_id)
    SET `view` =  aw.Vista
    WHERE Tickets.Fecha BETWEEN datSTART AND datEND;
    */

    

    IF (intNUMDAYS>0) THEN
        CALL `bi`.`ticket_add2` (intNUMDAYS-1);
    END IF;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_addkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_addkk`(intNUMDAYS INTEGER)
BEGIN

DECLARE datSTART DATETIME;
	
    IF (intNUMDAYS > 0) THEN
		SET datSTART = TIMESTAMPADD(DAY, -intNUMDAYS, CURDATE());
		DELETE FROM bi.ticket where `date` >= datSTART ;
        CALL `bi`.`ticket_add2` (intNUMDAYS);
		DELETE FROM bi.ticket where `date` < '2001-01-01';
    END IF;

UPDATE bi.ticket bt
JOIN vn2008.Tickets USING(Id_Ticket)
JOIN vn2008.Consignatarios C USING(Id_Consigna)
SET bt.Id_Cliente = C.Id_Cliente
, bt.Id_Trabajador = @idT := vn2008.Averiguar_ComercialCliente_Id(C.Id_Cliente,bt.date)
, bt.Id_propietario = @idT
WHERE Tickets.Id_Cliente = 31 AND bt.date >= datSTART;


-- Almacena los tickets que comisionan, para consultas rapidas

truncate table bi.f_tvc;

insert into bi.f_tvc
select Id_Ticket
from vn2008.Tickets t
join vn2008.Consignatarios cs using(Id_Consigna)
join vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente
join vn2008.warehouse w on w.id = t.warehouse_id
where c.`Real` = TRUE
and w.comisionantes = TRUE;




-- Quita las horas de los tickets del mes anterior
IF DAY(CURDATE()) = 15 THEN
	update vn2008.Tickets 
	set Fecha = date(Fecha) 
	where Fecha between TIMESTAMPADD(DAY,-46,CURDATE()) and TIMESTAMPADD(DAY, -1 - DAY(CURDATE()), CURDATE());
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_add_bydaykk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_add_bydaykk`(datFEC DATE)
BEGIN

    DECLARE datSTART DATETIME;
    DECLARE datEND DATETIME;

-- Seleccionamos los tickets a tratar añadiendolos a la tabla bi.ticket 

    SET @@session.max_sp_recursion_depth=2500;  -- Habilito la recursión en mysql hasta un límite de 2500.
   
    SET datSTART = DATE(datFEC);
    SET datEND = TIMESTAMPADD(DAY,30,datSTART);
        
    DELETE FROM bi.ticket WHERE `date` between datSTART and datEND;
     
    INSERT INTO bi.ticket(Id_Ticket,`date`, tipo_id, `year`,`week`,`month`,`view`,amount,Id_Trabajador, Id_Cliente, Id_Propietario )
    SELECT t.Id_Ticket,t.Fecha `date`,tipo_id, vn2008.vnyear(Fecha) as `year`, vn2008.vnweek(Fecha) as `week`, 
    vn2008.vnmonth(Fecha) as `month`, A.Vista `view`, IFNULL(round(sum(cantidad * preu * (100 - m.Descuento)/100),2),0) as amount,
    c.Id_Trabajador, c.Id_Cliente,  ifnull(c.Id_Trabajador,20)
    FROM vn2008.Tickets t 
		JOIN vn2008.Consignatarios cs using(Id_Consigna)
        JOIN vn2008.warehouse W ON W.id = t.warehouse_id 
        INNER JOIN vn2008.Clientes c on c.Id_Cliente = cs.Id_Cliente
        INNER JOIN vn2008.Movimientos m USING(Id_Ticket)
        INNER JOIN vn2008.Articles USING(Id_Article)
        INNER JOIN vn2008.Agencias A on A.Id_Agencia = t.Id_Agencia
        INNER JOIN vn2008.Tipos TP USING(tipo_id)
        LEFT JOIN vn2008.reinos r ON r.id = TP.reino_id
        WHERE Fecha >= datSTART 
        AND Fecha < datEND
        AND NOT W.fuente
        AND (invoice or t.Id_Cliente in (5,31))
        AND r.display <> 0
    GROUP BY t.Id_Ticket,tipo_id
    ON DUPLICATE KEY UPDATE amount = amount,
		`view` = `view`,
		`date` = `date`,
		`week` = `week`,
		`year` = `year`,
		`month` = `month`,
		tipo_id = tipo_id,
		Id_Trabajador = Id_Trabajador,
		Id_Cliente = Id_Cliente,
		Id_Propietario = ifnull(Id_Trabajador,20);
    
    UPDATE bi.ticket
		JOIN vn2008.Tickets using(Id_Ticket)
		JOIN vn2008.Agencias using(Id_Agencia)
		JOIN vn2008.agency_warehouse aw using(agency_id,warehouse_id)
    SET `view` =  aw.Vista
    WHERE Tickets.Fecha BETWEEN datSTART AND datEND;
    
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 `Ultima_Accion` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `Ultima_Accion`()
BEGIN

REPLACE INTO bi.lastaction(Id_Cliente, Cliente, Ultima_accion, Comercial)

SELECT Id_Cliente, Cliente, Ultima_accion, Comercial
FROM vn2008.Clientes
JOIN
(
SELECT Id_Cliente, MAX(calldate) as Ultima_accion, vn2008.Averiguar_ComercialCliente(Id_Cliente, CURDATE()) as Comercial
FROM
(
SELECT Id_Cliente, calldate
FROM vn2008.cdr 
JOIN vn2008.Contactos CT on CT.Telefono = dst
JOIN vn2008.Relaciones using(Id_Contacto)
WHERE Id_Cliente IS NOT NULL
AND duration > 30
UNION ALL
SELECT Id_Cliente, calldate
FROM vn2008.cdr 
JOIN vn2008.Contactos CT on CT.Movil = dst
JOIN vn2008.Relaciones using(Id_Contacto)
WHERE Id_Cliente IS NOT NULL
AND duration > 30
UNION ALL
SELECT Id_Cliente, calldate
FROM vn2008.cdr 
JOIN vn2008.Clientes CT on CT.Telefono = dst
WHERE duration > 30
UNION ALL
SELECT Id_Cliente, calldate
FROM vn2008.cdr 
JOIN vn2008.Clientes CT on CT.Movil = dst
WHERE duration > 30
UNION ALL
SELECT C.Id_Cliente, Fecha
FROM vn2008.Tickets JOIN vn2008.Consignatarios C using(Id_Consigna)
) sub
GROUP BY Id_Cliente ) sub2 USING(Id_Cliente);
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 `Velocity_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 `Velocity_Add`()
BEGIN

DECLARE bol_EXISTS BOOL;
DECLARE datMAX DATETIME;
DECLARE v_buffer VARCHAR(11);
DECLARE v_sql VARCHAR(255);



SELECT MAX(Fecha) INTO datMAX FROM bi.Velocity;

IF Date(datMAX) = CURDATE() AND hour(datMAX) > hour(now()) THEN

 
    SET v_buffer =  vn2008.buffer_name(CURDATE(),1);
    
	SELECT count(*) INTO bol_EXISTS FROM information_schema.`TABLES` 
        WHERE TABLE_NAME = CONVERT(v_buffer using utf8) collate utf8_general_ci;
     
    IF  bol_EXISTS THEN 
    
	SET v_sql = sql_printf (
					'INSERT INTO bi.Velocity(tipo_id, Fecha, Disponible, Visible)
					 SELECT A.tipo_id, NOW(), sum(avalaible), sum(visible)
					 FROM vn2008.%t b
					 JOIN Articles A ON b.item_id = A.Id_Article GROUP BY tipo_id;
		',
				v_buffer
	);
				
            
    CALL util.exec (v_sql);
		
	END IF;

END IF;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Current Database: `pbx`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `pbx` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `pbx`;

--
-- Table structure for table `blacklist`
--

DROP TABLE IF EXISTS `blacklist`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `blacklist` (
  `phone` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`phone`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Hangup input calls from this list';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklistBeforeInsert`
BEFORE INSERT ON `blacklist` FOR EACH ROW
BEGIN
	CALL phoneIsValid (NEW.phone);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`blacklistBerforeUpdate`
BEFORE UPDATE ON `blacklist` FOR EACH ROW
BEGIN
	CALL phoneIsValid (NEW.phone);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Table structure for table `cdr`
--

DROP TABLE IF EXISTS `cdr`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cdr` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `call_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `clid` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `src` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `dst` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `dcontext` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `channel` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `dst_channel` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `last_app` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `last_data` varchar(80) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `duration` int(11) NOT NULL DEFAULT '0',
  `billsec` int(11) NOT NULL DEFAULT '0',
  `disposition` varchar(45) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `ama_flags` int(11) NOT NULL DEFAULT '0',
  `account_code` varchar(20) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `unique_id` varchar(32) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  `user_field` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
  PRIMARY KEY (`id`),
  KEY `calldate` (`call_date`),
  KEY `dst` (`dst`),
  KEY `accountcode` (`account_code`),
  KEY `dstchannel` (`dst_channel`),
  KEY `disposition` (`disposition`),
  KEY `src` (`src`)
) ENGINE=MyISAM AUTO_INCREMENT=172800 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `cdrConf`
--

DROP TABLE IF EXISTS `cdrConf`;
/*!50001 DROP VIEW IF EXISTS `cdrConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `cdrConf` AS SELECT 
 1 AS `calldate`,
 1 AS `clid`,
 1 AS `src`,
 1 AS `dst`,
 1 AS `dcontext`,
 1 AS `channel`,
 1 AS `dstchannel`,
 1 AS `lastapp`,
 1 AS `lastdata`,
 1 AS `duration`,
 1 AS `billsec`,
 1 AS `disposition`,
 1 AS `amaflags`,
 1 AS `accountcode`,
 1 AS `uniqueid`,
 1 AS `userfield`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `config`
--

DROP TABLE IF EXISTS `config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `sundayFestive` tinyint(4) NOT NULL,
  `countryPrefix` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `followme`
--

DROP TABLE IF EXISTS `followme`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `followme` (
  `extension` varchar(128) CHARACTER SET utf8 NOT NULL,
  `phone` varchar(20) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`extension`),
  CONSTRAINT `followme_ibfk_1` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followmeBeforeInsert`
BEFORE INSERT ON `followme` FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.phone);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`followmeBeforeUpdate`
BEFORE UPDATE ON `followme` FOR EACH ROW
BEGIN
	CALL pbx.phoneIsValid (NEW.phone);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Temporary view structure for view `followmeConf`
--

DROP TABLE IF EXISTS `followmeConf`;
/*!50001 DROP VIEW IF EXISTS `followmeConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `followmeConf` AS SELECT 
 1 AS `name`,
 1 AS `music`,
 1 AS `context`,
 1 AS `takecall`,
 1 AS `declinecall`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `followmeConfig`
--

DROP TABLE IF EXISTS `followmeConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `followmeConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `music` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `context` varchar(50) CHARACTER SET utf8 NOT NULL,
  `takeCall` char(1) CHARACTER SET utf8 NOT NULL,
  `declineCall` char(1) CHARACTER SET utf8 NOT NULL,
  `timeout` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `followmeNumberConf`
--

DROP TABLE IF EXISTS `followmeNumberConf`;
/*!50001 DROP VIEW IF EXISTS `followmeNumberConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `followmeNumberConf` AS SELECT 
 1 AS `name`,
 1 AS `ordinal`,
 1 AS `phonenumber`,
 1 AS `timeout`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `queue`
--

DROP TABLE IF EXISTS `queue`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `queue` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(128) CHARACTER SET utf8 NOT NULL,
  `name` varchar(128) CHARACTER SET utf8 NOT NULL,
  `config` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`),
  UNIQUE KEY `description` (`description`),
  KEY `config` (`config`),
  CONSTRAINT `queue_ibfk_1` FOREIGN KEY (`config`) REFERENCES `queueConfig` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queues';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queueBeforeInsert`
BEFORE INSERT ON `queue` FOR EACH ROW
BEGIN
	CALL queueIsValid (NEW.name);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queueBeforeUpdate`
BEFORE UPDATE ON `queue` FOR EACH ROW
BEGIN
	CALL queueIsValid (NEW.name);
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Temporary view structure for view `queueConf`
--

DROP TABLE IF EXISTS `queueConf`;
/*!50001 DROP VIEW IF EXISTS `queueConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `queueConf` AS SELECT 
 1 AS `name`,
 1 AS `strategy`,
 1 AS `timeout`,
 1 AS `retry`,
 1 AS `weight`,
 1 AS `maxlen`,
 1 AS `ringinuse`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `queueConfig`
--

DROP TABLE IF EXISTS `queueConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `queueConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `strategy` varchar(128) CHARACTER SET utf8 NOT NULL,
  `timeout` int(10) unsigned NOT NULL,
  `retry` int(10) unsigned NOT NULL,
  `weight` int(10) unsigned NOT NULL,
  `maxLen` int(10) unsigned NOT NULL,
  `ringInUse` tinyint(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Default values for queues configuration';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `queueMember`
--

DROP TABLE IF EXISTS `queueMember`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `queueMember` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `queue` varchar(128) CHARACTER SET utf8 NOT NULL,
  `extension` varchar(128) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `queue` (`queue`,`extension`),
  KEY `extension` (`extension`),
  CONSTRAINT `queueMember_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `queueMember_ibfk_2` FOREIGN KEY (`extension`) REFERENCES `sip` (`extension`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=723 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Queue members';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `queueMemberConf`
--

DROP TABLE IF EXISTS `queueMemberConf`;
/*!50001 DROP VIEW IF EXISTS `queueMemberConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `queueMemberConf` AS SELECT 
 1 AS `uniqueid`,
 1 AS `queue_name`,
 1 AS `interface`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `queuePhone`
--

DROP TABLE IF EXISTS `queuePhone`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `queuePhone` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `queue` varchar(128) CHARACTER SET utf8 NOT NULL,
  `phone` varchar(128) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `queue` (`queue`,`phone`),
  CONSTRAINT `queuePhone_ibfk_1` FOREIGN KEY (`queue`) REFERENCES `queue` (`name`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1003 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhoneBeforeInsert`
BEFORE INSERT ON `queuePhone` FOR EACH ROW
BEGIN
	CALL phoneIsValid (NEW.phone);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`queuePhoneBeforeUpdate`
BEFORE UPDATE ON `queuePhone` FOR EACH ROW
BEGIN
	CALL phoneIsValid (NEW.phone);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Table structure for table `schedule`
--

DROP TABLE IF EXISTS `schedule`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `schedule` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `weekDay` tinyint(3) unsigned NOT NULL COMMENT '0 = Monday, 6 = Sunday',
  `timeStart` time NOT NULL,
  `timeEnd` time NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sip`
--

DROP TABLE IF EXISTS `sip`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sip` (
  `user_id` int(10) unsigned NOT NULL DEFAULT '0',
  `extension` varchar(128) CHARACTER SET utf8 NOT NULL,
  `secret` varchar(80) CHARACTER SET utf8 NOT NULL,
  `caller_id` varchar(80) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`user_id`),
  UNIQUE KEY `extension` (`extension`),
  CONSTRAINT `sip_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SIP accounts';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sipBeforeInsert`
BEFORE INSERT ON `sip` FOR EACH ROW
BEGIN
	CALL extensionIsValid (NEW.extension);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `sipAfterInsert`
AFTER INSERT ON `sip` FOR EACH ROW
BEGIN
	INSERT INTO sipReg (userId) VALUES (NEW.user_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 */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `pbx`.`sipBeforeUpdate`
BEFORE UPDATE ON `sip` FOR EACH ROW
BEGIN
	CALL extensionIsValid (NEW.extension);
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Temporary view structure for view `sipConf`
--

DROP TABLE IF EXISTS `sipConf`;
/*!50001 DROP VIEW IF EXISTS `sipConf`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `sipConf` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `secret`,
 1 AS `callerid`,
 1 AS `host`,
 1 AS `deny`,
 1 AS `permit`,
 1 AS `type`,
 1 AS `context`,
 1 AS `incominglimit`,
 1 AS `pickupgroup`,
 1 AS `careinvite`,
 1 AS `ipaddr`,
 1 AS `regseconds`,
 1 AS `port`,
 1 AS `defaultuser`,
 1 AS `useragent`,
 1 AS `lastms`,
 1 AS `fullcontact`,
 1 AS `regserver`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `sipConfig`
--

DROP TABLE IF EXISTS `sipConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sipConfig` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `host` varchar(40) CHARACTER SET utf8 DEFAULT NULL,
  `deny` varchar(95) CHARACTER SET utf8 NOT NULL,
  `permit` varchar(95) CHARACTER SET utf8 NOT NULL,
  `type` enum('user','peer','friend') CHARACTER SET utf8 NOT NULL,
  `context` varchar(80) CHARACTER SET utf8 NOT NULL,
  `incomingLimit` varchar(10) CHARACTER SET utf8 NOT NULL,
  `pickupGroup` varchar(10) CHARACTER SET utf8 NOT NULL,
  `careInvite` varchar(10) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Default values for SIP accounts';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sipReg`
--

DROP TABLE IF EXISTS `sipReg`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sipReg` (
  `userId` int(10) unsigned NOT NULL,
  `ipAddr` varchar(40) CHARACTER SET utf8 DEFAULT NULL,
  `regSeconds` int(10) unsigned DEFAULT NULL,
  `port` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `defaultUser` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `userAgent` varchar(80) CHARACTER SET utf8 DEFAULT NULL,
  `lastMs` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `fullContact` varchar(50) CHARACTER SET utf8 DEFAULT NULL,
  `regServer` varchar(20) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`userId`),
  CONSTRAINT `sipReg_ibfk_1` FOREIGN KEY (`userId`) REFERENCES `sip` (`user_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SIP registrations';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'pbx'
--

--
-- Dumping routines for database 'pbx'
--
/*!50003 DROP FUNCTION IF EXISTS `clientFromPhone` */;
/*!50003 SET @saved_cs_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 `clientFromPhone`(vPhone VARCHAR(255)) RETURNS int(11)
    DETERMINISTIC
BEGIN
    DECLARE vClient INT DEFAULT NULL;
    
    -- SET vPhone = vPhone COLLATE 'utf8_unicode_ci';
    
    -- Searchs a customer associated to the phone number

	DROP TEMPORARY TABLE IF EXISTS tmp.customer;
	CREATE TEMPORARY TABLE tmp.customer
		ENGINE = MEMORY
		SELECT id_cliente customer
			FROM vn2008.Clientes c
			WHERE telefono = vPhone
				OR movil = vPhone
		UNION
		SELECT id_cliente
			FROM vn2008.Consignatarios
			WHERE telefono = vPhone
				OR movil = vPhone
		UNION
		SELECT r.id_cliente
			FROM vn2008.Relaciones r
				JOIN vn2008.Contactos c ON r.Id_Contacto = c.Id_Contacto
			WHERE c.telefono = vPhone
				OR c.movil = vPhone;

	SELECT t.customer INTO vClient
		FROM tmp.customer t
			JOIN vn2008.Clientes c ON c.id_cliente = t.customer
		WHERE c.activo
        LIMIT 1;

	DROP TEMPORARY TABLE tmp.customer;

	RETURN vClient;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `phoneFormat` */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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`@`%` FUNCTION `phoneFormat`(vPhone VARCHAR(255)) RETURNS varchar(255) CHARSET utf8
BEGIN
	DECLARE vI INT DEFAULT 0;
	DECLARE vChr VARCHAR(1);
	DECLARE vLen INT DEFAULT LENGTH(vPhone);
	DECLARE vNewPhone VARCHAR(255) DEFAULT '';

	WHILE vI < vLen
    DO
		SET vChr = SUBSTR(vPhone, vI + 1, 1);
    
		IF vChr REGEXP '^[0-9]$'
        THEN
			SET vNewPhone = CONCAT(vNewPhone, vChr);
		ELSEIF vChr = '+' AND vI = 0
        THEN
			SET vNewPhone = CONCAT(vNewPhone, '00');
		END IF;
        
        SET vI = vI + 1;
    END WHILE;

	IF vNewPhone REGEXP '^0+$' OR vNewPhone = '' THEN
		RETURN NULL;
	END IF;

	IF vNewPhone REGEXP '^0034' THEN
		SET vNewPhone = SUBSTR(vNewPhone, 5);
	END IF;

	RETURN vNewPhone;
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 `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `extensionIsValid` */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 `extensionIsValid`(vExtension VARCHAR(255))
    DETERMINISTIC
BEGIN
	DECLARE vIsValid BOOLEAN;

	SET vIsValid =  vExtension IS NULL
		OR (vExtension REGEXP '^[0-9]{4}$'
		AND MOD(vExtension, 100) != 0);

	IF NOT vIsValid
	THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'EXTENSION_INVALID_FORMAT';
	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 */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `phoneIsValid` */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 `phoneIsValid`(vPhone VARCHAR(255))
BEGIN
	DECLARE vIsValid BOOLEAN;

    SET vIsValid =  vPhone IS NULL
		OR (vPhone REGEXP '^[0-9]+$'
		AND vPhone NOT REGEXP '^0+$'
		AND vPhone NOT REGEXP '^0034');

	IF NOT vIsValid
    THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'PHONE_INVALID_FORMAT';
    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 */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `queueIsValid` */;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_general_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 `queueIsValid`(vQueue VARCHAR(255))
    DETERMINISTIC
BEGIN
	DECLARE vIsValid BOOLEAN;

	SET vIsValid = vQueue IS NULL
		OR vQueue REGEXP '^[1-9][0-9]00$';

	IF NOT vIsValid
	THEN
		SIGNAL SQLSTATE '45000'
			SET MESSAGE_TEXT = 'QUEUE_INVALID_FORMAT';
	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 */ ;
ALTER DATABASE `pbx` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Current Database: `salix`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `salix` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `salix`;

--
-- Table structure for table `ACL`
--

DROP TABLE IF EXISTS `ACL`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ACL` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `model` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `property` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `accessType` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `permission` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `principalType` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `principalId` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=26 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `AccessToken`
--

DROP TABLE IF EXISTS `AccessToken`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `AccessToken` (
  `id` varchar(255) CHARACTER SET utf8 NOT NULL,
  `ttl` int(11) DEFAULT NULL,
  `scopes` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `created` datetime DEFAULT NULL,
  `userId` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `Account`
--

DROP TABLE IF EXISTS `Account`;
/*!50001 DROP VIEW IF EXISTS `Account`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Account` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `password`,
 1 AS `roleFk`,
 1 AS `active`,
 1 AS `email`,
 1 AS `created`,
 1 AS `updated`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Accounting`
--

DROP TABLE IF EXISTS `Accounting`;
/*!50001 DROP VIEW IF EXISTS `Accounting`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Accounting` AS SELECT 
 1 AS `id`,
 1 AS `bank`,
 1 AS `account`,
 1 AS `accountingTypeFk`,
 1 AS `entityFk`,
 1 AS `isActive`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Address`
--

DROP TABLE IF EXISTS `Address`;
/*!50001 DROP VIEW IF EXISTS `Address`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Address` AS SELECT 
 1 AS `id`,
 1 AS `consignee`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postcode`,
 1 AS `provinceFk`,
 1 AS `phone`,
 1 AS `mobile`,
 1 AS `isEnabled`,
 1 AS `isDefaultAddress`,
 1 AS `clientFk`,
 1 AS `defaultAgencyFk`,
 1 AS `longitude`,
 1 AS `latitude`,
 1 AS `isEqualizated`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Agency`
--

DROP TABLE IF EXISTS `Agency`;
/*!50001 DROP VIEW IF EXISTS `Agency`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Agency` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `warehouseFk`,
 1 AS `isVolumetric`,
 1 AS `bankFk`,
 1 AS `warehouseAliasFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `AgencyMode`
--

DROP TABLE IF EXISTS `AgencyMode`;
/*!50001 DROP VIEW IF EXISTS `AgencyMode`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `AgencyMode` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `description`,
 1 AS `agencyTypeFk`,
 1 AS `m3`,
 1 AS `agencyFk`,
 1 AS `inflation`,
 1 AS `sendMailTo`,
 1 AS `isForTicket`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Bank`
--

DROP TABLE IF EXISTS `Bank`;
/*!50001 DROP VIEW IF EXISTS `Bank`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Bank` AS SELECT 
 1 AS `id`,
 1 AS `bank`,
 1 AS `account`,
 1 AS `cash`,
 1 AS `entityFk`,
 1 AS `isActive`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `City`
--

DROP TABLE IF EXISTS `City`;
/*!50001 DROP VIEW IF EXISTS `City`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `City` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `provinceFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Client`
--

DROP TABLE IF EXISTS `Client`;
/*!50001 DROP VIEW IF EXISTS `Client`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Client` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `fi`,
 1 AS `socialName`,
 1 AS `contact`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postcode`,
 1 AS `provinceFk`,
 1 AS `countryFk`,
 1 AS `email`,
 1 AS `phone`,
 1 AS `mobile`,
 1 AS `fax`,
 1 AS `active`,
 1 AS `discount`,
 1 AS `credit`,
 1 AS `creditInsurance`,
 1 AS `iban`,
 1 AS `dueDay`,
 1 AS `equalizationTax`,
 1 AS `hasToInvoice`,
 1 AS `invoiceByEmail`,
 1 AS `payMethodFk`,
 1 AS `salesPersonFk`,
 1 AS `contactChannelFk`,
 1 AS `sepaVnl`,
 1 AS `coreVnl`,
 1 AS `coreVnh`,
 1 AS `eypbc`,
 1 AS `quality`,
 1 AS `vies`,
 1 AS `isRelevant`,
 1 AS `typeFk`,
 1 AS `accountingAccount`,
 1 AS `created`,
 1 AS `hasToInvoiceByAddress`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ClientCredit`
--

DROP TABLE IF EXISTS `ClientCredit`;
/*!50001 DROP VIEW IF EXISTS `ClientCredit`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ClientCredit` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `employeeFk`,
 1 AS `amount`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ClientCreditLimit`
--

DROP TABLE IF EXISTS `ClientCreditLimit`;
/*!50001 DROP VIEW IF EXISTS `ClientCreditLimit`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ClientCreditLimit` AS SELECT 
 1 AS `id`,
 1 AS `maxAmount`,
 1 AS `roleFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ClientObservation`
--

DROP TABLE IF EXISTS `ClientObservation`;
/*!50001 DROP VIEW IF EXISTS `ClientObservation`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ClientObservation` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `employeeFk`,
 1 AS `text`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ClientType`
--

DROP TABLE IF EXISTS `ClientType`;
/*!50001 DROP VIEW IF EXISTS `ClientType`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ClientType` AS SELECT 
 1 AS `id`,
 1 AS `code`,
 1 AS `type`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ContactChannel`
--

DROP TABLE IF EXISTS `ContactChannel`;
/*!50001 DROP VIEW IF EXISTS `ContactChannel`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ContactChannel` AS SELECT 
 1 AS `id`,
 1 AS `name`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Country`
--

DROP TABLE IF EXISTS `Country`;
/*!50001 DROP VIEW IF EXISTS `Country`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Country` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `inCee`,
 1 AS `code`,
 1 AS `currencyFk`,
 1 AS `realCountryFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `CreditClassification`
--

DROP TABLE IF EXISTS `CreditClassification`;
/*!50001 DROP VIEW IF EXISTS `CreditClassification`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `CreditClassification` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `started`,
 1 AS `ended`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Delivery`
--

DROP TABLE IF EXISTS `Delivery`;
/*!50001 DROP VIEW IF EXISTS `Delivery`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Delivery` AS SELECT 
 1 AS `id`,
 1 AS `date`,
 1 AS `m3`,
 1 AS `warehouseFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Employee`
--

DROP TABLE IF EXISTS `Employee`;
/*!50001 DROP VIEW IF EXISTS `Employee`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Employee` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `surname`,
 1 AS `userFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `FakeProduction`
--

DROP TABLE IF EXISTS `FakeProduction`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `FakeProduction` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL DEFAULT '0',
  `clientFk` int(11) NOT NULL DEFAULT '0',
  `client` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `date` date DEFAULT NULL,
  `hour` time DEFAULT NULL,
  `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `province` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `provinceFk` smallint(6) unsigned NOT NULL DEFAULT '0',
  `agency` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `agencyFk` smallint(6) NOT NULL,
  `lines` int(1) NOT NULL DEFAULT '0',
  `m3` decimal(5,2) NOT NULL DEFAULT '0.00',
  `problems` int(1) NOT NULL DEFAULT '0',
  `problem` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `stateFk` bigint(4) NOT NULL DEFAULT '0',
  `workerfk` int(11) NOT NULL DEFAULT '0',
  `worker` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `salesPersonFk` int(11) NOT NULL DEFAULT '0',
  `salesPerson` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `state` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `boxes` double DEFAULT NULL,
  `routeFk` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=826 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `Message`
--

DROP TABLE IF EXISTS `Message`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `Message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uuid` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sender` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `recipient` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `message` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sendDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `MessageInbox`
--

DROP TABLE IF EXISTS `MessageInbox`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `MessageInbox` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uuid` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sender` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `recipient` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `finalRecipient` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `message` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `sendDate` datetime DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `PayMethod`
--

DROP TABLE IF EXISTS `PayMethod`;
/*!50001 DROP VIEW IF EXISTS `PayMethod`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `PayMethod` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `graceDays`,
 1 AS `outstandingDebt`,
 1 AS `ibanRequired`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Province`
--

DROP TABLE IF EXISTS `Province`;
/*!50001 DROP VIEW IF EXISTS `Province`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Province` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `countryFk`,
 1 AS `warehouseFk`,
 1 AS `zoneFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Role`
--

DROP TABLE IF EXISTS `Role`;
/*!50001 DROP VIEW IF EXISTS `Role`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Role` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `description`,
 1 AS `created`,
 1 AS `modified`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `RoleMapping`
--

DROP TABLE IF EXISTS `RoleMapping`;
/*!50001 DROP VIEW IF EXISTS `RoleMapping`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `RoleMapping` AS SELECT 
 1 AS `id`,
 1 AS `principalType`,
 1 AS `principalId`,
 1 AS `roleId`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Route`
--

DROP TABLE IF EXISTS `Route`;
/*!50001 DROP VIEW IF EXISTS `Route`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Route` AS SELECT 
 1 AS `id`,
 1 AS `date`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `State`
--

DROP TABLE IF EXISTS `State`;
/*!50001 DROP VIEW IF EXISTS `State`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `State` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `order`,
 1 AS `alertLevel`,
 1 AS `code`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Ticket`
--

DROP TABLE IF EXISTS `Ticket`;
/*!50001 DROP VIEW IF EXISTS `Ticket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Ticket` AS SELECT 
 1 AS `id`,
 1 AS `agencyFk`,
 1 AS `employeeFk`,
 1 AS `date`,
 1 AS `hour`,
 1 AS `clientFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `TicketState`
--

DROP TABLE IF EXISTS `TicketState`;
/*!50001 DROP VIEW IF EXISTS `TicketState`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `TicketState` AS SELECT 
 1 AS `id`,
 1 AS `ticketFk`,
 1 AS `stateFk`,
 1 AS `employeeFk`,
 1 AS `updated`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Vehicle`
--

DROP TABLE IF EXISTS `Vehicle`;
/*!50001 DROP VIEW IF EXISTS `Vehicle`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Vehicle` AS SELECT 
 1 AS `id`,
 1 AS `numberPlate`,
 1 AS `tradeMark`,
 1 AS `model`,
 1 AS `companyFk`,
 1 AS `warehouseFk`,
 1 AS `description`,
 1 AS `m3`,
 1 AS `isActive`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Warehouse`
--

DROP TABLE IF EXISTS `Warehouse`;
/*!50001 DROP VIEW IF EXISTS `Warehouse`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Warehouse` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `tpv`,
 1 AS `inventory`,
 1 AS `isManaged`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `WarehouseAlias`
--

DROP TABLE IF EXISTS `WarehouseAlias`;
/*!50001 DROP VIEW IF EXISTS `WarehouseAlias`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `WarehouseAlias` AS SELECT 
 1 AS `id`,
 1 AS `name`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Worker`
--

DROP TABLE IF EXISTS `Worker`;
/*!50001 DROP VIEW IF EXISTS `Worker`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Worker` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `surname`,
 1 AS `userFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `Zone`
--

DROP TABLE IF EXISTS `Zone`;
/*!50001 DROP VIEW IF EXISTS `Zone`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `Zone` AS SELECT 
 1 AS `id`,
 1 AS `name`,
 1 AS `printingOrder`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `user`
--

DROP TABLE IF EXISTS `user`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `realm` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `username` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  `password` varchar(512) CHARACTER SET utf8 NOT NULL,
  `email` varchar(512) CHARACTER SET utf8 NOT NULL,
  `emailVerified` tinyint(1) DEFAULT NULL,
  `verificationToken` varchar(512) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=50054 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'salix'
--

--
-- Dumping routines for database 'salix'
--
/*!50003 DROP PROCEDURE IF EXISTS `production_control_source` */;
/*!50003 SET @saved_cs_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 `production_control_source`(idWarehouse INT, scopeDays TINYINT)
BEGIN
    CALL vn2008.production_control_source(idWarehouse, scopeDays);
    
	SET @id = 0;
    
    DROP TEMPORARY TABLE IF EXISTS tmp.production;
	CREATE TEMPORARY TABLE tmp.production
    ENGINE = MEMORY
		SELECT
				@id := @id+1 id,
				p.Id_Ticket ticketFk,
				p.Id_Cliente clientFk,
				p.Alias client,
				p.Fecha `date`,
				p.Hora hour,
				p.POBLACION city,
				p.PROVINCIA province,
				p.province_id provinceFk,
				p.Agencia agency,
				p.agency_id agencyFk,
				p.lines,
				p.m3,
				p.problems,
				p.problem,
				p.state stateFk,
				t.Id_Trabajador workerfk,
				CONCAT(t.Nombre, ' ', t.Apellidos) worker, 
				tt.Id_Trabajador salesPersonFk,
				CONCAT(tt.Nombre, ' ', tt.Apellidos) salesPerson, 
				s.name state,
				p.Cajas boxes,
				p.Id_Ruta routeFk
			FROM tmp.production_buffer p
				JOIN vn2008.state s ON p.state = s.id
				JOIN vn2008.Trabajadores t ON p.CodigoTrabajador = t.CodigoTrabajador COLLATE utf8_unicode_ci
				JOIN vn2008.Trabajadores tt ON p.Comercial = tt.CodigoTrabajador COLLATE utf8_unicode_ci;
                
	DROP TEMPORARY TABLE tmp.production_buffer;
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: `hedera`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `hedera` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `hedera`;

--
-- Temporary view structure for view `address_view`
--

DROP TABLE IF EXISTS `address_view`;
/*!50001 DROP VIEW IF EXISTS `address_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `address_view` AS SELECT 
 1 AS `id`,
 1 AS `customer_id`,
 1 AS `warehouse_id`,
 1 AS `name`,
 1 AS `city`,
 1 AS `province_id`,
 1 AS `zip_code`,
 1 AS `consignee`,
 1 AS `default`,
 1 AS `type_id`,
 1 AS `specs`,
 1 AS `insurance`,
 1 AS `postage`,
 1 AS `active`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `androidUser`
--

DROP TABLE IF EXISTS `androidUser`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `androidUser` (
  `androidId` varchar(200) CHARACTER SET utf8 NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`userFk`,`androidId`),
  CONSTRAINT `androidUser_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `basket`
--

DROP TABLE IF EXISTS `basket`;
/*!50001 DROP VIEW IF EXISTS `basket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `basket` AS SELECT 
 1 AS `id`,
 1 AS `date_make`,
 1 AS `date_send`,
 1 AS `customer_id`,
 1 AS `delivery_method_id`,
 1 AS `agency_id`,
 1 AS `address_id`,
 1 AS `company_id`,
 1 AS `note`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `basketOrder`
--

DROP TABLE IF EXISTS `basketOrder`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `basketOrder` (
  `customerFk` int(11) NOT NULL,
  `orderFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`orderFk`,`customerFk`),
  UNIQUE KEY `customer_id` (`customerFk`),
  CONSTRAINT `basketOrder_ibfk_1` FOREIGN KEY (`orderFk`, `customerFk`) REFERENCES `order` (`id`, `customer_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `basketOrder_ibfk_2` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `basketOrder_ibfk_3` FOREIGN KEY (`customerFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `basket_defaults`
--

DROP TABLE IF EXISTS `basket_defaults`;
/*!50001 DROP VIEW IF EXISTS `basket_defaults`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `basket_defaults` AS SELECT 
 1 AS `address_id`,
 1 AS `agency_id`,
 1 AS `delivery_method`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `basket_item`
--

DROP TABLE IF EXISTS `basket_item`;
/*!50001 DROP VIEW IF EXISTS `basket_item`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `basket_item` AS SELECT 
 1 AS `id`,
 1 AS `order_id`,
 1 AS `warehouse_id`,
 1 AS `item_id`,
 1 AS `amount`,
 1 AS `price`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `browser`
--

DROP TABLE IF EXISTS `browser`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `browser` (
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Browser name in browscap',
  `version` float NOT NULL COMMENT 'Minimal version',
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of compatible web browsers and its version';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `config`
--

DROP TABLE IF EXISTS `config`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `config` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `defaultLang` char(2) CHARACTER SET utf8 NOT NULL COMMENT 'The default language if none is specified',
  `https` tinyint(3) unsigned NOT NULL COMMENT 'Wether to force de use of HTTPS',
  `cookieLife` smallint(5) unsigned NOT NULL COMMENT 'The cookies life, in days',
  `jwtKey` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The key used to encode/decode JWT tokens',
  `default_form` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Form loaded at web login',
  `restUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `testRestUri` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `image_host` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL,
  `image_dir` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Directory where images are allocated',
  `guest_user` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Guest user name',
  `guest_pass` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'Guest password, base64 encoded',
  `test_domain` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for beta website',
  `production_domain` varchar(150) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The address for production website',
  `pdfs_dir` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Directory where pdfs are allocated',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Global configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `contact`
--

DROP TABLE IF EXISTS `contact`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `contact` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `recipient` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `customer_view`
--

DROP TABLE IF EXISTS `customer_view`;
/*!50001 DROP VIEW IF EXISTS `customer_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `customer_view` AS SELECT 
 1 AS `user_id`,
 1 AS `name`,
 1 AS `email`,
 1 AS `mail`,
 1 AS `default_address`,
 1 AS `credit`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `imageCollection`
--

DROP TABLE IF EXISTS `imageCollection`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imageCollection` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `desc` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `maxWidth` int(10) unsigned NOT NULL,
  `maxHeight` int(10) unsigned NOT NULL,
  `schema` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `table` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `column` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `imageCollectionSize`
--

DROP TABLE IF EXISTS `imageCollectionSize`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imageCollectionSize` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `collectionFk` int(10) unsigned NOT NULL,
  `width` int(10) unsigned NOT NULL,
  `height` int(10) unsigned NOT NULL,
  `crop` tinyint(3) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `image_schema_id` (`collectionFk`),
  CONSTRAINT `imageCollectionSize_ibfk_1` FOREIGN KEY (`collectionFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `imageConfig`
--

DROP TABLE IF EXISTS `imageConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imageConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier',
  `maxSize` int(10) unsigned NOT NULL COMMENT 'Maximun size for uploaded images in MB',
  `useXsendfile` tinyint(4) NOT NULL COMMENT 'Whether to use the apache module XSendfile',
  `url` varchar(255) NOT NULL COMMENT 'Public URL where image are hosted',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COMMENT='Global image parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `imageFile`
--

DROP TABLE IF EXISTS `imageFile`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `imageFile` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `schemaFk` int(10) unsigned NOT NULL,
  `file` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `stamp` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `schema_id_file` (`schemaFk`,`file`),
  CONSTRAINT `imageFile_ibfk_1` FOREIGN KEY (`schemaFk`) REFERENCES `imageCollection` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=32793 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `invoice_view`
--

DROP TABLE IF EXISTS `invoice_view`;
/*!50001 DROP VIEW IF EXISTS `invoice_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `invoice_view` AS SELECT 
 1 AS `invoice_id`,
 1 AS `serial_num`,
 1 AS `issued`,
 1 AS `amount`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `language`
--

DROP TABLE IF EXISTS `language`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `language` (
  `code` varchar(10) CHARACTER SET utf8 NOT NULL,
  `name` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `orgName` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`code`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `link`
--

DROP TABLE IF EXISTS `link`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `link` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `image` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=36 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `location`
--

DROP TABLE IF EXISTS `location`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `location` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `lat` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
  `lng` varchar(12) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `address` varchar(75) COLLATE utf8_unicode_ci DEFAULT NULL,
  `postcode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `city` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `province` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `phone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `language` char(2) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=8 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mailConfig`
--

DROP TABLE IF EXISTS `mailConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT COMMENT 'Identifier',
  `host` varchar(255) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'localhost' COMMENT 'SMTP host',
  `port` smallint(6) NOT NULL DEFAULT '465' COMMENT 'SMTP port',
  `secure` tinyint(1) NOT NULL DEFAULT '1' COMMENT 'Wether to use a secure connection',
  `sender` varchar(255) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The sender mail address',
  `senderName` varchar(75) CHARACTER SET utf8 NOT NULL COMMENT 'The sender name',
  `user` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'SMTP user',
  `password` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'SMTP password, base64 encoded',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `menu`
--

DROP TABLE IF EXISTS `menu`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `menu` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `path` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `roleFk` int(10) unsigned NOT NULL,
  `parentFk` int(10) unsigned DEFAULT NULL,
  `displayOrder` tinyint(4) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `group_id` (`roleFk`),
  KEY `parent` (`parentFk`),
  CONSTRAINT `menu_ibfk_1` FOREIGN KEY (`roleFk`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=31 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `message`
--

DROP TABLE IF EXISTS `message`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `message` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `code` char(35) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `code` (`code`)
) ENGINE=MyISAM AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `metatag`
--

DROP TABLE IF EXISTS `metatag`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `metatag` (
  `id` int(11) NOT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `content` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `myAddress`
--

DROP TABLE IF EXISTS `myAddress`;
/*!50001 DROP VIEW IF EXISTS `myAddress`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myAddress` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `street`,
 1 AS `city`,
 1 AS `postalCode`,
 1 AS `provinceFk`,
 1 AS `nickname`,
 1 AS `isDefaultAddress`,
 1 AS `active`,
 1 AS `longitude`,
 1 AS `latitude`,
 1 AS `warehouseFk`,
 1 AS `agencyFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `myMenu`
--

DROP TABLE IF EXISTS `myMenu`;
/*!50001 DROP VIEW IF EXISTS `myMenu`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myMenu` AS SELECT 
 1 AS `id`,
 1 AS `path`,
 1 AS `description`,
 1 AS `parentFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `myTicket`
--

DROP TABLE IF EXISTS `myTicket`;
/*!50001 DROP VIEW IF EXISTS `myTicket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myTicket` AS SELECT 
 1 AS `id`,
 1 AS `clientFk`,
 1 AS `warehouseFk`,
 1 AS `shipped`,
 1 AS `landed`,
 1 AS `nickname`,
 1 AS `agencyModeFk`,
 1 AS `refFk`,
 1 AS `addressFk`,
 1 AS `isSigned`,
 1 AS `package`,
 1 AS `location`,
 1 AS `companyFk`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `myTicketRow`
--

DROP TABLE IF EXISTS `myTicketRow`;
/*!50001 DROP VIEW IF EXISTS `myTicketRow`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myTicketRow` AS SELECT 
 1 AS `id`,
 1 AS `itemFk`,
 1 AS `ticketFk`,
 1 AS `concept`,
 1 AS `quantity`,
 1 AS `price`,
 1 AS `discount`,
 1 AS `reserved`,
 1 AS `isPicked`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `myTpvTransaction`
--

DROP TABLE IF EXISTS `myTpvTransaction`;
/*!50001 DROP VIEW IF EXISTS `myTpvTransaction`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `myTpvTransaction` AS SELECT 
 1 AS `id`,
 1 AS `merchantFk`,
 1 AS `clientFk`,
 1 AS `receiptFk`,
 1 AS `amount`,
 1 AS `response`,
 1 AS `status`,
 1 AS `created`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `news`
--

DROP TABLE IF EXISTS `news`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `news` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `text` text COLLATE utf8_unicode_ci NOT NULL,
  `image` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `priority` tinyint(3) unsigned NOT NULL DEFAULT '3',
  `tag` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'new',
  `__date_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT 'Deprecated',
  `__user_id` int(10) NOT NULL COMMENT 'Deprecated',
  PRIMARY KEY (`id`),
  KEY `user` (`userFk`),
  KEY `tag` (`tag`),
  CONSTRAINT `news_ibfk_1` FOREIGN KEY (`userFk`) REFERENCES `account`.`account` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `news_ibfk_2` FOREIGN KEY (`tag`) REFERENCES `newsTag` (`name`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=12987 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `newsTag`
--

DROP TABLE IF EXISTS `newsTag`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `newsTag` (
  `name` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `order`
--

DROP TABLE IF EXISTS `order`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `order` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `date_send` date NOT NULL DEFAULT '0000-00-00',
  `customer_id` int(11) NOT NULL,
  `delivery_method_id` int(11) DEFAULT '3',
  `agency_id` int(11) DEFAULT '2',
  `address_id` int(11) DEFAULT NULL,
  `company_id` smallint(5) unsigned NOT NULL DEFAULT '442',
  `note` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `source_app` set('WEB','ANDROID','IOS','TPV','TABLET_VN','') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'TPV',
  `is_bionic` tinyint(1) NOT NULL DEFAULT '1',
  `confirmed` tinyint(1) NOT NULL DEFAULT '0',
  `date_make` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `first_row_stamp` datetime DEFAULT NULL,
  `confirm_date` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `address` (`address_id`),
  KEY `delivery_method` (`delivery_method_id`),
  KEY `agency` (`agency_id`),
  KEY `customer_id` (`customer_id`),
  KEY `company_id` (`company_id`),
  KEY `id` (`id`,`customer_id`),
  KEY `source_app` (`source_app`),
  KEY `confirmed` (`confirmed`),
  CONSTRAINT `order_ibfk_5` FOREIGN KEY (`address_id`) REFERENCES `vn2008`.`Consignatarios` (`id_consigna`) ON UPDATE CASCADE,
  CONSTRAINT `order_ibfk_8` FOREIGN KEY (`delivery_method_id`) REFERENCES `vn2008`.`Vistas` (`vista_id`) ON UPDATE CASCADE,
  CONSTRAINT `order_ibfk_9` FOREIGN KEY (`agency_id`) REFERENCES `vn2008`.`Agencias` (`Id_Agencia`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1209359 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderCheck`
--

DROP TABLE IF EXISTS `orderCheck`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderCheck` (
  `id` tinyint(1) unsigned NOT NULL AUTO_INCREMENT,
  `maxTime` time NOT NULL,
  `denySunday` tinyint(1) NOT NULL,
  `denyDay` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Conditions to check when an order is confirmed';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderCheckFestive`
--

DROP TABLE IF EXISTS `orderCheckFestive`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderCheckFestive` (
  `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `acceptOrders` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `date` (`date`)
) ENGINE=MyISAM AUTO_INCREMENT=14 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderCheckWday`
--

DROP TABLE IF EXISTS `orderCheckWday`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderCheckWday` (
  `weekday` tinyint(3) unsigned NOT NULL COMMENT '0 = Monday, 6 = Sunday',
  `maxTime` time NOT NULL,
  PRIMARY KEY (`weekday`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderConfig`
--

DROP TABLE IF EXISTS `orderConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderConfig` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `employeeFk` int(11) NOT NULL,
  `deliveryAgencyFk` int(11) NOT NULL,
  `guestMethod` varchar(45) CHARACTER SET utf8 NOT NULL,
  `guestAgencyFk` int(11) NOT NULL,
  `reserveTime` time NOT NULL,
  PRIMARY KEY (`id`),
  KEY `employee_id` (`employeeFk`),
  KEY `delivery_agency` (`deliveryAgencyFk`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `orderRow`
--

DROP TABLE IF EXISTS `orderRow`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderRow` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `orderFk` int(10) unsigned NOT NULL DEFAULT '0',
  `itemFk` int(11) NOT NULL DEFAULT '0',
  `warehouseFk` int(11) DEFAULT NULL,
  `shipment` date DEFAULT NULL,
  `amount` smallint(6) unsigned NOT NULL DEFAULT '0',
  `price` decimal(10,2) DEFAULT NULL,
  `rate` smallint(5) unsigned DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `saleFk` int(11) DEFAULT NULL COMMENT 'Deprecated',
  PRIMARY KEY (`id`),
  KEY `item` (`itemFk`),
  KEY `order_id` (`orderFk`),
  KEY `created` (`created`),
  KEY `warehouse_shipment` (`warehouseFk`,`shipment`),
  CONSTRAINT `orderRow_ibfk_2` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON UPDATE CASCADE,
  CONSTRAINT `orderRow_ibfk_3` FOREIGN KEY (`orderFk`) REFERENCES `order` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7531286 DEFAULT 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 `orderRowBeforeInsert`
	BEFORE INSERT ON `orderRow`
    FOR EACH ROW
BEGIN
	DECLARE vIsFirst BOOL;

	SELECT (first_row_stamp IS NULL) INTO vIsFirst  
		FROM `order` 
		WHERE id = NEW.orderFk;

	IF vIsFirst THEN
		UPDATE `order` SET first_row_stamp = NOW() 
			WHERE id = NEW.orderFk;
	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 `orderRowComponent`
--

DROP TABLE IF EXISTS `orderRowComponent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `orderRowComponent` (
  `rowFk` int(10) unsigned NOT NULL,
  `componentFk` int(11) NOT NULL,
  `price` decimal(12,4) NOT NULL,
  PRIMARY KEY (`rowFk`,`componentFk`),
  KEY `component_id` (`componentFk`),
  CONSTRAINT `orderRowComponent_ibfk_1` FOREIGN KEY (`rowFk`) REFERENCES `orderRow` (`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 view structure for view `order_basket`
--

DROP TABLE IF EXISTS `order_basket`;
/*!50001 DROP VIEW IF EXISTS `order_basket`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_basket` AS SELECT 
 1 AS `customer_id`,
 1 AS `order_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `order_component`
--

DROP TABLE IF EXISTS `order_component`;
/*!50001 DROP VIEW IF EXISTS `order_component`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_component` AS SELECT 
 1 AS `order_row_id`,
 1 AS `component_id`,
 1 AS `price`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `order_config`
--

DROP TABLE IF EXISTS `order_config`;
/*!50001 DROP VIEW IF EXISTS `order_config`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_config` AS SELECT 
 1 AS `id`,
 1 AS `employee_id`,
 1 AS `delivery_agency`,
 1 AS `guest_method`,
 1 AS `guest_agency`,
 1 AS `reserve_time`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `order_confirm_time`
--

DROP TABLE IF EXISTS `order_confirm_time`;
/*!50001 DROP VIEW IF EXISTS `order_confirm_time`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_confirm_time` AS SELECT 
 1 AS `date_make`,
 1 AS `source_app`,
 1 AS `customer_id`,
 1 AS `confirm_date`,
 1 AS `first_row_stamp`,
 1 AS `minutos`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `order_row`
--

DROP TABLE IF EXISTS `order_row`;
/*!50001 DROP VIEW IF EXISTS `order_row`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_row` AS SELECT 
 1 AS `id`,
 1 AS `order_id`,
 1 AS `item_id`,
 1 AS `warehouse_id`,
 1 AS `shipment`,
 1 AS `amount`,
 1 AS `price`,
 1 AS `rate`,
 1 AS `created`,
 1 AS `Id_Movimiento`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `order_row_view`
--

DROP TABLE IF EXISTS `order_row_view`;
/*!50001 DROP VIEW IF EXISTS `order_row_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_row_view` AS SELECT 
 1 AS `id`,
 1 AS `order_id`,
 1 AS `warehouse_id`,
 1 AS `item_id`,
 1 AS `amount`,
 1 AS `price2`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `order_view`
--

DROP TABLE IF EXISTS `order_view`;
/*!50001 DROP VIEW IF EXISTS `order_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `order_view` AS SELECT 
 1 AS `id`,
 1 AS `date_make`,
 1 AS `date_send`,
 1 AS `customer_id`,
 1 AS `delivery_method_id`,
 1 AS `agency_id`,
 1 AS `note`,
 1 AS `address_id`,
 1 AS `company_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `restPriv`
--

DROP TABLE IF EXISTS `restPriv`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `restPriv` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `methodPath` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `role` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `role` (`role`),
  CONSTRAINT `restPriv_ibfk_1` FOREIGN KEY (`role`) REFERENCES `account`.`role` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `shelf`
--

DROP TABLE IF EXISTS `shelf`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shelf` (
  `id` int(10) unsigned NOT NULL,
  `name` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `nTrays` tinyint(3) unsigned NOT NULL,
  `trayheight` mediumint(8) unsigned NOT NULL,
  `topTrayHeight` mediumint(8) unsigned NOT NULL,
  `width` mediumint(8) unsigned NOT NULL,
  `depth` mediumint(8) unsigned NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Dimensiones de las estanterias';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `shelfConfig`
--

DROP TABLE IF EXISTS `shelfConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `shelfConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(25) COLLATE utf8_unicode_ci NOT NULL,
  `namePrefix` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `warehouse` smallint(5) unsigned NOT NULL,
  `family` smallint(5) unsigned NOT NULL,
  `shelf` int(10) unsigned NOT NULL,
  `maxAmount` smallint(5) unsigned DEFAULT NULL,
  `showPacking` tinyint(4) NOT NULL,
  `stack` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `shelf_id` (`shelf`),
  KEY `family_id` (`family`),
  KEY `warehouse_id` (`warehouse`),
  CONSTRAINT `shelfConfig_ibfk_1` FOREIGN KEY (`family`) REFERENCES `vn2008`.`Tipos` (`tipo_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `shelfConfig_ibfk_2` FOREIGN KEY (`shelf`) REFERENCES `shelf` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `shelfConfig_ibfk_3` FOREIGN KEY (`warehouse`) REFERENCES `vn2008`.`warehouse` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `social`
--

DROP TABLE IF EXISTS `social`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `social` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `link` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `icon` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `priority` tinyint(3) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `priority` (`priority`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `survey`
--

DROP TABLE IF EXISTS `survey`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `survey` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `question` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `surveyAnswer`
--

DROP TABLE IF EXISTS `surveyAnswer`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `surveyAnswer` (
  `id` int(10) unsigned NOT NULL,
  `surveyFk` int(10) unsigned NOT NULL,
  `answer` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
  `votes` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `survey` (`surveyFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `surveyVote`
--

DROP TABLE IF EXISTS `surveyVote`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `surveyVote` (
  `surveyFk` int(10) unsigned NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`surveyFk`,`userFk`),
  KEY `surveyVote_ibfk_2` (`userFk`),
  CONSTRAINT `surveyVote_ibfk_1` FOREIGN KEY (`surveyFk`) REFERENCES `survey` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `surveyVote_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `ticket_row_view`
--

DROP TABLE IF EXISTS `ticket_row_view`;
/*!50001 DROP VIEW IF EXISTS `ticket_row_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticket_row_view` AS SELECT 
 1 AS `id`,
 1 AS `item_id`,
 1 AS `ticket_id`,
 1 AS `concept`,
 1 AS `amount`,
 1 AS `price`,
 1 AS `fixed`,
 1 AS `discount`,
 1 AS `cost`,
 1 AS `reserved`,
 1 AS `ok`*/;
SET character_set_client = @saved_cs_client;

--
-- Temporary view structure for view `ticket_view`
--

DROP TABLE IF EXISTS `ticket_view`;
/*!50001 DROP VIEW IF EXISTS `ticket_view`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `ticket_view` AS SELECT 
 1 AS `id`,
 1 AS `customer_id`,
 1 AS `warehouse_id`,
 1 AS `date`,
 1 AS `delivery`,
 1 AS `alias`,
 1 AS `agency_id`,
 1 AS `note`,
 1 AS `invoice`,
 1 AS `address_id`,
 1 AS `employee_id`,
 1 AS `comments`,
 1 AS `signed`,
 1 AS `packages`,
 1 AS `location`,
 1 AS `hour`,
 1 AS `blocked`,
 1 AS `solution`,
 1 AS `company_id`,
 1 AS `type`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `tpvConfig`
--

DROP TABLE IF EXISTS `tpvConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `currency` smallint(5) unsigned NOT NULL,
  `terminal` tinyint(3) unsigned NOT NULL,
  `transactionType` tinyint(3) unsigned NOT NULL,
  `maxAmount` int(10) unsigned DEFAULT NULL,
  `employeeFk` int(10) NOT NULL,
  `url` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT 'The bank web service URL for production environment',
  `testMode` tinyint(3) unsigned NOT NULL DEFAULT '0' COMMENT 'Whether test mode is enabled',
  `testUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank web service URL for test environment',
  `testKey` varchar(50) CHARACTER SET utf8 DEFAULT NULL COMMENT 'The bank secret key for test environment',
  `merchantUrl` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `employee_id` (`employeeFk`),
  CONSTRAINT `employee_id` FOREIGN KEY (`employeeFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tpvError`
--

DROP TABLE IF EXISTS `tpvError`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvError` (
  `code` char(7) COLLATE utf8_unicode_ci NOT NULL,
  `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT=' List of possible TPV errors';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tpvImapConfig`
--

DROP TABLE IF EXISTS `tpvImapConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvImapConfig` (
  `id` tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
  `host` varchar(150) COLLATE utf8_unicode_ci NOT NULL,
  `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `pass` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `cleanPeriod` varchar(15) CHARACTER SET utf8 NOT NULL,
  `successFolder` varchar(150) CHARACTER SET utf8 DEFAULT NULL,
  `errorFolder` varchar(150) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='IMAP configuration parameters for virtual TPV';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tpvMerchant`
--

DROP TABLE IF EXISTS `tpvMerchant`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvMerchant` (
  `id` int(10) unsigned NOT NULL COMMENT 'Merchant identifier',
  `description` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Small description',
  `companyFk` smallint(6) unsigned DEFAULT NULL COMMENT 'Company associated with the merchant',
  `bankFk` int(10) NOT NULL COMMENT 'The bank where merchant receipts are created',
  `secretKey` varchar(50) COLLATE utf8_unicode_ci NOT NULL COMMENT 'The merchant secret key to sign transactions',
  PRIMARY KEY (`id`),
  KEY `bank_id` (`bankFk`),
  KEY `company_id` (`companyFk`),
  KEY `id` (`id`,`companyFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV providers';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tpvMerchantEnable`
--

DROP TABLE IF EXISTS `tpvMerchantEnable`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvMerchantEnable` (
  `merchantFk` int(10) unsigned NOT NULL DEFAULT '0',
  `companyFk` smallint(6) unsigned NOT NULL,
  PRIMARY KEY (`merchantFk`,`companyFk`),
  UNIQUE KEY `company_id` (`companyFk`),
  CONSTRAINT `tpvMerchantEnable_ibfk_1` FOREIGN KEY (`merchantFk`, `companyFk`) REFERENCES `tpvMerchant` (`id`, `companyFk`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Virtual TPV enabled providers';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tpvResponse`
--

DROP TABLE IF EXISTS `tpvResponse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvResponse` (
  `id` smallint(5) unsigned NOT NULL,
  `message` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='List of possible TPV reponses';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tpvTransaction`
--

DROP TABLE IF EXISTS `tpvTransaction`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tpvTransaction` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `merchantFk` int(10) unsigned NOT NULL,
  `clientFk` int(11) NOT NULL,
  `receiptFk` int(11) DEFAULT NULL,
  `amount` int(10) unsigned NOT NULL,
  `response` smallint(5) unsigned DEFAULT NULL COMMENT 'Status notified by bank: NULL if no notification, 0 if success, error otherwise',
  `errorCode` char(7) COLLATE utf8_unicode_ci DEFAULT NULL,
  `status` enum('started','ok','ko') COLLATE utf8_unicode_ci NOT NULL DEFAULT 'started',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `merchant_id` (`merchantFk`),
  KEY `receipt_id` (`receiptFk`),
  KEY `user_id` (`clientFk`),
  KEY `response` (`response`),
  KEY `error_code` (`errorCode`),
  CONSTRAINT `receipt_id` FOREIGN KEY (`receiptFk`) REFERENCES `vn2008`.`Recibos` (`Id`) ON DELETE SET NULL ON UPDATE CASCADE,
  CONSTRAINT `tpvTransaction_ibfk_1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `tpvTransaction_ibfk_2` FOREIGN KEY (`merchantFk`) REFERENCES `tpvMerchant` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=181005 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Transactions realized through the virtual TPV';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `userSession`
--

DROP TABLE IF EXISTS `userSession`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `userSession` (
  `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `lastUpdate` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `ssid` char(64) COLLATE utf8_unicode_ci DEFAULT NULL,
  `data` text COLLATE utf8_unicode_ci,
  `userVisit` int(10) unsigned DEFAULT NULL,
  UNIQUE KEY `ssid` (`ssid`),
  KEY `userVisit` (`userVisit`),
  KEY `lastUpdate` (`lastUpdate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Temporary view structure for view `user_android`
--

DROP TABLE IF EXISTS `user_android`;
/*!50001 DROP VIEW IF EXISTS `user_android`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `user_android` AS SELECT 
 1 AS `android_id`,
 1 AS `user_id`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `visit`
--

DROP TABLE IF EXISTS `visit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visit` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `firstAgent` int(10) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `firstAgent` (`firstAgent`),
  CONSTRAINT `visit_ibfk_1` FOREIGN KEY (`firstAgent`) REFERENCES `visitAgent` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1112123 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `visitAccess`
--

DROP TABLE IF EXISTS `visitAccess`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visitAccess` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `agent` int(10) unsigned NOT NULL,
  `stamp` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `ip` int(10) unsigned DEFAULT NULL,
  `referer` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `visit_access_idx_agent` (`agent`),
  KEY `stamp` (`stamp`),
  CONSTRAINT `visitAccess_ibfk_1` FOREIGN KEY (`agent`) REFERENCES `visitAgent` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2356472 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `visitAgent`
--

DROP TABLE IF EXISTS `visitAgent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visitAgent` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `visit` int(10) unsigned NOT NULL,
  `firstAccess` int(10) unsigned DEFAULT NULL,
  `platform` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `browser` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL,
  `version` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `javascript` tinyint(3) unsigned DEFAULT NULL,
  `cookies` tinyint(3) unsigned DEFAULT NULL,
  `agent` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `visit_id` (`visit`),
  KEY `firstAccess` (`firstAccess`),
  CONSTRAINT `visitAgent_ibfk_1` FOREIGN KEY (`visit`) REFERENCES `visit` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `visitAgent_ibfk_2` FOREIGN KEY (`firstAccess`) REFERENCES `visitAccess` (`id`) ON DELETE SET NULL ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1627507 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `visitUser`
--

DROP TABLE IF EXISTS `visitUser`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `visitUser` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `access` int(10) unsigned NOT NULL,
  `user` int(10) unsigned DEFAULT NULL,
  `stamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `access_id` (`access`),
  KEY `date_time` (`stamp`),
  KEY `user_id` (`user`),
  CONSTRAINT `visitUser_ibfk_1` FOREIGN KEY (`access`) REFERENCES `visitAccess` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2309412 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'hedera'
--

--
-- Dumping routines for database 'hedera'
--
/*!50003 DROP FUNCTION IF EXISTS `basketGetId` */;
/*!50003 SET @saved_cs_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 `basketGetId`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE v_order INT;
    
    SELECT order_id INTO v_order FROM order_basket
		WHERE customer_id = account.userGetId();

	RETURN v_order;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `clientGetDebt` */;
/*!50003 SET @saved_cs_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 `clientGetDebt`(vDate DATE) RETURNS decimal(10,2)
BEGIN
/**
 * Calcula el saldo del cliente actual.
 *
 * @return Saldo del cliente
 */
	RETURN vn.clientGetDebt(account.userGetId(), 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 FUNCTION IF EXISTS `invoiceGetPath` */;
/*!50003 SET @saved_cs_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 `invoiceGetPath`(vInvoice INT) RETURNS varchar(255) CHARSET utf8
BEGIN
	DECLARE vIssued DATE;
	DECLARE vSerial VARCHAR(15);

	SELECT issued, ref 
		INTO vIssued, vSerial
		FROM vn.invoiceOut WHERE id = vInvoice;

	RETURN CONCAT_WS('/'
		,'invoice'
		,YEAR(vIssued)
		,MONTH(vIssued)
		,DAY(vIssued)
		,CONCAT(YEAR(vIssued), vSerial, '.pdf')
	);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `orderGetTotal` */;
/*!50003 SET @saved_cs_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 `orderGetTotal`(vOrder INT) RETURNS decimal(10,2)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * Obtiene el total de un pedido con el IVA y el recargo de
 * equivalencia incluidos.
 *
 * @param vOrder El identificador del pedido
 * @return El total del pedido
 */
	DECLARE vTotal DECIMAL(10,2);

	CALL orderGetTax (vOrder);

	SELECT SUM(taxBase) + SUM(tax) + SUM(equalizationTax) INTO vTotal
		FROM tmp.orderTax;

	DROP TEMPORARY TABLE tmp.orderTax;
	
	RETURN vTotal;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `order_get_total` */;
/*!50003 SET @saved_cs_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 `order_get_total`(vOrder INT) RETURNS decimal(10,2)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * Obtiene el total de un pedido con el IVA y el recargo de
 * equivalencia incluidos.
 *
 * @deprecated Use function orderGetTotal() instead
 *
 * @param vOrder El identificador del pedido
 * @return El total del pedido
 */
	RETURN orderGetTotal (vOrder);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `userCheckRestPriv` */;
/*!50003 SET @saved_cs_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 `userCheckRestPriv`(vMethodPath VARCHAR(255)) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN
/**
 * Comprueba si el usuario actual tiene permiso para ejecutar
 * un servicio REST.
 *
 * @param vMethodPath Ruta del servicio REST a ejecutar
 * @return %TRUE si tiene permisos, %FALSE en caso contrario
 **/
	DECLARE vRole INT DEFAULT NULL;
    
    SELECT role INTO vRole FROM restPriv
		WHERE methodPath = vMethodPath;
        
	RETURN vRole IS NULL
		OR account.userHasRoleId (vRole);
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 `basketAddItem` */;
/*!50003 SET @saved_cs_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 `basketAddItem`(
	vWarehouse INT,
    vItem INT,
    vAmount INT)
BEGIN
	DECLARE vOrder INT;
	DECLARE vRow INT;
    DECLARE vAdd INT;
	DECLARE vAvailable INT;
	DECLARE vDone BOOL;
	DECLARE vGrouping INT;
    DECLARE vRate INT;
    DECLARE vShipment DATE;
	DECLARE vPrice DECIMAL(10,2);
	
	DECLARE cur CURSOR FOR
		SELECT grouping, price, rate
			FROM tmp.bionic_price
			WHERE warehouse_id = vWarehouse
				AND item_id = vItem
			ORDER BY grouping DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	CALL bionic_from_item (vItem);

	START TRANSACTION;

    SET vOrder = basketGetId();
    
    SELECT Fecha_envio INTO vShipment
		FROM tmp.travel_tree
        WHERE warehouse_id = vWarehouse;
    
	SELECT available INTO vAvailable
		FROM tmp.bionic_lot
		WHERE warehouse_id = vWarehouse
			AND item_id = vItem;
			
	IF vAmount > vAvailable
	THEN
		CALL util.throw ('ORDER_ROW_UNAVAILABLE');
	END IF;
	
    OPEN cur;
    
	l: LOOP
		SET vDone = FALSE;
		FETCH cur INTO vGrouping, vPrice, vRate;

		IF vDone THEN
			LEAVE l;
		END IF;
        
        SET vAdd = vAmount - MOD(vAmount, vGrouping);
        SET vAmount = vAmount - vAdd;

		IF vAdd = 0 THEN
			ITERATE l;
		END IF;

		INSERT INTO order_row SET
			order_id = vOrder,
            item_id = vItem,
            warehouse_id = vWarehouse,
            shipment = vShipment,
            rate = vRate,
            amount = vAdd,
            price = vPrice;
			
		SET vRow = LAST_INSERT_ID();

		INSERT INTO order_component (order_row_id, component_id, price)
			SELECT vRow, c.component_id, c.cost
				FROM tmp.bionic_component c
					JOIN bi.tarifa_componentes t
						ON t.Id_Componente = c.component_id
						AND (t.tarifa_class IS NULL OR t.tarifa_class = vRate)
				WHERE c.warehouse_id = vWarehouse
					AND c.item_id = vItem;
	END LOOP;
    
    CLOSE cur;				
	COMMIT;
    
    CALL vn2008.bionic_free ();
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 `basketCheck` */;
/*!50003 SET @saved_cs_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 `basketCheck`()
BEGIN
/**
 * Comprueba que la cesta esta creada y que su configuración es
 * correcta. Si la configuración es correcta pero lleva mucho
 * tiempo creada actualiza los precios y cantidades de los artículos.
 *
 * @select El id del pedido y el estado de la cesta
 */
	DECLARE vOrder INT;
	DECLARE vCreated DATETIME;
	DECLARE vStatus VARCHAR(15) DEFAULT 'OK';

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vStatus = 'NOT_EXISTS';
	DECLARE CONTINUE HANDLER FOR SQLEXCEPTION SET vStatus = 'BAD_CONFIG';

	SELECT id, date_make
		INTO vOrder, vCreated
		FROM basket;

	IF vStatus = 'OK'
	THEN
		CALL orderCheckConfig (vOrder);
		
		IF vStatus = 'OK' AND vCreated < TIMESTAMPADD(DAY, -1, NOW())
		THEN
			CALL orderUpdate (vOrder);
			SET vStatus = 'UPDATED';
		END IF;
	END IF;

	SELECT vStatus stat;
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 `basketConfigure` */;
/*!50003 SET @saved_cs_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 `basketConfigure`(
	vDelivery DATE,
    vDeliveryMethod VARCHAR(45),
    vAgency INT,
    vAddress INT)
BEGIN
/**
 * Configura la cesta de la compra utilizando los parámetros 
 * pasados. Si los parámetros no son válidos devuelve un error.
 *
 * @param vDelivery Fecha de recogida
 * @param vAgency Id de la agencia
 * @param vAddress Id de dirección de envío, @NULL si es recogida
 */
	DECLARE vOrder INT;
    DECLARE vCompany INT;
	DECLARE vDeliveryMethodId INT;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vOrder = NULL;
	DECLARE EXIT HANDLER FOR SQLSTATE '45000'
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	SELECT id INTO vDeliveryMethodId
		FROM vn.deliveryMethod
			WHERE code = vDeliveryMethod;
			
	IF vDeliveryMethod = 'DELIVERY'
	THEN
		SELECT delivery_agency INTO vAgency
			FROM order_config;
	END IF;

	IF vDeliveryMethod = 'PICKUP' AND vAddress IS NULL
	THEN
		SELECT default_address INTO vAddress
			FROM customer_view;
	END IF;
        
	SET vOrder = basketGetId();

	IF vOrder IS NULL
	THEN
		SELECT empresa_id INTO vCompany
			FROM vn2008.Clientes_empresa
			WHERE Id_Cliente = account.userGetId()
				AND CURDATE() BETWEEN fecha_ini AND fecha_fin
			LIMIT 1;

		INSERT INTO `order`
			SET
				customer_id = account.userGetId(),
				date_send = vDelivery,
				delivery_method_id = vDeliveryMethodId,
				agency_id = vAgency,
				address_id = vAddress,
                source_app = 'WEB',
                company_id = IFNULL(vCompany, 442);

		SET vOrder = LAST_INSERT_ID();
        
        INSERT INTO order_basket SET
			customer_id = account.userGetId(),
            order_id = vOrder;
	ELSE
		UPDATE `order`
			SET
				date_send = vDelivery,
				delivery_method_id = vDeliveryMethodId,
				agency_id = vAgency,
				address_id = vAddress
			WHERE
				id = vOrder;
                
		CALL orderUpdate (vOrder);
	END IF;

	CALL orderCheckConfig (vOrder);

	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `basketConfigureForGuest` */;
/*!50003 SET @saved_cs_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 `basketConfigureForGuest`()
BEGIN
    DECLARE vMethod VARCHAR(45);
    DECLARE vAgency INT;
    
    SELECT guest_method, guest_agency
		INTO vMethod, vAgency
        FROM order_config
        LIMIT 1;
    
    CALL basketConfigure (CURDATE(), vMethod, vAgency, NULL);
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 `basketConfirm` */;
/*!50003 SET @saved_cs_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 `basketConfirm`()
BEGIN
	DECLARE vOrder INT DEFAULT basketGetId ();

	IF vOrder IS NOT NULL
    THEN
		CALL order_confirm_bionic (vOrder);
		
		DELETE FROM order_basket
			WHERE order_id = vOrder;
	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 `basketGetTax` */;
/*!50003 SET @saved_cs_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 `basketGetTax`()
    READS SQL DATA
BEGIN
/**
 * Returns the taxes for the current client basket.
 *
 * @treturn tmp.orderTax
 */
	CALL orderGetTax (basketGetId());
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 `bionic_calc` */;
/*!50003 SET @saved_cs_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 `bionic_calc`()
BEGIN
	DECLARE v_date DATE;
	DECLARE v_address INT;
	DECLARE v_agency INT;
    
    SELECT date_send, address_id, agency_id
    INTO v_date, v_address, v_agency
		FROM basket;

	CALL vn2008.bionic_calc (v_date, v_address, v_agency);

	IF account.userGetName () = 'visitor'
    THEN
		DROP TEMPORARY TABLE tmp.bionic_component;
        UPDATE tmp.bionic_item SET price = NULL;
	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 `bionic_from_basket` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_basket`()
BEGIN
	DECLARE v_order INT;
	DECLARE v_date DATE;
	DECLARE v_address INT;
	DECLARE v_agency INT;
    
    SELECT id, date_send, address_id, agency_id
		INTO v_order, v_date, v_address, v_agency
		FROM basket;
        
	CALL vn2008.bionic_from_order (v_date, v_address, v_agency, v_order);
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 `bionic_from_item` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `bionic_from_item`(v_item INT)
BEGIN
	DECLARE v_date DATE;
	DECLARE v_address INT;
	DECLARE v_agency INT;
    
    SELECT date_send, address_id, agency_id
    INTO v_date, v_address, v_agency
		FROM basket;

	CALL vn2008.bionic_from_item (v_date, v_address, v_agency, v_item);
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 `catalogGetAvailable` */;
/*!50003 SET @saved_cs_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 `catalogGetAvailable`()
BEGIN
/**
 * Gets the available items list that meets the tag filter.
 *
 * @table tItems
 */
    CALL itemGetAvailable;
    
    DELETE t FROM tItems t
		JOIN tmp.itemAvailable a ON a.id = t.id
        WHERE a.id IS NULL;
        
	DROP TEMPORARY TABLE tmp.itemAvailable;
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 `catalogGetItems` */;
/*!50003 SET @saved_cs_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 `catalogGetItems`()
BEGIN
/**
 * Returns the list of items.
 *
 * @table tItems The list of items
 * @select The list of items
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.bionic_calc;
	CREATE TEMPORARY TABLE tmp.bionic_calc
			(INDEX (item_id))
			ENGINE = MEMORY
			SELECT id item_id FROM tItems;
 
	CALL bionic_calc ();
	DROP TEMPORARY TABLE tmp.bionic_calc;

	SELECT i.id, i.name, i.description, i.category, i.size, i.image, i.inkFk,
			IF(i.stems > 1, i.stems, NULL) stems, b.available, b.price, b.producer,
            a.tag1, a.val1, a.tag2, a.val2, a.tag3, a.val3
		FROM tmp.bionic_item b
			JOIN vn.item i ON i.id = b.item_id
            LEFT JOIN vn.itemTagArranged a ON a.itemFk = i.id
			LEFT JOIN vn.producer p ON p.id = i.producerFk
		WHERE b.available > 0
		ORDER BY i.relevancy DESC, i.name, i.size
		LIMIT 40;
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 `catalogGetTags` */;
/*!50003 SET @saved_cs_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 `catalogGetTags`(vLimit INT)
BEGIN
/**
 * Returns the main tags for a list of items.
 *
 * @table tItems The list of items
 * @select The main tags for the passed items
 */
    CALL catalogGetAvailable;

	DROP TEMPORARY TABLE IF EXISTS tTags;
	CREATE TEMPORARY TABLE tTags
		(INDEX (tagFk))
		ENGINE = MEMORY
		SELECT it.tagFk, SUM(it.priority) priority
			FROM vn.itemTag it
				JOIN tItems i ON i.id = it.itemFk
			GROUP BY tagFk
			LIMIT vLimit;

	SELECT l.id, l.name
		FROM tTags t 
			JOIN vn.tagL10n l ON l.id = t.tagFk
		ORDER BY priority DESC;

	DROP TEMPORARY TABLE tTags;
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 `catalogGetTagValues` */;
/*!50003 SET @saved_cs_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 `catalogGetTagValues`(vTag INT)
BEGIN
/**
 * Returns the list of available values for a tag and a list of items.
 *
 * @table tItems The list of items
 * @param vTag The tag identifier
 * @select The list of available tags
 */
    CALL catalogGetAvailable;

	SELECT DISTINCT it.value
		FROM vn.itemTag it
			JOIN tItems i ON i.id = it.itemFk
		WHERE it.tagFk = vTag
        ORDER BY value
        LIMIT 200;
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 `itemAllocator` */;
/*!50003 SET @saved_cs_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 `itemAllocator`(
	 vWh TINYINT
	,vDate DATE
    ,vType INT
    ,vPrefix VARCHAR(255)
    ,vUseIds BOOLEAN
)
BEGIN
	DECLARE vPrefixLen SMALLINT;
	DECLARE vFilter VARCHAR(255) DEFAULT NULL;
	DECLARE vDateInv DATE DEFAULT vn2008.date_inv();

	SET vPrefixLen = LENGTH(vPrefix);
    
    IF vPrefix IS NOT NULL AND vPrefixLen > 0
    THEN
		SET vFilter = CONCAT(vPrefix, '%');
        SET vPrefixLen = vPrefixLen + 1;
	END IF;

	DROP TEMPORARY TABLE IF EXISTS filter;
    CREATE TEMPORARY TABLE filter
	(INDEX (item_id))
	ENGINE = MEMORY
	SELECT Id_Article item_id FROM vn2008.Articles
		WHERE tipo_id = vType
			AND (vFilter IS NULL OR Article LIKE vFilter);

	DROP TEMPORARY TABLE IF EXISTS current_stock;
	CREATE TEMPORARY TABLE current_stock
	(INDEX (item_id))
	ENGINE = MEMORY
	SELECT item_id, SUM(Cantidad) amount FROM
	(
		SELECT Id_Article item_id, Cantidad 
			FROM vn2008.Compres c
			JOIN vn2008.Entradas e USING(Id_Entrada)
			JOIN vn2008.travel t ON t.id = e.travel_id
				WHERE landing BETWEEN vDateInv AND vDate
					AND warehouse_id = vWh
					AND NOT Redada
		UNION ALL
		SELECT Id_Article, -Cantidad
			FROM vn2008.Compres c
			JOIN vn2008.Entradas e USING(Id_Entrada)
			JOIN vn2008.travel t ON t.id = e.travel_id
				WHERE shipment BETWEEN vDateInv AND CURDATE()
					AND warehouse_id_out = vWh
					AND NOT Redada
					AND delivered
		UNION ALL
		SELECT m.Id_Article, -m.Cantidad
			FROM vn2008.Movimientos m
			JOIN vn2008.Tickets t USING(Id_Ticket)
            JOIN vn.ticketState s ON s.ticket = t.Id_Ticket
				WHERE t.Fecha BETWEEN vDateInv AND CURDATE()
					AND t.warehouse_id = vWh
                    AND (t.Etiquetasemitidas OR s.alertLevel = 3)
	) t
	GROUP BY item_id
		HAVING amount > 0;

	DROP TEMPORARY TABLE IF EXISTS tmp;
	CREATE TEMPORARY TABLE tmp
	(INDEX (item_id))
	ENGINE = MEMORY
	SELECT * FROM
	(
		SELECT c.Id_Article item_id, c.Id_Compra id, c.Id_Cubo, c.packing
			FROM vn2008.Compres c
			JOIN vn2008.Entradas e USING(Id_Entrada)
			JOIN vn2008.travel t ON t.id = e.travel_id
				WHERE t.landing BETWEEN vDateInv AND vDate
					AND c.Novincular = FALSE
					AND c.Tarifa2 >= 0
					AND Id_Cubo IS NOT NULL
				ORDER BY t.warehouse_id = 1 DESC, t.landing DESC
	) t GROUP BY item_id;

	DROP TEMPORARY TABLE IF EXISTS result;
	CREATE TEMPORARY TABLE result
	ENGINE = MEMORY
	SELECT a.Id_Article, IF(vPrefixLen > 0, SUBSTRING(a.Article, vPrefixLen), a.Article) Article,
    t.packing, CEIL(s.amount / t.packing) etiquetas, t.Id_Cubo, IF(c.z > 0, c.z, 0) z, c.x, c.y, a.Nicho
		FROM vn2008.Articles a
			JOIN filter f ON f.item_id = a.Id_Article 
			JOIN current_stock s ON s.item_id = a.Id_Article
			LEFT JOIN tmp t ON t.item_id = a.Id_Article
			LEFT JOIN vn2008.Cubos c ON c.Id_Cubo = t.Id_Cubo
		WHERE CEIL(s.amount / t.packing) > 0
			AND c.box;
            
	IF vUseIds
	THEN
		SELECT * FROM result
			ORDER BY Id_Article;
	ELSE
		SELECT * FROM result
			ORDER BY Article, packing;
	END IF;

	DROP TEMPORARY TABLE
		filter,
		current_stock,
		tmp,
        result;
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 `itemGetAvailable` */;
/*!50003 SET @saved_cs_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 `itemGetAvailable`()
BEGIN
/**
 * Gets the available items list.
 *
 * @table tmp.itemAvailable
 */  
	DECLARE vDelivery DATE;
	DECLARE vAddress INT;
	DECLARE vAgency INT;
    
    SELECT date_send, address_id, agency_id
    INTO vDelivery, vAddress, vAgency
		FROM basket;
  
	CALL vn2008.bionic_available_ (vDelivery, vAddress, vAgency);

	DROP TEMPORARY TABLE IF EXISTS tmp.itemAvailable;
	CREATE TEMPORARY TABLE tmp.itemAvailable
		(INDEX (id))
        ENGINE = MEMORY
		SELECT c.item_id id
			FROM cache.available c
				JOIN vn2008.t_bionic_available a ON c.calc_id = a.calc_id
			WHERE c.available > 0
			GROUP BY c.item_id;

	DROP TEMPORARY TABLE vn2008.t_bionic_available;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_available` */;
/*!50003 SET @saved_cs_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              = '' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_available`()
BEGIN
/**
 * Genera una tabla con los ids de los articulos disponibles. 
 *
 * @table tmp.item_available
 **/  
	DECLARE v_delivery DATE;
	DECLARE v_address INT;
	DECLARE v_agency INT;
    
    SELECT date_send, address_id, agency_id
    INTO v_delivery, v_address, v_agency
		FROM basket;
  
	CALL vn2008.bionic_available_ (v_delivery, v_address, v_agency);

	DROP TEMPORARY TABLE IF EXISTS tmp.item_available;
	CREATE TEMPORARY TABLE tmp.item_available
		(INDEX (item_id))
        ENGINE = MEMORY
		SELECT c.item_id
		FROM `cache`.available c
			JOIN vn2008.t_bionic_available a ON c.calc_id = a.calc_id
		WHERE c.available > 0
        GROUP BY c.item_id;

	DROP TEMPORARY TABLE vn2008.t_bionic_available;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `item_list` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `item_list`(v_warehouse SMALLINT, v_shipping DATE, v_realm INT, v_rate TINYINT)
BEGIN
	DECLARE v_calc INT;

	CALL cache.available_refresh (v_calc, TRUE, v_warehouse, v_shipping);
    CALL vn2008.item_last_buy_ (v_warehouse, v_shipping);

	SELECT a.Id_Article, a.Article, a.Categoria, a.Medida, a.Tallos,
		c.available, a.Color, o.Abreviatura, t.Tipo, a.tipo_id, a.Foto,
			CASE b.caja
				WHEN 0 THEN 1
				WHEN 2 THEN b.packing
				ELSE b.grouping
			END AS grouping,
			CASE v_rate
				WHEN 1 THEN b.Tarifa1
				WHEN 2 THEN b.Tarifa2
				WHEN 3 THEN b.Tarifa3
				ELSE NULL
			END AS price
		FROM cache.available c
			JOIN vn2008.Articles a ON a.Id_Article = c.item_id
            JOIN vn2008.t_item_last_buy l ON l.item_id = c.item_id
			JOIN vn2008.Tipos t ON t.tipo_id = a.tipo_id
			JOIN vn2008.reinos r ON t.reino_id = r.id
			JOIN vn2008.Compres b ON b.Id_Compra = l.buy_id
			LEFT JOIN vn2008.Origen o ON a.id_origen = o.id
		WHERE c.calc_id = v_calc
			AND c.available > 0
			AND c.item_id != 90
            AND r.display
			AND (v_realm IS NULL OR v_realm = r.id)
		ORDER BY a.tipo_id, Article, Medida;
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 `myTicketGet` */;
/*!50003 SET @saved_cs_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 `myTicketGet`(vTicket INT)
BEGIN
/**
 * Returns a current user ticket header.
 *
 * @param vTicket The ticket identifier
 */
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		ENGINE = MEMORY
		SELECT id ticketFk FROM myTicket
			WHERE id = vTicket;

	CALL vn.ticketGetTax (NULL);

	SELECT t.id, t.landed, t.shipped, t.refFk, ag.description agency, 
			a.postalCode, a.city, a.nickname, p.name province,
			v.taxBase taxBase, v.taxBase + v.tax + v.equalizationTax AS total
		FROM tmp.ticketTax v
			JOIN vn.ticket t ON t.id = v.ticketFk
			JOIN vn.address a ON a.id = t.addressFk
			JOIN vn.agencyMode ag ON ag.id = t.agencyModeFk
			JOIN vn.province p ON p.id = a.provinceFk
		WHERE t.id = vTicket;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTax;
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 `myTicketGetRows` */;
/*!50003 SET @saved_cs_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 `myTicketGetRows`(vTicket INT)
BEGIN
/**
 * Returns a current user ticket lines.
 *
 * @param vTicket The ticket identifier
 * @select The ticket lines
 */
	SELECT r.itemFk, r.quantity, r.concept, r.price, r.discount,
			o.code origin, i.category, i.size, i.stems, i.inkFk, i.image
		FROM myTicketRow r
			JOIN vn.item i ON i.id = r.itemFk  
			LEFT JOIN vn.origin o ON o.id = i.originFk
		WHERE r.ticketFk = vTicket
		ORDER BY r.concept;
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 `myTicketList` */;
/*!50003 SET @saved_cs_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 `myTicketList`(vFrom DATE, vTo DATE)
BEGIN
/**
 * Returns the current user list of tickets between two dates reange.
 * Also returns the total price with tax of every ticket.
 *
 * @param vFrom From date, if %NULL current date minus 25 days
 * @param vTo To date, if %NULL current date
 * @select The tickets list
 */
	SET vFrom = IFNULL(vFrom, DATE_FORMAT(TIMESTAMPADD(DAY, -25, CURDATE()), '%Y-%m-01'));
	SET vTo = IFNULL(vTo, TIMESTAMPADD(YEAR, 1, CURDATE()));

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		(KEY (ticketFk))
		ENGINE = MEMORY
		SELECT t.id ticketFk
			FROM myTicket t
			WHERE landed BETWEEN TIMESTAMP(vFrom) AND TIMESTAMP(vTo, '23:59:59');
	
	CALL vn.ticketGetTotal;

	SELECT v.id, IFNULL(v.landed, v.shipped) landed, v.shipped, v.companyFk,
			a.city, a.nickname, ag.description agency, t.total
		FROM tmp.ticket i
			JOIN vn.ticket v ON v.id = i.ticketFk
			JOIN vn.address a ON a.id = v.addressFk
            JOIN vn.agencyMode ag ON ag.id = agencyModeFk
			JOIN tmp.ticketTotal t ON t.ticketFk = i.ticketFk
		ORDER BY IFNULL(v.landed, v.shipped) DESC, i.ticketFk DESC;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal,
		tMovementFixed;
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 `myTicketLogAccess` */;
/*!50003 SET @saved_cs_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 `myTicketLogAccess`(vTicket INT)
BEGIN
/**
 * Logs an access to a ticket.
 *
 * @param vTicket The ticket identifier
 */
	INSERT INTO vn.ticketLog
		(originFk, userFk, `action`, description)
		SELECT vTicket, account.userGetId(), 'select', 'Access'
			FROM myTicket t
			WHERE t.id = vTicket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderCheckConfig` */;
/*!50003 SET @saved_cs_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 `orderCheckConfig`(vOrder INT)
proc: BEGIN
/**
 * Comprueba que la configuración del pedido es correcta.
 *
 * @param vOrder Identificador del pedido
 */
	DECLARE vDeliveryMethod VARCHAR(255);
	DECLARE vDelivery DATE;
	DECLARE vAgency INT;
	DECLARE vAddress INT;

	-- Obtiene los datos del pedido

	SELECT d.code, o.date_send, o.agency_id, o.address_id
		INTO vDeliveryMethod, vDelivery, vAgency, vAddress
		FROM `order` o
			JOIN vn.deliveryMethod d ON d.id = o.delivery_method_id
		WHERE o.id = vOrder;

	-- Comprueba que se ha seleccionado una dirección

	IF vDeliveryMethod IN ('AGENCY', 'DELIVERY')
	&& vAddress IS NULL
	THEN
		CALL util.throw ('ORDER_EMPTY_ADDRESS');
	END IF;

	-- Comprueba que la agencia es correcta

	IF !vn.AgencyIsAvailable (vAgency, vDelivery, vAddress) THEN
		CALL util.throw ('ORDER_INVALID_AGENCY');
	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 `orderCheckDate` */;
/*!50003 SET @saved_cs_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 `orderCheckDate`(vDate DATE)
BEGIN
	DECLARE vMaxTime TIME;
	DECLARE vFestive BOOLEAN;
	DECLARE vDenyDay DATE;
	DECLARE vDenySunday BOOLEAN;

	SELECT COUNT(*) INTO vFestive
		FROM orderCheckFestive
		WHERE TIMESTAMPADD(YEAR, -YEAR(vDate), vDate) = date
			AND acceptOrders = FALSE;

	IF vDate < CURDATE()
	THEN
		CALL util.throw ('ORDER_DATE_PAST');
	ELSEIF vFestive > 0
	THEN
		CALL util.throw ('ORDER_DATE_HOLIDAY');
	ELSE
		SELECT c.denySunday, c.denyDay, IFNULL(w.maxTime, c.maxTime)
			INTO vDenySunday, vDenyDay, vMaxTime
			FROM orderCheck c
			LEFT JOIN orderCheckWday w
				ON w.weekday = WEEKDAY(CURDATE());

		IF vDate = CURDATE() AND CURTIME() > vMaxTime
		THEN
			CALL util.throw ('ORDER_DATE_LAST');
		ELSEIF WEEKDAY(vDate) = 6 AND vDenySunday
		THEN
			CALL util.throw ('ORDER_DATE_SUNDAY');
		ELSEIF vDate = vDenyDay
		THEN
			CALL util.throw ('ORDER_DATE_SATURATED');
		END IF;
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderConfirm` */;
/*!50003 SET @saved_cs_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 `orderConfirm`(vOrder INT)
BEGIN
/**
 * Confirms an order, creating each of its tickets on
 * the corresponding date and store.
 *
 * @deprecated Use orderConfirm() instead
 *
 * @param vOrder The order identifier
 */
	DECLARE vOk BOOL;
	DECLARE vDone BOOL DEFAULT FALSE;
	DECLARE vWarehouse INT;
	DECLARE vShipment DATETIME;
	DECLARE vTicket INT;
	DECLARE vNotes VARCHAR(255);
	DECLARE vItem INT;
	DECLARE vConcept VARCHAR(30);
	DECLARE vAmount INT;
	DECLARE vPrice DECIMAL(10,2);
	DECLARE vSale INT;
	DECLARE vRate INT;
	DECLARE vEmployee INT;
	DECLARE vRowId INT;
	DECLARE vDelivery DATE;
	DECLARE vAddress INT;
	DECLARE vAgency INT;
	DECLARE vIsConfirmed BOOL;
	DECLARE vClientId INT;
	DECLARE vCompanyId INT;
	DECLARE vAgencyModeId INT;

	DECLARE TICKET_FREE INT DEFAULT 2;
	DECLARE SYSTEM_WORKER INT DEFAULT 20;

	DECLARE cDates CURSOR FOR
		SELECT t.Fecha_envio, r.warehouse_id
			FROM `order` o
				JOIN order_row r ON r.order_id = o.id
				LEFT JOIN vn2008.travel_tree t ON t.warehouse_id = r.warehouse_id
			WHERE o.id = vOrder AND r.amount != 0
			GROUP BY warehouse_id;

	DECLARE cRows CURSOR FOR 
		SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate
			FROM order_row r
				JOIN vn2008.Articles a ON a.Id_Article = r.item_id
			WHERE r.amount != 0
				AND r.warehouse_id = vWarehouse
				AND r.order_id = vOrder
			ORDER BY r.rate DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET vDone = TRUE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	-- Carga los datos del pedido

	SELECT o.date_send, o.address_id, o.note, a.agency_id,
			o.confirmed, cs.Id_Cliente, o.company_id, o.agency_id
		INTO vDelivery, vAddress, vNotes, vAgency,
			vIsConfirmed, vClientId, vCompanyId, vAgencyModeId
		FROM hedera.`order` o
			JOIN vn2008.Agencias a ON a.Id_Agencia = o.agency_id
			JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id
		WHERE id = vOrder;
			
	-- Comprueba que el pedido no está confirmado

	IF vIsConfirmed THEN
		CALL util.throw ('ORDER_ALREADY_CONFIRMED');
	END IF;

	-- Comprueba que el pedido no está vacío

	SELECT COUNT(*) > 0 INTO vOk
		FROM order_row WHERE order_id = vOrder AND amount > 0;

	IF !vOk THEN
		CALL util.throw ('ORDER_EMPTY');
	END IF;

	-- Carga las fechas de salida de cada almacén

	CALL vn2008.travel_tree (vDelivery, vAddress, vAgency);

	-- Trabajador que realiza la acción

	SELECT Id_Trabajador INTO vEmployee
		FROM vn2008.Trabajadores
		WHERE user_id = account.userGetId();

	IF vEmployee IS NULL THEN
		SELECT employee_id INTO vEmployee FROM order_config;
	END IF;

	-- Crea los tickets del pedido

	START TRANSACTION;

	OPEN cDates;

	lDates:
	LOOP
		SET vTicket = NULL;
		SET vDone = FALSE;
		FETCH cDates INTO vShipment, vWarehouse;
		
		IF vDone THEN
			LEAVE lDates;
		END IF;

		-- Busca un ticket existente que coincida con los parametros del nuevo pedido

		SELECT Id_Ticket INTO vTicket
			FROM vn2008.Tickets t 
			LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket
			JOIN `order` o
				ON o.address_id = t.Id_Consigna
					AND vWarehouse = t.warehouse_id
					AND o.agency_id = t.Id_Agencia
					AND t.landing = o.date_send
					AND vShipment = DATE(t.Fecha)
			WHERE o.id = vOrder
				AND t.Factura IS NULL
				AND IFNULL(tls.alertLevel,0) = 0
				AND t.Id_Cliente <> 1118
			LIMIT 1;
		
		-- Crea el ticket en el caso de no existir uno adecuado

		IF vTicket IS NULL
		THEN
			CALL vn.ticketCreate (
				vClientId,
                IFNULL(vShipment, CURDATE()),
                vWarehouse,
                vCompanyId,
                vAddress,
                vAgencyModeId,
                NULL,
                vDelivery,
                vTicket
			);
		ELSE
			INSERT INTO vncontrol.inter
				SET Id_Ticket = vTicket,
					Id_Trabajador = SYSTEM_WORKER,
					state_id = TICKET_FREE;
		END IF;
		
		INSERT IGNORE INTO vn2008.order_Tickets
			SET order_id = vOrder,
				Id_Ticket = vTicket;

		-- Añade las notas

		IF vNotes IS NOT NULL AND vNotes != ''
		THEN
			INSERT INTO vn2008.ticket_observation (Id_Ticket, observation_type_id, text)
				VALUES (vTicket, 4/*comercial*/, vNotes)
				ON DUPLICATE KEY UPDATE text = CONCAT(VALUES(text),'. ', text);
		END IF;

		-- Añade los movimientos y sus componentes

		OPEN cRows;

		lRows:
		LOOP
			SET vDone = FALSE;
			FETCH cRows INTO vRowId, vItem, vConcept, vAmount, vPrice, vRate;

			IF vDone THEN
				LEAVE lRows;
			END IF;

			INSERT INTO vn2008.Movimientos 
			SET
				Id_Article = vItem,
				Id_Ticket = vTicket,
				Concepte = vConcept,
				Cantidad = vAmount,
				Preu = vPrice,
				CostFixat = 0,
				PrecioFijado = TRUE;

			SET vSale = LAST_INSERT_ID();

			INSERT INTO vn2008.Movimientos_componentes (Id_Movimiento, Id_Componente, Valor)
				SELECT vSale, cm.component_id, cm.price
					FROM order_component cm
						JOIN bi.tarifa_componentes tc ON tc.Id_Componente = cm.component_id
					WHERE cm.order_row_id = vRowId
					GROUP BY vSale, cm.component_id;

			UPDATE order_row SET Id_Movimiento = vSale 
				WHERE id = vRowId;

		END LOOP;

		CLOSE cRows;

		  -- Fija el Costfixat

		UPDATE vn2008.Movimientos m
			JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
				FROM vn2008.Movimientos_componentes mc
					JOIN bi.tarifa_componentes tc USING(Id_Componente)
					JOIN bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base
					JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
				WHERE m.Id_Ticket = vTicket
				GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento
			SET m.CostFixat = sum_valor;
	END LOOP;

	CLOSE cDates;

	DELETE FROM order_basket WHERE order_id = vOrder;
	UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() 
		WHERE id = vOrder;

	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `orderGetTax` */;
/*!50003 SET @saved_cs_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 `orderGetTax`(vOrder INT)
    READS SQL DATA
BEGIN
/**
 * Calcula el IVA, y el recargo de equivalencia de un pedido
 * desglosados por tipos.
 *
 * @param vOrder El identificador del pedido
 * @treturn tmp.orderTax Bases imponibles, IVA y recargo de equivalencia
 */
	CALL vn.taxGetRates (NULL);

	-- Calcula el IVA y el recargo desglosado.

	DROP TEMPORARY TABLE IF EXISTS tmp.orderTax;
	CREATE TEMPORARY TABLE tmp.orderTax
		(INDEX (orderFk))
		ENGINE = MEMORY
		SELECT id orderFk, t.type, t.taxBase,
				CAST(IF(t.hasTax, t.taxBase * x.rate, 0) AS DECIMAL(10,2)) tax,
				CAST(IF(t.hasEqualizationTax, t.taxBase * x.equalizationTax, 0) AS DECIMAL(10,2)) equalizationTax
			FROM (
				SELECT o.id, g.countryFk, g.type
						,SUM(CAST(m.amount * m.price AS DECIMAL(10,2))) taxBase
						,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax
						,c.isEqualizated != FALSE AS hasEqualizationTax
					FROM `order` o
						JOIN orderRow m ON m.orderFk = o.id
						JOIN vn.item a ON a.id = m.itemFk
						JOIN vn.client c ON c.id = o.customer_id
						JOIN vn.supplier p ON p.id = o.company_id
						JOIN tmp.taxClass g
							ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk
					WHERE o.id = vOrder
					GROUP BY o.id, g.type
			) t
			JOIN tmp.taxType x
				ON x.countryFk = t.countryFk AND x.type = t.type;

	DROP TEMPORARY TABLE
		tmp.taxClass,
		tmp.taxType;
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 `orderNew` */;
/*!50003 SET @saved_cs_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 `orderNew`()
BEGIN

	DECLARE vCount INT;

	DECLARE vDeliveryMethod INT;

	DECLARE vAgency INT;

	DECLARE vAddress INT;

	DECLARE vWarehouse INT DEFAULT NULL;



	SELECT COUNT(*) INTO vCount FROM order_view;



	IF vCount >= 3 THEN

		CALL util.throw ('ORDER_MAX_EXCEEDED');

	END IF;



	SELECT co.Id_Consigna, co.Id_Agencia, a.Vista

	INTO vAddress, vAgency, vDeliveryMethod

		FROM vn2008.Clientes c

		LEFT JOIN vn2008.Consignatarios co ON co.Id_Consigna = c.default_address

		JOIN vn2008.Agencias a ON a.Id_Agencia = co.Id_Agencia

			WHERE c.Id_cliente = user_id();



	INSERT INTO `order`

	SET

		date_send = CURDATE(),

		customer_id = user_id(),

		delivery_method_id = IFNULL(vDeliveryMethod, DEFAULT(delivery_method_id)),

		agency_id = IFNULL(vAgency, DEFAULT(agency_id)),

		address_id = IFNULL(vAddress, DEFAULT(address_id)),

		wh_id = IFNULL(vWarehouse, DEFAULT(wh_id)),

		type_id = IFNULL(vAgency, DEFAULT(type_id)),
		is_bionic = FALSE;

        

	SELECT LAST_INSERT_ID() order_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 `orderUpdate` */;
/*!50003 SET @saved_cs_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 `orderUpdate`(vOrder INT)
proc: BEGIN
/**
 * Actualiza la líneas de un pedido.
 *
 * @param vOrder Id del pedido
 */
	DECLARE vDate DATE;
	DECLARE vAddress INT;
	DECLARE vAgency INT;
	DECLARE vNRows INT;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	SELECT COUNT(*) INTO vNRows
		FROM order_row WHERE order_id = vOrder;

	IF vNRows > 0
	THEN
		SELECT date_send, address_id, agency_id
			INTO vDate, vAddress, vAgency
			FROM `order`
			WHERE id = vOrder;

		CALL vn2008.bionic_from_order (vDate, vAddress, vAgency, vOrder);

		DELETE c
			FROM order_row r
				JOIN order_component c ON c.order_row_id = r.id
				WHERE r.order_id = vOrder;
				
		UPDATE order_row r
			LEFT JOIN tmp.bionic_price l
				ON l.warehouse_id = r.warehouse_id
					AND l.item_id = r.item_id
					AND l.rate = r.rate
			LEFT JOIN tmp.travel_tree t
				ON t.warehouse_id = r.warehouse_id
			SET
				r.price = l.price,
				r.amount = IF(l.item_id IS NOT NULL, r.amount + IF(@m := MOD(r.amount, l.grouping), l.grouping - @m, 0), 0),
				r.shipment = t.Fecha_envio
			WHERE r.order_id = vOrder;

		INSERT INTO order_component (order_row_id, component_id, price)
		SELECT r.id, c.component_id, c.cost
			FROM order_row r
				JOIN tmp.bionic_component c
					ON c.warehouse_id = r.warehouse_id
						AND c.item_id = r.item_id
				JOIN bi.tarifa_componentes t
					ON t.Id_Componente = c.component_id
						AND (t.tarifa_class IS NULL OR t.tarifa_class = r.rate)
			WHERE r.order_id = vOrder;
	END IF;

	UPDATE `order` SET date_make = NOW()
		WHERE id = vOrder;

	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `order_confirm_bionic` */;
/*!50003 SET @saved_cs_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 `order_confirm_bionic`(vOrder INT)
BEGIN
/**
 * Confirma un pedido, creando cada uno de sus tickets en la fecha
 * y almacén correspondientes.
 *
 * @deprecated Use orderConfirm() instead
 *
 * @param vOrder Identificador del pedido
 */
	CALL orderConfirm (vOrder);
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 `order_get_vat` */;
/*!50003 SET @saved_cs_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 `order_get_vat`(vOrder INT)
    READS SQL DATA
BEGIN
/**
 * Calcula el IVA, y el recargo de equivalencia de un pedido
 * desglosados por tipos.
 *
 * @deprecated Use procedure orderGetTax() instead
 *
 * @param vOrder El identificador del pedido
 * @table t_order_vat Bases imponibles, su IVA y su recargo de equivalencia.
 */
	CALL orderGetTax (vOrder);
    
    DROP TEMPORARY TABLE IF EXISTS t_order_vat;
	CREATE TEMPORARY TABLE t_order_vat
		ENGINE = MEMORY
        SELECT orderFk order_id, type rate, taxBase tax_base,
				tax vat, equalizationTax surcharge
			FROM tmp.orderTax;

	DROP TEMPORARY TABLE tmp.orderTax;
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 `surveyVote` */;
/*!50003 SET @saved_cs_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 `surveyVote`(vAnswer INT)
BEGIN
	DECLARE vSurvey INT;
	DECLARE vCount TINYINT;
	DECLARE EXIT HANDLER FOR 1062
		CALL util.throw ('SURVEY_MAX_ONE_VOTE');

	SELECT survey_id INTO vSurvey
		FROM survey_answer WHERE id = vAnswer;

	INSERT INTO survey_vote
		VALUES (vSurvey, account.userGetId());

	UPDATE survey_answer SET votes = votes + 1
		WHERE id = vAnswer;
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 `ticketLog` */;
/*!50003 SET @saved_cs_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 `ticketLog`(vticket INT)
BEGIN
	INSERT INTO vn2008.Tickets_dits
		(idaccion_dits, Id_Trabajador, Id_Ticket)
        SELECT 146, 4, id
			FROM ticket_view WHERE id = vTicket;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticket_list` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8mb4 */ ;
/*!50003 SET character_set_results = utf8mb4 */ ;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` PROCEDURE `ticket_list`()
BEGIN

/**

 * Devuelve los tickets del cliente del último mes, calculando

 * el total de cada ticket.

 *

 * @select Listado de tickets

 **/

	DROP TEMPORARY TABLE IF EXISTS vn2008.ticket_tmp;

	CREATE TEMPORARY TABLE vn2008.ticket_tmp

	(KEY (ticket_id))

	ENGINE = MEMORY

	SELECT t.id ticket_id FROM ticket_view t

		WHERE date > TIMESTAMP(DATE_FORMAT(TIMESTAMPADD(DAY, -25, CURDATE()), '%Y-%m-01'));



	CALL vn2008.ticket_total ();



	DROP TEMPORARY TABLE IF EXISTS t_movement_fixed;

	CREATE TEMPORARY TABLE t_movement_fixed

	(KEY (ticket_id))

	ENGINE = MEMORY

	SELECT ticket_id, BIT_AND(fixed != FALSE) all_fixed

		FROM ticket_row_view

		JOIN vn2008.ticket_tmp USING(ticket_id)

			GROUP BY ticket_id;

	

	SELECT i.ticket_id, IFNULL(v.delivery, v.`date`) `date`, city, consignee, type, company_id,

		IF(all_fixed, t.total, NULL) total,

		IF(v.date >= CURDATE() AND v.invoice IS NULL AND all_fixed

			,t.total

			,NULL

		) pending

			FROM vn2008.ticket_tmp i

			JOIN ticket_view v ON i.ticket_id = v.id

			JOIN address_view c ON v.address_id = c.id

			JOIN vn2008.ticket_total t USING(ticket_id)

			LEFT JOIN t_movement_fixed m USING(ticket_id)

				ORDER BY IFNULL(v.delivery, v.`date`) DESC, i.ticket_id DESC;



	DROP TEMPORARY TABLE vn2008.ticket_tmp;

	DROP TEMPORARY TABLE vn2008.ticket_total;

	DROP TEMPORARY TABLE t_movement_fixed;

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 `tpvTransactionConfirm` */;
/*!50003 SET @saved_cs_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 `tpvTransactionConfirm`(
	 vAmount INT
	,vOrder INT
	,vMerchant INT
	,vCurrency INT
	,vResponse INT
    ,vErrorCode VARCHAR(10)
)
BEGIN
/**
 * Confirma una transacción previamente iniciada, reescribiendo
 * sus datos por los confirmados por el banco (solo si estos difieren).
 * Genera el recibo y su correspondiente entrada en caja.
 *
 * @param vAmount Cantidad confirmada
 * @param vOrder Identificador de transacción
 * @param vMerchant Identificador de comercio
 * @param vCurrency Identificador de moneda
 * @param vResponse Identificador de respuesta del banco
 * @param vErrorCode Código de error del banco, si lo hubiera
 */
	DECLARE vReceipt INT;
	DECLARE vStatus VARCHAR(10);
	DECLARE vCustomer INT;
	DECLARE vBank INT;
	DECLARE vCompany INT;
	DECLARE vEmployee INT;
	DECLARE vIsDuplicated BOOLEAN;
	DECLARE vDate DATE;
	DECLARE vConcept VARCHAR(25) DEFAULT 'Cobro Web';

    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	START TRANSACTION;

	SELECT COUNT(*) > 0 INTO vIsDuplicated
		FROM tpvTransaction
			WHERE id = vOrder AND response IS NOT NULL
		FOR UPDATE;

	IF vIsDuplicated
	THEN
		CALL util.throw ('TRANSACTION_DUPLICATED');
	END IF;

	IF vResponse BETWEEN 0 AND 99
	THEN
		SELECT
			t.clientFk
			,m.bankFk
			,m.companyFk
			,c.employeeFk
			,DATE(t.created)
		INTO
			vCustomer
			,vBank
			,vCompany
			,vEmployee
			,vDate
			FROM tpvMerchant m
			JOIN tpvConfig c ON c.id = 1
			LEFT JOIN tpvTransaction t ON t.id = vOrder
				WHERE m.id = vMerchant;

		INSERT INTO vn2008.Recibos
		SET
			Entregado = vAmount / 100
			,Fechacobro = vDate
			,Id_Trabajador = vEmployee
			,Id_Banco = vBank
			,Id_Cliente = vCustomer
			,empresa_id = vCompany
			,Id_Factura = vConcept
            ,conciliado = TRUE;

		SET vReceipt = LAST_INSERT_ID();
		SET vStatus = 'ok';

		-- Código redundante

		DO vn2008.till_entry
		(
			vCustomer
			,vBank
			,vAmount / 100
			,vConcept
			,vDate
			,'A'
			,TRUE
			,vCustomer
			,vCompany
			,vEmployee
		);
	ELSE
		SET vReceipt = NULL;
		SET vStatus = 'ko';
	END IF;

	UPDATE tpvTransaction
	SET
		merchantFk = vMerchant
		,receiptFk = vReceipt
		,amount = vAmount
		,response = vResponse
        ,errorCode = vErrorCode
		,status = vStatus
			WHERE id = vOrder;

	COMMIT;
END ;;
DELIMITER ;
/*!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 `tpvTransactionConfirmAll` */;
/*!50003 SET @saved_cs_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 `tpvTransactionConfirmAll`(vDate DATE)
BEGIN
/**
 * Confirma todas las transacciones confirmadas por el cliente pero no
 * por el banco para una fecha dada.
 *
 * @param vDate Fecha deseada
 */
	DECLARE vOrder INT;
	DECLARE vDone BOOLEAN DEFAULT FALSE;
	DECLARE vDateIni DATETIME DEFAULT TIMESTAMP(vDate, '00:00:00');
	DECLARE vDateEnd DATETIME DEFAULT TIMESTAMP(vDate, '23:59:59');

	DECLARE cTransactions CURSOR FOR
	SELECT id
		FROM tpvTransaction
			WHERE created BETWEEN vDateIni AND vDateEnd
			AND status = 'ok'
			AND response IS NULL;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;

	OPEN cTransactions;

	l: LOOP
		FETCH cTransactions INTO vOrder;

		IF vDone THEN
			LEAVE l;
		END IF;

		CALL tpvTransactionConfirmById (vOrder);
	END LOOP l;

	CLOSE cTransactions;
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 `tpvTransactionConfirmById` */;
/*!50003 SET @saved_cs_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 `tpvTransactionConfirmById`(vOrder INT)
BEGIN
/**
 * Confirma manualmente una transacción espedificando su identificador.
 *
 * @param vOrder Identificador de la transacción
 */
	DECLARE vAmount INT;
	DECLARE vMerchant INT;
	DECLARE vCurrency INT;

	SELECT amount, merchantFk, currency
		INTO vAmount, vMerchant, vCurrency
			FROM tpvTransaction t
			JOIN tpvMerchant m ON m.id = t.merchantFk
			JOIN tpvConfig c
				WHERE t.id = vOrder;

	CALL tpvTransactionConfirm (
		 vAmount
		,vOrder
		,vMerchant
		,vCurrency
		,0
		,NULL
	);
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 `tpvTransactionEnd` */;
/*!50003 SET @saved_cs_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 `tpvTransactionEnd`(vTransaction INT, vStatus VARCHAR(12))
BEGIN
/**
 * Finaliza una transaccción estableciendo su estado a 'ok' o
 * 'ko' en función de si esta se ha realizado correctamente.
 * Este procedimiento debe ser llamado directamente por el cliente
 * nada mas finalizar la transacción y solo tiene validez hasta que
 * llega la notificacion definitiva desde el banco.
 *
 * @param vTransaction El identificador de la transacción
 * @param vStatus El estado, 'ok' o 'ko'
 */
	IF vStatus IN ('ok', 'ko')
	THEN
		UPDATE myTpvTransaction SET status = vStatus
			WHERE id = vTransaction AND response IS NULL;
	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 `tpvTransactionStart` */;
/*!50003 SET @saved_cs_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 `tpvTransactionStart`(vAmount INT, vCompany INT)
BEGIN
/**
 * Inicia una nueva transacción con el TPV virtual, generando
 * un identificador de transacción y devolviendo con un SELECT
 * los parámetros que deben enviarse a la URL del servicio web
 * del banco.
 *
 * @param vAmount Cantidad a pagar en céntimos
 * @param vCompany El identificador de la empresa
 *
 * @select Los parámetros que deben pasarse al banco
 */
	DECLARE vTransaction CHAR(12);
	DECLARE vMerchant INT;
	DECLARE vUrl VARCHAR(255);
	DECLARE vKey VARCHAR(50);
	DECLARE vTestMode BOOLEAN;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
	BEGIN
		ROLLBACK;
		RESIGNAL;
	END;

	START TRANSACTION;

	IF vCompany IS NULL
	THEN
		SELECT companyFk INTO vCompany
			FROM tpvMerchantEnable LIMIT 1;
	END IF;

	SELECT merchantFk INTO vMerchant
		FROM tpvMerchantEnable WHERE companyFk = vCompany;

	SELECT testMode INTO vTestMode
		FROM tpvConfig;

	IF NOT vTestMode
	THEN
		SELECT c.url, m.secretKey INTO vUrl, vKey
			FROM tpvMerchant m
			JOIN tpvConfig c
				WHERE m.id = vMerchant;
	ELSE
		SELECT testUrl, testKey INTO vUrl, vKey
			FROM tpvConfig;
	END IF;

	INSERT INTO myTpvTransaction
	SET
		merchantFk = vMerchant
		,clientFk = account.userGetId()
		,amount = vAmount;

	SET vTransaction = LAST_INSERT_ID();

	SELECT
		 vAmount amount
		,vTransaction transactionId
		,vMerchant merchant
		,currency
		,transactionType
		,terminal
		,merchantUrl
		,vUrl url
		,vKey secretKey
		FROM tpvConfig;

	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `tpvTransactionUndo` */;
/*!50003 SET @saved_cs_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 `tpvTransactionUndo`(
	vOrder INT
)
BEGIN
	DECLARE vCustomer INT;
	DECLARE vAmount DOUBLE;
	DECLARE vReceipt INT;
	DECLARE vDate DATE;
	DECLARE vBank INT;
	DECLARE vAccount VARCHAR(12);
	DECLARE vSubaccount VARCHAR(12);

    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	START TRANSACTION;

	SELECT
		 t.clientFk
		,t.amount / 100
		,t.receiptFk
		,DATE(t.created)
		,m.bankFk
	INTO
		 vCustomer
		,vAmount
		,vReceipt
		,vDate
		,vBank
		FROM tpvTransaction t
        JOIN tpvMerchant m ON m.id = t.merchantFk
		JOIN tpvConfig c
			WHERE t.id = vOrder
		FOR UPDATE;

	-- Elimina el recibo

	DELETE FROM vn2008.Recibos
		WHERE Id = vReceipt LIMIT 1;

	-- Elimina la entrada de cajas

	DELETE FROM vn2008.Cajas
		WHERE Id_Banco = vBank
		AND DATE(CajaFecha) = vDate
		AND Entrada = vAmount
			LIMIT 1;

	-- Elimina los asientos contables

	SELECT Cuenta INTO vSubaccount
		 FROM vn2008.Clientes WHERE Id_Cliente = vCustomer;

	SELECT Cuenta INTO vAccount
		FROM vn2008.Bancos WHERE Id_Banco = vBank;

	DELETE FROM vn2008.XDiario
		WHERE SUBCTA = vSubaccount
		AND CONTRA = vAccount
		AND DATE(FECHA) = vDate
		AND EUROHABER = vAmount
			LIMIT 1;

	DELETE FROM vn2008.XDiario
		WHERE CONTRA = vSubaccount
		AND SUBCTA = vAccount
		AND DATE(FECHA) = vDate
		AND EURODEBE = vAmount
			LIMIT 1;

	-- Actualiza la transaccion

	UPDATE tpvTransaction
		SET response = NULL, status = 'started'
			WHERE id = vOrder;

	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `transactionEnd` */;
/*!50003 SET @saved_cs_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 `transactionEnd`(vTransaction INT, vStatus VARCHAR(12))
BEGIN
/**
 * @deprecated Use procedure tpvTransactionEnd() instead
 */
	CALL tpvTransactionEnd(vTransaction, vStatus);
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 `transactionStart` */;
/*!50003 SET @saved_cs_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 `transactionStart`(vAmount INT, vCompany INT)
BEGIN
/**
 * @deprecated Use procedure tpvtransactionStart() instead
 */
	CALL tpvtransactionStart(vAmount, vCompany);
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 `visitRegister` */;
/*!50003 SET @saved_cs_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 `visitRegister`(
	 vVisit INT
	,vPlatform VARCHAR(30)
	,vBrowser VARCHAR(30)
	,vVersion VARCHAR(15)
	,vJavascript TINYINT
	,vCookies TINYINT
	,vAgent VARCHAR(255)
	,vIp INT
	,vReferer VARCHAR(255)
)
BEGIN
	DECLARE vFirstVisit TINYINT DEFAULT FALSE;
	DECLARE vFirstAgent TINYINT DEFAULT FALSE;
	DECLARE vAgentId INT DEFAULT NULL;
	DECLARE vAccessId INT DEFAULT NULL;

	-- Registers the visit

	IF vVisit IS NULL || (SELECT COUNT(*) FROM visit WHERE id = vVisit) = 0
	THEN
		INSERT INTO visit SET id = DEFAULT;
        SET vVisit = LAST_INSERT_ID();
		SET vFirstVisit = TRUE;
	END IF;

	SELECT id INTO vAgentId FROM visitAgent
		WHERE visit = vVisit
			AND (agent = vAgent OR (vAgent IS NULL AND agent IS NULL))
		LIMIT 1;

	-- Registers the user agent

	IF vAgentId IS NULL
	THEN
		INSERT INTO visitAgent SET
			 visit = vVisit
            ,platform = vPlatform
            ,browser = vBrowser
            ,version = vVersion
            ,javascript = vJavascript
            ,cookies = vCookies
            ,agent = vAgent;

        SET vAgentId = LAST_INSERT_ID();
		SET vFirstAgent = TRUE;
	END IF;

	IF vFirstVisit
    THEN
		UPDATE visit SET firstAgent = vAgentId
			WHERE id = vVisit;
	END IF;

	-- Registers the user access

	INSERT INTO visitAccess SET
		 agent = vAgentId
		,ip = vIp
        ,referer = vReferer;

	SET vAccessId = LAST_INSERT_ID();

	IF vFirstAgent
    THEN
		UPDATE visitAgent SET firstAccess = vAccessId
			WHERE id = vAgentId;
	END IF;
    
    -- Returns the visit info

	SELECT vVisit visit, vAccessId access;
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 `visitUserNew` */;
/*!50003 SET @saved_cs_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 `visitUserNew`(
	 vAccess INT
	,vSsid VARCHAR(64)
)
BEGIN
	DECLARE vUserVisit INT;

	INSERT INTO visitUser SET
		access = vAccess,
		user = account.userGetId();

	SET vUserVisit = LAST_INSERT_ID();
    
    UPDATE userSession SET userVisit = vUserVisit
		WHERE ssid = vSsid;
        
	DELETE FROM userSession
		WHERE lastUpdate < TIMESTAMPADD(HOUR, -1, NOW());
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 `__order_confirm_bionic` */;
/*!50003 SET @saved_cs_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 `__order_confirm_bionic`(v_order INT)
BEGIN
/**
 * Confirma un pedido, creando cada uno de sus tickets en la fecha
 * y almacén correspondientes.
 *
 * @param v_order Identificador del pedido
 **/
	DECLARE v_ok BOOLEAN;
	DECLARE v_done BOOLEAN DEFAULT FALSE;
	DECLARE v_wh INT;
	DECLARE v_shipment DATETIME;
	DECLARE v_ticket INT;
	DECLARE v_note VARCHAR(255);
	DECLARE i_article INT;
	DECLARE v_concepte VARCHAR(30);
	DECLARE i_amount INT;
	DECLARE d_price DOUBLE;
	DECLARE i_movimiento INT;
	DECLARE i_rate INT;
	DECLARE i_worker INT;
	DECLARE i_order_row INT;
	DECLARE d_delivery DATE;
	DECLARE i_address INT;
	DECLARE i_agency INT;
    DECLARE b_confirmed BOOLEAN;
    DECLARE TICKET_FREE INT DEFAULT 2;
	DECLARE SYSTEM_WORKER INT DEFAULT 20;
	DECLARE vClientId INT;
    DECLARE vCompanyId INT;
	DECLARE vAgencyModeId INT;

	DECLARE cur_tick CURSOR FOR
		SELECT t.Fecha_envio, r.warehouse_id
			FROM `order` o
				JOIN order_row r ON r.order_id = o.id
				LEFT JOIN vn2008.travel_tree t ON t.warehouse_id = r.warehouse_id
			WHERE o.id = v_order AND r.amount != 0
			GROUP BY warehouse_id;

	DECLARE cur_mov CURSOR FOR 
		SELECT r.id, r.item_id, a.Article, r.amount, r.price, r.rate
			FROM order_row r
				JOIN vn2008.Articles a ON a.Id_Article = r.item_id
			WHERE r.amount != 0
				AND r.warehouse_id = v_wh
				AND r.order_id = v_order
			ORDER BY r.rate DESC;

	DECLARE CONTINUE HANDLER FOR NOT FOUND
		SET v_done = TRUE;

	DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
		ROLLBACK;
        RESIGNAL;
	END;

	-- Carga los datos del pedido
    
        SELECT o.date_send, o.address_id, o.note, a.agency_id, o.confirmed,cs.Id_Cliente,o.company_id,o.agency_id
			 INTO d_delivery,i_address, v_note, i_agency, b_confirmed,vClientId , vCompanyId,vAgencyModeId
			FROM hedera.`order` o
				JOIN vn2008.Agencias a ON a.Id_Agencia = o.agency_id
				JOIN vn2008.Consignatarios cs ON cs.Id_Consigna = o.address_id
			WHERE id = v_order;
            
	-- Comprueba que el pedido no está confirmado

	IF b_confirmed THEN
		CALL util.throw ('ORDER_ALREADY_CONFIRMED');
	END IF;

	-- Comprueba que el pedido no está vacío
    
	SELECT COUNT(*) > 0 INTO v_ok
		FROM order_row WHERE order_id = v_order AND amount > 0;

	IF !v_ok THEN
		CALL util.throw ('ORDER_EMPTY');
	END IF;

	-- Carga las fechas de salida de cada almacén

	CALL vn2008.travel_tree (d_delivery, i_address, i_agency);

	-- Trabajador que realiza la acción

	SELECT Id_Trabajador INTO i_worker
		FROM vn2008.Trabajadores
		WHERE user_id = account.userGetId();

	IF i_worker IS NULL THEN
		SELECT employee_id INTO i_worker FROM order_config;
	END IF;
    
	-- Crea los tickets del pedido

	START TRANSACTION;

	OPEN cur_tick;

	tick_loop:
	LOOP
        SET v_ticket = NULL;
		SET v_done = FALSE;
		FETCH cur_tick INTO v_shipment, v_wh;
		
		IF v_done THEN
			LEAVE tick_loop;
		END IF;

	-- Busca un ticket existente que coincida con los parametros del nuevo pedido
		SELECT Id_Ticket INTO v_ticket
			FROM vn2008.Tickets t 
			LEFT JOIN vn.ticketState tls on tls.ticket = t.Id_Ticket
			JOIN `order` o
				ON o.address_id = t.Id_Consigna
					AND v_wh = t.warehouse_id
                    AND o.agency_id = t.Id_Agencia
					AND t.landing = o.date_send
                    AND v_shipment = DATE(t.Fecha)
			WHERE o.id = v_order
				AND t.Factura IS NULL
				AND IFNULL(tls.alertLevel,0) = 0
             /*   AND t.PedidoImpreso = 0
				AND t.Etiquetasemitidas = 0
                AND vn2008.is_bionic(t.Id_Ticket)  */
                AND t.Id_Cliente <> 1118
			LIMIT 1;		
           
		
		-- Crea el ticket en el caso de no existir uno adecuado

		IF v_ticket IS NULL
        THEN
			call vn.ticketCreate( vClientId, IFNULL(v_shipment,CURDATE()), v_wh, vCompanyId, i_address, vAgencyModeId, NULL, d_delivery, v_ticket);
		ELSE
			-- UPDATE vn2008.Tickets SET Localizacion = CONCAT(Localizacion,'B+') WHERE Id_Ticket = v_ticket;
			INSERT INTO vncontrol.inter(Id_Ticket, Id_Trabajador, state_id)
			VALUES(v_ticket, SYSTEM_WORKER, TICKET_FREE);

		END IF;
        
		INSERT IGNORE INTO vn2008.order_Tickets (order_id, Id_Ticket)
			VALUES (v_order, v_ticket);

		-- Añade las notas

		IF v_note IS NOT NULL && v_note != ''
		THEN
			INSERT INTO vn2008.ticket_observation (Id_Ticket, observation_type_id, text)
				VALUES (v_ticket, 4/*comercial*/, v_note)
				ON DUPLICATE KEY UPDATE text = CONCAT(VALUES(text),'. ', text);
		END IF;

		-- Añade los movimientos y sus componentes

		OPEN cur_mov;

		mov_loop:
		LOOP
			SET v_done = FALSE;
			FETCH cur_mov INTO i_order_row, i_article, v_concepte, i_amount, d_price, i_rate;

			IF v_done THEN
				LEAVE mov_loop;
			END IF;

			INSERT INTO vn2008.Movimientos 
			SET
				Id_Article = i_article,
				Id_Ticket = v_ticket,
				Concepte = v_concepte,
				Cantidad = i_amount,
				Preu = d_price,
				CostFixat = 0,
				PrecioFijado = TRUE;

			SET i_movimiento = LAST_INSERT_ID();

			INSERT INTO vn2008.Movimientos_componentes (Id_Movimiento, Id_Componente, Valor)
				SELECT i_movimiento, cm.component_id, cm.price
					FROM order_component cm
						JOIN bi.tarifa_componentes tc ON tc.Id_Componente = cm.component_id
					WHERE cm.order_row_id = i_order_row
					GROUP BY i_movimiento, cm.component_id;

			UPDATE order_row SET Id_Movimiento = i_movimiento 
				WHERE id = i_order_row;
   
		END LOOP;

		CLOSE cur_mov;
          -- Fija el Costfixat
    
		UPDATE vn2008.Movimientos m
			JOIN (SELECT SUM(mc.Valor) sum_valor,mc.Id_Movimiento 
                    FROM vn2008.Movimientos_componentes mc
                    join bi.tarifa_componentes tc using(Id_Componente)
					join bi.tarifa_componentes_series tcs on tcs.tarifa_componentes_series_id = tc.tarifa_componentes_series_id AND tcs.base
                    JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
                    where m.Id_Ticket = v_ticket
					GROUP BY mc.Id_Movimiento) mc ON mc.Id_Movimiento = m.Id_Movimiento
			SET m.CostFixat = sum_valor;
	END LOOP;

	CLOSE cur_tick;
    
	DELETE FROM order_basket WHERE order_id = v_order;
	UPDATE `order` SET confirmed = TRUE, confirm_date = NOW() 
		WHERE id = v_order;

	COMMIT;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;

--
-- Current Database: `bs`
--

CREATE DATABASE /*!32312 IF NOT EXISTS*/ `bs` /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci */;

USE `bs`;

--
-- Temporary view structure for view `VentasPorCliente`
--

DROP TABLE IF EXISTS `VentasPorCliente`;
/*!50001 DROP VIEW IF EXISTS `VentasPorCliente`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `VentasPorCliente` AS SELECT 
 1 AS `Id_Cliente`,
 1 AS `VentaBasica`,
 1 AS `year`,
 1 AS `month`*/;
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 `vn2008`.`Bancos` (`Id_Banco`) 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 `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 `vn2008`.`Trabajadores` (`Id_Trabajador`) 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 `vn2008`.`Trabajadores` (`Id_Trabajador`) 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 `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 `vn2008`.`Clientes` (`id_cliente`) 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 `mana_spellers`
--

DROP TABLE IF EXISTS `mana_spellers`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mana_spellers` (
  `Id_Trabajador` int(11) NOT NULL,
  `size` int(11) NOT NULL DEFAULT '300',
  `used` int(11) NOT NULL DEFAULT '0',
  `prices_modifier_rate` double NOT NULL DEFAULT '0',
  `prices_modifier_activated` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`Id_Trabajador`),
  KEY `fk_mana_spellers_Trabajadores_idx` (`Id_Trabajador`),
  CONSTRAINT `fk_mana_spellers_Trabajadores` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
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 ;;
/*!50003 CREATE*/ /*!50017 DEFINER=`root`@`%`*/ /*!50003 TRIGGER `bs`.`mana_spellers_AFTER_INSERT` AFTER INSERT ON `mana_spellers` FOR EACH ROW
BEGIN

	
	REPLACE vn2008.Permisos(Id_Grupo, Id_Trabajador) 
    VALUES(6, NEW.Id_Trabajador);
    
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 ;

--
-- 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,
  `order` int(11) DEFAULT NULL,
  `schema` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `procedure` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT 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 */ ;

--
-- Temporary view structure for view `v_ventas`
--

DROP TABLE IF EXISTS `v_ventas`;
/*!50001 DROP VIEW IF EXISTS `v_ventas`*/;
SET @saved_cs_client     = @@character_set_client;
SET character_set_client = utf8;
/*!50001 CREATE VIEW `v_ventas` AS SELECT 
 1 AS `importe`,
 1 AS `recargo`,
 1 AS `year`,
 1 AS `month`,
 1 AS `week`,
 1 AS `day`*/;
SET character_set_client = @saved_cs_client;

--
-- Table structure for table `vendedores`
--

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',
  PRIMARY KEY (`Id_Trabajador`,`año`,`mes`),
  CONSTRAINT `trabajador_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) 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` (
  `Id_Trabajador` int(11) NOT NULL,
  `fecha` date NOT NULL,
  `importe` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`Id_Trabajador`,`fecha`),
  CONSTRAINT `evo_vendedor_trabajador` FOREIGN KEY (`Id_Trabajador`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) 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 `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `empresa_bs_ventas` FOREIGN KEY (`empresa_id`) REFERENCES `vn2008`.`empresa` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `mov_to_mov` FOREIGN KEY (`Id_Movimiento`) REFERENCES `vn2008`.`Movimientos` (`Id_Movimiento`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `tip_to_tip` FOREIGN KEY (`tipo_id`) REFERENCES `vn2008`.`Tipos` (`tipo_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 `ventasComponentes`
--

DROP TABLE IF EXISTS `ventasComponentes`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ventasComponentes` (
  `Fecha` varchar(10) CHARACTER SET utf8 NOT NULL DEFAULT '',
  `Id_Componente` int(11) NOT NULL,
  `Importe` decimal(10,2) DEFAULT NULL
) 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 */;

--
-- Dumping events for database 'bs'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `nightly_tasks` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8 */ ;;
/*!50003 SET character_set_results = utf8 */ ;;
/*!50003 SET collation_connection  = utf8_general_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks` ON SCHEDULE EVERY 1 DAY STARTS '2017-08-27 01:00:00' ON COMPLETION NOT PRESERVE ENABLE DO CALL bs.nightTaskLauncher() */ ;;
/*!50003 SET time_zone             = @saved_time_zone */ ;;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;;
/*!50003 SET character_set_client  = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection  = @saved_col_connection */ ;;
/*!50106 DROP EVENT IF EXISTS `nightly_tasks2` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8 */ ;;
/*!50003 SET character_set_results = utf8 */ ;;
/*!50003 SET collation_connection  = utf8_general_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks2` ON SCHEDULE EVERY 1 DAY STARTS '2017-03-24 02:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call bs.nightTaskLauncher() */ ;;
/*!50003 SET time_zone             = @saved_time_zone */ ;;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;;
/*!50003 SET character_set_client  = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection  = @saved_col_connection */ ;;
/*!50106 DROP EVENT IF EXISTS `nightly_tasks3` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8 */ ;;
/*!50003 SET character_set_results = utf8 */ ;;
/*!50003 SET collation_connection  = utf8_general_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks3` ON SCHEDULE EVERY 1 DAY STARTS '2017-03-24 03:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call bs.nightTaskLauncher() */ ;;
/*!50003 SET time_zone             = @saved_time_zone */ ;;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;;
/*!50003 SET character_set_client  = @saved_cs_client */ ;;
/*!50003 SET character_set_results = @saved_cs_results */ ;;
/*!50003 SET collation_connection  = @saved_col_connection */ ;;
/*!50106 DROP EVENT IF EXISTS `nightly_tasks4` */;;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8 */ ;;
/*!50003 SET character_set_results = utf8 */ ;;
/*!50003 SET collation_connection  = utf8_general_ci */ ;;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;;
/*!50003 SET @saved_time_zone      = @@time_zone */ ;;
/*!50003 SET time_zone             = 'SYSTEM' */ ;;
/*!50106 CREATE*/ /*!50117 DEFINER=`root`@`%`*/ /*!50106 EVENT `nightly_tasks4` ON SCHEDULE EVERY 1 DAY STARTS '2017-03-24 04:00:00' ON COMPLETION NOT PRESERVE ENABLE DO call bs.nightTaskLauncher() */ ;;
/*!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 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 '2017-01-01';
DECLARE vDateEnd DATE DEFAULT '2017-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
			GROUP BY mc.Id_Componente;

	SET vDate = TIMESTAMPADD(DAY,1,vDate);

	IF DAY(vDate) MOD 10 = 0 THEN 
    
		SELECT vDate;
        
	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 `bancos_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 `bancos_evolution_add`()
BEGIN
/*

Inserta en la tabla bancos_evolution los saldos acumulados

*/


DECLARE vCurrentDate DATE;
DECLARE vStartingDate DATE DEFAULT '2015-01-01';
DECLARE vMaxDate DATE DEFAULT TIMESTAMPADD(MONTH, 2, CURDATE());

SELECT max(Fecha) 
	INTO vStartingDate 
    FROM bs.bancos_evolution
    WHERE Fecha > '2015-01-01';

DELETE FROM bs.bancos_evolution 
WHERE Fecha > vStartingDate;

SET vCurrentDate = vStartingDate;




		WHILE vCurrentDate < vMaxDate DO
        
					IF day(vCurrentDate) mod 28 = 0 then 
                       SELECT vCurrentDate;
					end if;
                    
                    
					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 */ ;
ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!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.name) 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.name) 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 `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)
BEGIN
create TEMPORARY TABLE workerAndBelow ENGINE=MEMORY

SELECT w.id
	FROM vn.worker w
	WHERE w.bossFk=vWorker OR w.id=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, Greuge
			FROM bi.Greuge_Evolution
			WHERE Fecha = (SELECT MAX(Fecha) FROM bi.Greuge_Evolution)
		) 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)
		JOIN workerAndBelow w ON w.id = c.Id_Trabajador
    WHERE v.fecha BETWEEN TIMESTAMPADD(YEAR, - 1, CURDATE()) AND CURDATE()
		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(CURDATE()) + 1, CURDATE()) AND CURDATE() - 1)
    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 CURDATE() AND LAST_DAY(CURDATE())
    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(CURDATE())
            AND YEAR(fecha) = YEAR(CURDATE()) - 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, CURDATE()), '%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
WHERE
    (c.Id_Trabajador = vWorker OR tr.boss = vWorker);
DROP TEMPORARY TABLE workerAndBelow;
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_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 `manaCustomerFill_kk` */;
/*!50003 SET @saved_cs_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 `manaCustomerFill_kk`()
BEGIN


/* Rellena la tabla caché bs.manaCustomer desde 0 
*
* Utilizar para reconstruirla en caso de que se corrompa.
*
*/

DECLARE vFromDated DATE;
DECLARE vToDated DATETIME DEFAULT '2015-12-31 23:59:59';
DECLARE isDone BOOLEAN DEFAULT FALSE;

DELETE FROM bs.manaCustomer;

WHILE NOT isDone DO

	SELECT TIMESTAMPADD(DAY,1,vToDated), TIMESTAMPADD(MONTH, 1, vToDated)
		INTO vFromDated, vToDated;
		
	IF vToDated >= CURDATE() THEN

		SET vToDated = TIMESTAMPADD(SECOND,-1,CURDATE());
        SET isDone = TRUE;

	END IF;
    
    INSERT INTO bs.manaCustomer(Id_Cliente, Mana)
		SELECT Id_Cliente, newMana 
			FROM
				(SELECT cs.Id_Cliente, - sum(Cantidad * Valor) as newMana
					FROM vn2008.Tickets t
						JOIN vn2008.Consignatarios cs using(Id_Consigna)
						JOIN vn2008.Movimientos m using(Id_Ticket)
						JOIN vn2008.Movimientos_componentes mc using(Id_Movimiento)
					WHERE Id_Componente IN (39, 37) -- maná auto y maná
						AND Fecha BETWEEN vFromDated AND vToDated
					GROUP BY cs.Id_Cliente
				) t1
			ON DUPLICATE KEY UPDATE Mana = Mana + newMana;
    
    SELECT 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 `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;

    WHILE timestampadd(week,1,vFromDated) < CURDATE() DO

        SELECT
                timestampadd(week,1,vFromDated),
                timestampadd(week,-4,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 Fecha > vFromDated 
                            AND 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 `mana_price_modifier_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 `mana_price_modifier_update`()
BEGIN

INSERT INTO vn2008.daily_task_log(consulta) 
VALUES ('bs.mana_price_modifier_update');

UPDATE mana_spellers
JOIN
	(SELECT Id_Trabajador, floor(sum(importe)/12) as pesoCarteraMensual
     FROM bs.vendedores v
     WHERE año * 100 + mes >= (year(curdate()) -1) * 100 + month(curdate())
     GROUP BY Id_Trabajador
	) ultimo_año_de_ventas using(Id_Trabajador)
SET prices_modifier_rate =  GREATEST(-0.05,LEAST(0.05,round(- used/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 `nightly_tasks` */;
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 `nightly_tasks`()
BEGIN

DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN 
	INSERT INTO vn2008.mail SET `to` = 'informatica@verdnatura.es', subject = 'bs.nightly_tasks', `text` = CONCAT('ERROR ', @errno, ' (', @sqlstate, '): ', @text);
    INSERT INTO vn2008.mail SET `to` = 'pako@verdnatura.es', subject = 'bs.nightly_tasks', `text` = CONCAT('ERROR ', @errno, ' (', @sqlstate, '): ', @text);
END;

	insert into vn2008.daily_task_log(consulta) VALUES('arranca el event bs.nightly_tasks');
    
    call bancos_evolution_add;
    
    call fondo_evolution_add;
    
    call ventas_add(timestampadd(month,-1,curdate()),curdate());
    
    call ventas_contables_add(YEAR(TIMESTAMPADD(MONTH,-1,CURDATE())), MONTH(TIMESTAMPADD(MONTH,-1,CURDATE())));
    
    call bs.vendedores_add(year(curdate()), month(curdate()));
    
    call bs.vendedores_add(year(timestampadd(month,-1,curdate()))
						, month(timestampadd(month,-1,curdate()))
                          );
                          
    call carteras_add;
    
    call vn2008.mana_inventory_requery;
    
    call bs.mana_price_modifier_update;
    
    call bs.manaCustomerUpdate;
    
    insert into vn2008.daily_task_log(consulta) VALUES('finalitza el event bs.nightly_tasks');
    
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 `nightTaskLauncher` */;
/*!50003 SET @saved_cs_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 `nightTaskLauncher`()
BEGIN

	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vSchema VARCHAR(255);
    DECLARE vProcedure VARCHAR(255);
    DECLARE vId INT;

	DECLARE rs CURSOR FOR
			SELECT id,`schema`, `procedure` 
				FROM bs.nightTask 
                WHERE IFNULL(finished,0) <= CURDATE()
				ORDER BY `order`;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vId, vSchema, vProcedure;

	WHILE NOT done DO

		SELECT vId, vSchema, vProcedure;

		UPDATE bs.nightTask
			SET started = now()
			WHERE id = vId;

		CALL util.exec (sql_printf('CALL %s.%s',vSchema, vProcedure)); 
        
		UPDATE bs.nightTask
			SET finished = now()
			WHERE id = vId;

		FETCH rs INTO vId, vSchema, vProcedure;

	END WHILE;

	CLOSE rs;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nocturnEvent_Tickets_Bionizar` */;
/*!50003 SET @saved_cs_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 `nocturnEvent_Tickets_Bionizar`()
BEGIN

DECLARE MyDate DATE;
/*
 DECLARE EXIT HANDLER FOR SQLEXCEPTION 
 BEGIN 

	GET DIAGNOSTICS CONDITION 2 @errno = MYSQL_ERRNO, @text = MESSAGE_TEXT;
	SELECT CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto'));
	INSERT INTO vn2008.mail (`to`,`subject`,`text`)  VALUES ('jgallego@verdnatura.es', 'nocturnEvent_Tickets_Bionizar' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')));
	INSERT INTO vn2008.mail (`to`,`subject`,`text`)  VALUES ('pako@verdnatura.es', 'nocturnEvent_Tickets_Bionizar' ,CONCAT('ERROR ', IFNULL(@errno,0), ': ', ifnull(@text,'texto')));

END;
*/


SET MyDate = timestampadd(week,-1,curdate());

	INSERT INTO vn2008.daily_task_log(consulta) VALUES('Comença la rebionització de tickets ');

WHILE MyDate < CURDATE() DO

	CALL `vn2008`.`bionic_tickets_range_bionizar`(MyDate, MyDate);

	SET MyDate = timestampadd(DAY,1,MyDate);

	SELECT MyDate;

END WHILE;

	INSERT INTO vn2008.daily_task_log(consulta) VALUES('finalitza la rebionització de tickets ');


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`(IN intYEAR INT, IN intMONTH INT)
BEGIN

REPLACE vendedores

SELECT c.Id_Trabajador
     , intYEAR
     , intMONTH
     , sum(importe) as importe
     , sum(importe) * 0.029 as comision
     , 0 as comisionCedida
     , 0 as comisionArrendada
     
FROM ventas v
JOIN vn2008.Clientes c on v.Id_Cliente = c.Id_Cliente
JOIN vn2008.time on time.date = v.fecha
WHERE time.year = intYEAR and time.month = intMONTH
AND c.Id_Trabajador is not null
GROUP BY c.Id_Trabajador;

-- Ventas cedidas

UPDATE vendedores
JOIN
(
SELECT cc.Id_Trabajador_old as Id_Trabajador
     , sum(importe) * 0.029 * comision_old as cedido
     
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 
JOIN vn2008.time on time.date = v.fecha
WHERE time.year = intYEAR and time.month = intMONTH
AND c.Id_Trabajador is not null
GROUP BY cc.Id_Trabajador_old
) sub using(Id_Trabajador)
SET comisionCedida = cedido, comision = comision - cedido
WHERE año = intYEAR and mes = intMONTH;

-- Ventas arrendadas

UPDATE vendedores
JOIN
(
SELECT cc.Id_Trabajador_new as Id_Trabajador
     , sum(importe) * 0.029 * comision_new as arrendada
     
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 on time.date = v.fecha
WHERE time.year = intYEAR and time.month = intMONTH
AND c.Id_Trabajador is not null
GROUP BY cc.Id_Trabajador_new
) sub using(Id_Trabajador)
SET comisionArrendada = arrendada, comision = comision - arrendada
WHERE año = intYEAR and mes = intMONTH;


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()), month(curdate()));
    call bs.vendedores_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 `vendedores_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 `vendedores_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.vendedores_evolution;

		WHILE datFEC < CURDATE() DO
        
					SELECT datFEC;

					REPLACE bs.vendedores_evolution(  Id_Trabajador
                                                     , fecha
                                                     , importe)

					SELECT Id_Trabajador
                         , datFEC as fecha
                         , sum(importe) as importe
                         
                    FROM
                    (

							SELECT Id_Trabajador
								 , importe
							FROM bs.vendedores_evolution
							WHERE fecha = TIMESTAMPADD(DAY,-1,datFEC)  -- las ventas acumuladas del dia anterior
			
							UNION ALL
							
							SELECT c.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.Movimientos m using(Id_Movimiento)
							JOIN vn2008.Tickets t using(Id_Ticket)
							JOIN vn2008.Consignatarios cs using(Id_Consigna)
							JOIN vn2008.Clientes c on cs.Id_Cliente = c.Id_Cliente
							JOIN vn2008.Tipos using(tipo_id)
							WHERE v.fecha IN (datFEC, TIMESTAMPADD(DAY,-365,datFEC))
                            AND c.Id_Trabajador is not null
							AND (Id_Article = 98 or Id_Article = 95 or reino_id != 6)
							GROUP BY c.Id_Trabajador
														
                            
					)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 `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 vStartingPeriod INT;
DECLARE vStartingDate DATETIME;
DECLARE vEndingDate DATETIME;
DECLARE TIPO_PATRIMONIAL INT DEFAULT 188;

SET datEND = vn2008.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


-- Ventes bioniques
																										SELECT vStartingDate,vEndingDate, datEND;

		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
		JOIN vn2008.empresa e on e.id = empresa_id
		WHERE t.Fecha between vStartingDate and vEndingDate
        AND datEND >= '2015-10-01'
        AND (
			c.`Real` != 0 
			OR c.Razonsocial = 'MIRIAM FERRER TORIBIO' 
            OR c.Razonsocial = 'VERDNATURA COMPLEMENTOS' 
            )
		AND 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;
        
/*
UPDATE vn2008.Movimientos m
JOIN bs.ventas v ON v.Id_Movimiento = m.Id_Movimiento
SET m.Costfixat = IFNULL(round(v.importe/m.Cantidad,2),0)
WHERE v.fecha between vStartingDate and vEndingDate;
*/

	SET vStartingDate = TIMESTAMPADD(DAY,1, vStartingDate);
	SET vEndingDate = vn2008.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_contables_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 `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  
			+ IF(tp.Id_Trabajador = 24 , 7,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 */ ;
ALTER DATABASE `bs` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!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 */ ;











-- Dump completed on 2017-12-27  7:52:59
