-- MySQL dump 10.13  Distrib 5.7.17, for Win64 (x86_64)
--
-- Host: db.verdnatura.es    Database: edi
-- ------------------------------------------------------
-- 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: `edi`
--

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

USE `edi`;

--
-- Table structure for table `PriceDetails`
--

DROP TABLE IF EXISTS `PriceDetails`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `PriceDetails` (
  `ID` int(11) NOT NULL,
  `SuplyResponseID` int(11) NOT NULL,
  `PriceType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `Price` decimal(10,2) DEFAULT NULL,
  `BasisQuantitiy` int(11) DEFAULT NULL,
  `BasisQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `MinimumQuantity` int(11) DEFAULT NULL,
  `MinimumQuantityType` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `MaximumQuantity Integer` int(11) DEFAULT NULL,
  `MaximumQuantityType` varchar(255) COLLATE utf8_unicode_ci 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 `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=274346 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 AUTO_INCREMENT,
  `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,
  `supplyResponseID` int(11) 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=293788 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 `putOrder`
--

DROP TABLE IF EXISTS `putOrder`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `putOrder` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `deliveryInformationID` int(11) DEFAULT NULL,
  `supplyResponsID` int(11) DEFAULT NULL,
  `orderTradelineItemID` int(11) DEFAULT NULL COMMENT 'ticketFk',
  `OrderTradeLineDateTime` datetime DEFAULT NULL,
  `quantity` int(11) DEFAULT NULL,
  `EndUserPartyID` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `EndUserPartyGLN` tinyint(4) DEFAULT NULL,
  `OrderStatus` int(11) DEFAULT NULL COMMENT '1 pending\n2 confirmed\n3 canceled',
  `isOrderProcessed` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `orderTradelineItemID_UNIQUE` (`orderTradelineItemID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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 AUTO_INCREMENT,
  `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,
  `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,
  `CountryOfOrigin` 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,
  `AgentGLN` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `MaximumNumberToOrder` int(11) DEFAULT NULL,
  `MaximumOrderType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley',
  `IncrementalOrderableQuantity` int(11) DEFAULT NULL,
  `IncrementalOrderableQuantityType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley',
  `PackingPrice` decimal(10,2) DEFAULT NULL,
  `PackingPriceType` varchar(25) COLLATE utf8_unicode_ci DEFAULT NULL,
  `PackingPriceQuantity` int(11) DEFAULT NULL,
  `PackingQuantityType` tinyint(1) DEFAULT NULL COMMENT 'Unit: 1 = piece, 2 = bunch, 3 = box, 4 = layer, 5 = load carrier/trolley',
  `MarketPlaceID` 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: `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=8715620 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: `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=61385 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(), reserveTime) INTO v_reserve_date
		FROM hedera.orderConfig;
	
    -- 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(), reserveTime) INTO v_reserve_date
		FROM hedera.orderConfig;
	
    -- 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`(vWarehouseId INT)
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 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; 

	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;
			
			-- 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 = vWarehouseId
		AND fecha = CURDATE();

		REPLACE cache.departure_limit(warehouse_id, fecha, hora, minSpeed)
		VALUES (vWarehouseId, 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` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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`(vWarehouseId INT)
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 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; 

OPEN rs;

FETCH rs INTO rsDeparture, rsHoras , rsInicio;

SELECT rsDeparture, rsHoras , rsInicio,  vWarehouseId, 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 (vWarehouseId, 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 */ ;
/*!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_refreshkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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_refreshkk`()
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 */ ;
/*!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: `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 */;

--
-- 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 */;

--
-- 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 */;

--
-- 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 */;

--
-- 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 */;

--
-- 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;
DECLARE vOneYearAgo DATETIME;

SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
SET vDateLong = TIMESTAMPADD(MONTH, -18,CURDATE());
SET vOneYearAgo = TIMESTAMPADD(YEAR, -1,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) 
    OR Fecha < vOneYearAgo;

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

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

USE `vn`;

--
-- Table structure for table `accountingType`
--

DROP TABLE IF EXISTS `accountingType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accountingType` (
  `id` smallint(6) NOT NULL DEFAULT '0',
  `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='descripcio dels valors de la columna "cash" de la taula vn2008.Bancios';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `activityTaxDismissed`
--

DROP TABLE IF EXISTS `activityTaxDismissed`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `activityTaxDismissed` (
  `clientFk` int(11) NOT NULL,
  `isNotified` tinyint(1) DEFAULT '0',
  `isDismissed` tinyint(1) DEFAULT '0',
  `notified` int(11) DEFAULT '0',
  PRIMARY KEY (`clientFk`),
  CONSTRAINT `clientFk` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `addressForPackaging`
--

DROP TABLE IF EXISTS `addressForPackaging`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `addressForPackaging` (
  `addressFk` int(11) NOT NULL,
  `packagingValue` decimal(10,2) NOT NULL DEFAULT '0.04',
  PRIMARY KEY (`addressFk`),
  CONSTRAINT `addresForPackaging_fk1` FOREIGN KEY (`addressFk`) REFERENCES `vn2008`.`Consignatarios` (`id_consigna`) 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 `autonomousRegion`
--

DROP TABLE IF EXISTS `autonomousRegion`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `autonomousRegion` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  `countryFk` mediumint(8) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `countryFk` (`countryFk`),
  CONSTRAINT `countryFk` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `bookingPlanner`
--

DROP TABLE IF EXISTS `bookingPlanner`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `bookingPlanner` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `pgcFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `taxAreaFk` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'SPAIN',
  `priority` int(2) unsigned DEFAULT NULL,
  `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `countryFk` mediumint(8) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `taxArea_bookingPlanner_idx` (`taxAreaFk`),
  KEY `pgcFk_bookingPlanner_idx` (`pgcFk`),
  KEY `taxClassFk` (`taxClassFk`),
  KEY `countryFk` (`countryFk`),
  CONSTRAINT `bookingPlanner_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE,
  CONSTRAINT `bookingPlanner_ibfk_2` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON DELETE CASCADE,
  CONSTRAINT `bookingPlanner_ibfk_3` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON DELETE CASCADE,
  CONSTRAINT `taxArea_bookingPlanner` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=81 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendarHolidays`
--

DROP TABLE IF EXISTS `calendarHolidays`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendarHolidays` (
  `calendarHolidaysTypeFk` int(11) NOT NULL,
  `dated` date NOT NULL,
  `calendarHolidaysNameFk` int(11) DEFAULT NULL,
  `workCenterFk` int(11) NOT NULL,
  PRIMARY KEY (`dated`,`workCenterFk`),
  KEY `calendarholidaystypeFk_idx` (`calendarHolidaysTypeFk`),
  KEY `calendarHolidaysNameFk_idx` (`calendarHolidaysNameFk`),
  KEY `workCenterFk_idx` (`workCenterFk`),
  CONSTRAINT `calendarHolidaysNameFk` FOREIGN KEY (`calendarHolidaysNameFk`) REFERENCES `calendarHolidaysName` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `calendarholidaystypeFk` FOREIGN KEY (`calendarHolidaysTypeFk`) REFERENCES `calendarHolidaysType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `workCenterFk` FOREIGN KEY (`workCenterFk`) REFERENCES `workCenter` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendarHolidaysName`
--

DROP TABLE IF EXISTS `calendarHolidaysName`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendarHolidaysName` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=21 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `calendarHolidaysType`
--

DROP TABLE IF EXISTS `calendarHolidaysType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `calendarHolidaysType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `hexColour` char(7) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `category`
--

DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `nick` varchar(3) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `clientCreditLimit`
--

DROP TABLE IF EXISTS `clientCreditLimit`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientCreditLimit` (
  `id` int(11) NOT NULL,
  `maxAmount` int(10) unsigned NOT NULL,
  `roleFk` int(10) unsigned 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 `clientLog`
--

DROP TABLE IF EXISTS `clientLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `clientLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `originFk` (`originFk`),
  KEY `userFk` (`userFk`),
  CONSTRAINT `clientLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `clientLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=15113 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `confectionType`
--

DROP TABLE IF EXISTS `confectionType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `confectionType` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `description` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `mdbServer` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `fakeEmail` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `defaultersMaxAmount` int(10) DEFAULT '200' COMMENT 'maxima deuda permitida a partir de la cual se bloquea a un usuario',
  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 `cplusCorrectingType`
--

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

--
-- Table structure for table `cplusInvoiceType472`
--

DROP TABLE IF EXISTS `cplusInvoiceType472`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusInvoiceType472` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)SOPORTADO – DEDUCIBLE (472)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cplusInvoiceType477`
--

DROP TABLE IF EXISTS `cplusInvoiceType477`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusInvoiceType477` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*18) TIPO FACTURA (Asientos)REPERCUTIDO - DEVENGADO (477)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cplusRectificationType`
--

DROP TABLE IF EXISTS `cplusRectificationType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusRectificationType` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*20) TIPO RECTIFICATIVA (Asientos)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cplusSubjectOp`
--

DROP TABLE IF EXISTS `cplusSubjectOp`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusSubjectOp` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*17) TIPO OPERACIÓN SUJETA/NO SUJETA (Asientos)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cplusTaxBreak`
--

DROP TABLE IF EXISTS `cplusTaxBreak`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusTaxBreak` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*16) TIPO EXENCIÓN (Asientos)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cplusTerIdNif`
--

DROP TABLE IF EXISTS `cplusTerIdNif`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusTerIdNif` (
  `id` int(11) NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 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 `cplusTrascendency472`
--

DROP TABLE IF EXISTS `cplusTrascendency472`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusTrascendency472` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos)SOPORTADO – DEDUCIBLE (472)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `cplusTrascendency477`
--

DROP TABLE IF EXISTS `cplusTrascendency477`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `cplusTrascendency477` (
  `id` int(10) unsigned NOT NULL,
  `description` varchar(255) CHARACTER SET utf8 NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='(*15) CLAVE DE RÉGIMEN ESPECIAL O TRASCENDENCIA(Asientos) REPERCUTIDO - DEVENGADO (477)';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `creditClassification`
--

DROP TABLE IF EXISTS `creditClassification`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `creditClassification` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `client` int(11) NOT NULL,
  `dateStart` date NOT NULL,
  `dateEnd` date DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `creditClassifClientFk_idx` (`client`),
  KEY `creditClassifdateEnd_idx` (`dateEnd`),
  CONSTRAINT `creditClassifClientFk` FOREIGN KEY (`client`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=2626 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` 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 `vn`.`creditClassification_BEFORE_UPDATE` BEFORE UPDATE ON `creditClassification` FOR EACH ROW
BEGIN
	IF NEW.client <> OLD.client THEN
		CALL util.throw('NOT_ALLOWED_CHANGE_CLIENT');
    END IF;
    IF NEW.dateEnd IS NOT NULL AND OLD.dateEnd IS NULL THEN
		UPDATE vn2008.Clientes c
			SET creditInsurance = 0 WHERE c.Id_cliente = NEW.client;
    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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Table structure for table `creditInsurance`
--

DROP TABLE IF EXISTS `creditInsurance`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `creditInsurance` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `creditClassification` int(11) DEFAULT NULL,
  `credit` int(11) DEFAULT NULL,
  `creationDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `grade` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `CreditInsurance_Fk1_idx` (`creditClassification`),
  CONSTRAINT `CreditInsurance_Fk1` FOREIGN KEY (`creditClassification`) REFERENCES `creditClassification` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=1679 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Detalla los clientes que tienen seguro de credito';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` 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 `vn`.`creditInsurance_AFTER_INSERT` AFTER INSERT ON `creditInsurance` FOR EACH ROW
BEGIN
	UPDATE vn2008.Clientes c
		JOIN vn.creditClassification  cc ON cc.client = c.Id_Cliente
        SET creditInsurance = NEW.credit WHERE cc.id = NEW.creditClassification;
        
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- 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;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `deliveryError`
--

DROP TABLE IF EXISTS `deliveryError`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `deliveryError` (
  `ticket` int(11) NOT NULL,
  `description` varchar(255) CHARACTER SET latin1 NOT NULL,
  `worker` int(11) NOT NULL,
  `creation_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY `errorTickets_idx` (`ticket`),
  KEY `errorWorker_idx` (`worker`),
  CONSTRAINT `errorTickets` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `errorWorker` FOREIGN KEY (`worker`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `entryLog`
--

DROP TABLE IF EXISTS `entryLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `entryLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `userFk` (`userFk`),
  KEY `logEntry_ibfk_1` (`originFk`),
  CONSTRAINT `entryLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Entradas` (`Id_Entrada`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `entryLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=24376 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `excuse`
--

DROP TABLE IF EXISTS `excuse`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `excuse` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `txt` varchar(255) CHARACTER SET latin1 NOT NULL,
  `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `gateArea`
--

DROP TABLE IF EXISTS `gateArea`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `gateArea` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `inkI18n`
--

DROP TABLE IF EXISTS `inkI18n`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `inkI18n` (
  `inkFk` char(3) COLLATE utf8_unicode_ci NOT NULL,
  `lang` char(2) CHARACTER SET utf8 NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`inkFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceCorrectionType`
--

DROP TABLE IF EXISTS `invoiceCorrectionType`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceCorrectionType` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `description` varchar(100) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `description_UNIQUE` (`description`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceInSerial`
--

DROP TABLE IF EXISTS `invoiceInSerial`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceInSerial` (
  `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cplusTerIdNifFk` int(11) NOT NULL DEFAULT '1',
  `taxAreaFk` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`code`),
  KEY `InvoiceInSerial_Fk1_idx` (`cplusTerIdNifFk`),
  KEY `InvoiceInSerial_Fk1_idx1` (`taxAreaFk`),
  CONSTRAINT `InvoiceInSerial_Fk1` FOREIGN KEY (`cplusTerIdNifFk`) REFERENCES `cplusTerIdNif` (`id`),
  CONSTRAINT `InvoiceInSerial_Fk2` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceOutExpence`
--

DROP TABLE IF EXISTS `invoiceOutExpence`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutExpence` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `invoiceOutFk` int(10) unsigned NOT NULL,
  `amount` decimal(10,2) NOT NULL DEFAULT '0.00',
  `expenceFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `invoiceOutExpence_restriccion` (`expenceFk`,`invoiceOutFk`),
  KEY `invoiceOutExpence_FK_1_idx` (`invoiceOutFk`),
  KEY `invoiceOutExpence_FK_2_idx` (`expenceFk`),
  CONSTRAINT `invoiceOutExpence_FK_1` FOREIGN KEY (`invoiceOutFk`) REFERENCES `vn2008`.`Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `invoiceOutExpence_FK_2` FOREIGN KEY (`expenceFk`) REFERENCES `vn2008`.`Gastos` (`Id_Gasto`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=45362 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Desglosa la base imponible de una factura en funcion del tipo de gasto/venta';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceOutSerial`
--

DROP TABLE IF EXISTS `invoiceOutSerial`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutSerial` (
  `code` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
  `description` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `isTaxed` tinyint(1) NOT NULL DEFAULT '1',
  `taxAreaFk` varchar(15) COLLATE utf8_unicode_ci NOT NULL DEFAULT 'NATIONAL',
  `isCEE` tinyint(1) NOT NULL DEFAULT '0',
  `cplusInvoiceType477Fk` int(10) unsigned DEFAULT '1',
  PRIMARY KEY (`code`),
  KEY `taxAreaFk_idx` (`taxAreaFk`),
  CONSTRAINT `invoiceOutSerial_ibfk_1` FOREIGN KEY (`taxAreaFk`) REFERENCES `taxArea` (`code`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `invoiceOutTax`
--

DROP TABLE IF EXISTS `invoiceOutTax`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `invoiceOutTax` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `invoiceOutFk` int(10) unsigned NOT NULL,
  `taxableBase` decimal(10,2) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `vat` decimal(10,2) NOT NULL DEFAULT '0.00',
  `pgcFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL DEFAULT '0000000000',
  PRIMARY KEY (`id`),
  UNIQUE KEY `invoiceOutTax_Resctriccion` (`invoiceOutFk`,`pgcFk`),
  KEY `invoiceOutFk_idx` (`invoiceOutFk`),
  KEY `pgcFk` (`pgcFk`),
  CONSTRAINT `invoiceOutFk` FOREIGN KEY (`invoiceOutFk`) REFERENCES `vn2008`.`Facturas` (`factura_id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `invoiceOutTax_ibfk_1` FOREIGN KEY (`pgcFk`) REFERENCES `pgc` (`code`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=855453 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemCategoryI18n`
--

DROP TABLE IF EXISTS `itemCategoryI18n`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemCategoryI18n` (
  `categoryFk` int(10) unsigned NOT NULL,
  `lang` char(2) CHARACTER SET utf8 NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`categoryFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemConversor`
--

DROP TABLE IF EXISTS `itemConversor`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemConversor` (
  `espItemFk` int(11) NOT NULL,
  `genItemFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`espItemFk`),
  KEY `itemConversor_fk2_idx` (`genItemFk`),
  CONSTRAINT `itemConversor_fk1` FOREIGN KEY (`espItemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `itemConversor_fk2` FOREIGN KEY (`genItemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona los item específicos con los genéricos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemTag`
--

DROP TABLE IF EXISTS `itemTag`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTag` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) NOT NULL,
  `tagFk` int(11) NOT NULL,
  `value` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
  `priority` int(2) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `priorityItem` (`itemFk`,`priority`),
  KEY `tagFk` (`tagFk`,`value`),
  CONSTRAINT `itemFK` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14178 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemTagArranged`
--

DROP TABLE IF EXISTS `itemTagArranged`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTagArranged` (
  `itemFk` int(11) NOT NULL,
  `tag1` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `val1` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag2` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `val2` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag3` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `val3` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag4` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `val4` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `val5` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `tag6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `val6` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`itemFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Cache de columnas de características de artículo';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemTaxCountry`
--

DROP TABLE IF EXISTS `itemTaxCountry`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTaxCountry` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `itemFk` int(11) DEFAULT NULL,
  `countryFk` mediumint(8) unsigned DEFAULT NULL,
  `taxClassFk` tinyint(3) unsigned NOT NULL DEFAULT '1',
  `effectived` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `taxClassFK_idx` (`taxClassFk`),
  KEY `countryFK_paises_idx` (`countryFk`),
  KEY `itemFK_Article_idx` (`itemFk`),
  CONSTRAINT `countryFK_paises` FOREIGN KEY (`countryFk`) REFERENCES `vn2008`.`Paises` (`Id`) ON UPDATE CASCADE,
  CONSTRAINT `itemFK_Article` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `taxClassFK_Iva_Group` FOREIGN KEY (`taxClassFk`) REFERENCES `vn2008`.`iva_group` (`iva_group_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=437545 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Define la clase de iva por artículo y pais';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemTypeI18n`
--

DROP TABLE IF EXISTS `itemTypeI18n`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemTypeI18n` (
  `typeFk` smallint(5) unsigned NOT NULL,
  `lang` char(2) CHARACTER SET utf8 NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`typeFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `itemVerdecora`
--

DROP TABLE IF EXISTS `itemVerdecora`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `itemVerdecora` (
  `itemFk` int(11) NOT NULL,
  `codin` int(11) DEFAULT NULL,
  PRIMARY KEY (`itemFk`),
  CONSTRAINT `itemVerdecora_fk1` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Relaciona nuestros articulos con los de Verdecora';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `mailTemplates`
--

DROP TABLE IF EXISTS `mailTemplates`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `mailTemplates` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) CHARACTER SET utf8 NOT NULL,
  `attachmentPath` text CHARACTER SET utf8 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 `manuscript`
--

DROP TABLE IF EXISTS `manuscript`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `manuscript` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` varchar(45) CHARACTER SET utf8 NOT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `enabled` tinyint(1) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `code_UNIQUE` (`code`)
) ENGINE=InnoDB AUTO_INCREMENT=4 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(50) CHARACTER SET utf8 NOT NULL,
  `sender` varchar(50) CHARACTER SET utf8 NOT NULL,
  `recipient` varchar(50) CHARACTER SET utf8 NOT NULL,
  `message` longtext CHARACTER SET utf8,
  `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `sender` (`sender`),
  KEY `recipient` (`recipient`),
  KEY `uuid` (`uuid`(8))
) ENGINE=InnoDB AUTO_INCREMENT=1338735 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(50) CHARACTER SET utf8 NOT NULL,
  `sender` varchar(50) CHARACTER SET utf8 NOT NULL,
  `recipient` varchar(45) CHARACTER SET utf8 NOT NULL,
  `finalRecipient` varchar(50) CHARACTER SET utf8 NOT NULL,
  `message` longtext CHARACTER SET utf8,
  `sendDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `read` varchar(45) CHARACTER SET utf8 NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `uuid` (`uuid`(8)),
  KEY `finalRecipient` (`finalRecipient`)
) ENGINE=InnoDB AUTO_INCREMENT=1482242 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `noticeCategory`
--

DROP TABLE IF EXISTS `noticeCategory`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `noticeCategory` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `keyName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `name` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `subject` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL,
  `description` text COLLATE utf8_unicode_ci,
  `isEnabled` tinyint(1) NOT NULL DEFAULT '1',
  `requiredRole` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  UNIQUE KEY `keyName_UNIQUE` (`keyName`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `noticeSubscription`
--

DROP TABLE IF EXISTS `noticeSubscription`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `noticeSubscription` (
  `noticeCategoryFk` int(11) NOT NULL DEFAULT '0',
  `userFk` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`noticeCategoryFk`,`userFk`),
  KEY `noticeSubscription_ibfk_2` (`userFk`),
  CONSTRAINT `noticeSubscription_ibfk_1` FOREIGN KEY (`noticeCategoryFk`) REFERENCES `noticeCategory` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `noticeSubscription_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `originI18n`
--

DROP TABLE IF EXISTS `originI18n`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `originI18n` (
  `originFk` tinyint(2) unsigned NOT NULL,
  `lang` char(2) CHARACTER SET utf8 NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`originFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `outgoingInvoiceVat`
--

DROP TABLE IF EXISTS `outgoingInvoiceVat`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `outgoingInvoiceVat` (
  `outgoingInvoice` mediumint(8) NOT NULL,
  `taxBase` decimal(12,2) DEFAULT NULL,
  `equalizationTax` decimal(12,2) DEFAULT NULL,
  `Vat` decimal(12,2) DEFAULT NULL,
  PRIMARY KEY (`outgoingInvoice`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `packageEquivalent`
--

DROP TABLE IF EXISTS `packageEquivalent`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `packageEquivalent` (
  `packageFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `equivalentFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`packageFk`,`equivalentFk`),
  KEY `packageEquivalent_fk2_idx` (`equivalentFk`),
  CONSTRAINT `packageEquivalent_fk1` FOREIGN KEY (`packageFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `packageEquivalent_fk2` FOREIGN KEY (`equivalentFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='recoge los modelos de cubos que se han de sustituir a efectos de presentar informes resumidos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `person`
--

DROP TABLE IF EXISTS `person`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `person` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL,
  `surnames` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
  `fi` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL,
  `birth` date DEFAULT NULL,
  `readerId` int(11) DEFAULT NULL,
  `workerFk` int(11) DEFAULT NULL,
  `isDisable` tinyint(1) NOT NULL DEFAULT '0',
  `isFreelance` tinyint(1) NOT NULL DEFAULT '0',
  `isSsDiscounted` tinyint(1) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  UNIQUE KEY `nif` (`fi`),
  KEY `nifIndex` (`fi`),
  KEY `workerFk_idx` (`workerFk`)
) ENGINE=InnoDB AUTO_INCREMENT=818 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `pgc`
--

DROP TABLE IF EXISTS `pgc`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pgc` (
  `code` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `rate` decimal(10,2) NOT NULL,
  `name` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  `cplusTaxBreakFk` int(10) unsigned DEFAULT '1',
  `mod340` tinyint(1) NOT NULL DEFAULT '0',
  `mod347` tinyint(1) NOT NULL DEFAULT '0',
  `cplusTrascendency477Fk` int(10) unsigned DEFAULT '1',
  PRIMARY KEY (`code`),
  KEY `pgc_fk1_idx` (`cplusTaxBreakFk`),
  KEY `pgc_fk2_idx` (`cplusTrascendency477Fk`),
  CONSTRAINT `pgc_fk1` FOREIGN KEY (`cplusTaxBreakFk`) REFERENCES `cplusTaxBreak` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `pgc_fk2` FOREIGN KEY (`cplusTrascendency477Fk`) REFERENCES `cplusTrascendency477` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Plan General Contable';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `pgcEqu`
--

DROP TABLE IF EXISTS `pgcEqu`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `pgcEqu` (
  `vatFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Cuenta de IVA',
  `equFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL COMMENT 'Cuenta de recargo de equivalencia',
  PRIMARY KEY (`vatFk`,`equFk`),
  KEY `pgcEqu_fk2_idx` (`equFk`),
  CONSTRAINT `pgcEqu_fk1` FOREIGN KEY (`vatFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `pgcEqu_fk2` FOREIGN KEY (`equFk`) REFERENCES `pgc` (`code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Recoge las cuentas contables con recargo de equivalencia e identifica a la que corresponde al iva y la que corresponde al recargo';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `postCode`
--

DROP TABLE IF EXISTS `postCode`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `postCode` (
  `code` varchar(10) CHARACTER SET latin1 NOT NULL,
  `townFk` int(11) NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`code`),
  KEY `postCode_ix1` (`townFk`),
  KEY `postCode_ix2` (`geoFk`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `profile`
--

DROP TABLE IF EXISTS `profile`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `profile` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `personFk` int(11) DEFAULT NULL,
  `profileTypeFk` int(11) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`),
  KEY `personFk` (`personFk`),
  KEY `profileTypeFk` (`profileTypeFk`),
  CONSTRAINT `profile_ibfk_1` FOREIGN KEY (`personFk`) REFERENCES `person` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `profile_ibfk_2` FOREIGN KEY (`profileTypeFk`) REFERENCES `profileType` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=697 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `profileType`
--

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

--
-- Table structure for table `routeGate`
--

DROP TABLE IF EXISTS `routeGate`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeGate` (
  `deviceId` varchar(30) CHARACTER SET utf8 NOT NULL,
  `displayText` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `status` set('idle','doing','done','') CHARACTER SET utf8 DEFAULT 'idle',
  `gateAreaFk` int(11) NOT NULL DEFAULT '1',
  `routeFk` int(11) DEFAULT NULL,
  `freeTickets` int(11) DEFAULT NULL,
  `expeditions` int(11) DEFAULT NULL,
  `scanned` int(11) DEFAULT NULL,
  `flag` blob,
  `pallets` int(11) DEFAULT NULL,
  `lastScanned` datetime DEFAULT NULL,
  PRIMARY KEY (`deviceId`),
  UNIQUE KEY `routeFk_UNIQUE` (`routeFk`),
  KEY `routeGate_fk1_idx` (`gateAreaFk`)
) ENGINE=InnoDB 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 `vn`.`routeGateBeforeUpdate`
	BEFORE UPDATE ON `routeGate`
    FOR EACH ROW
BEGIN
	IF (NOT (NEW.expeditions <=> OLD.expeditions)
		OR NOT (NEW.scanned <=> OLD.scanned))
		AND NEW.status <=> OLD.status
	THEN
		IF NEW.expeditions = 0
        THEN
			SET NEW.status = 'idle';
		ELSEIF NEW.expeditions = NEW.scanned
        THEN
			SET NEW.status = 'done';
        ELSE
			SET NEW.status = 'doing';
        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 */ ;

--
-- Table structure for table `routeLog`
--

DROP TABLE IF EXISTS `routeLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `routeLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=327142 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `sms`
--

DROP TABLE IF EXISTS `sms`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `sms` (
  `id` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `senderFk` int(11) NOT NULL,
  `destinationFk` int(11) DEFAULT NULL,
  `sender` varchar(15) CHARACTER SET utf8 NOT NULL DEFAULT '693474205',
  `destination` varchar(15) CHARACTER SET utf8 NOT NULL,
  `message` varchar(160) COLLATE utf8_unicode_ci NOT NULL,
  `statusCode` smallint(9) NOT NULL DEFAULT '0',
  `status` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=87324 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `smsConfig`
--

DROP TABLE IF EXISTS `smsConfig`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `smsConfig` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `uri` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `user` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `password` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  `title` varchar(50) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='SMS configuration parameters';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `solunionCAP`
--

DROP TABLE IF EXISTS `solunionCAP`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `solunionCAP` (
  `creditInsurance` int(11) NOT NULL,
  `dateStart` date NOT NULL,
  `dateEnd` date NOT NULL,
  `dateLeaving` date DEFAULT NULL,
  PRIMARY KEY (`creditInsurance`,`dateStart`),
  KEY `solunionCAPdateLeavingIdx` (`dateLeaving`),
  CONSTRAINT `solunionCAP` FOREIGN KEY (`creditInsurance`) REFERENCES `creditInsurance` (`id`) 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 `vn` 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 `vn`.`solunionCAP_AFTER_INSERT` AFTER INSERT ON `solunionCAP` FOR EACH ROW
BEGIN
	UPDATE vn2008.Clientes c
		JOIN creditClassification cc ON c.Id_Cliente = cc.client 
		JOIN creditInsurance ci ON ci.creditClassification = cc.id
	SET creditInsurance = ci.credit * 2 WHERE ci.id = NEW.creditInsurance;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `vn` 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 `vn`.`solunionCAP_AFTER_UPDATE` AFTER UPDATE ON `solunionCAP` FOR EACH ROW
BEGIN
	IF NEW.dateLeaving IS NOT NULL THEN
		UPDATE vn2008.Clientes c
			JOIN creditClassification cc ON c.Id_Cliente = cc.client 
			JOIN creditInsurance ci ON ci.creditClassification = cc.id
		SET creditInsurance = ci.credit WHERE ci.id = OLD.creditInsurance;
	ELSE
		UPDATE vn2008.Clientes c
			JOIN creditClassification cc ON c.Id_Cliente = cc.client 
			JOIN creditInsurance ci ON ci.creditClassification = cc.id
		SET creditInsurance = ci.credit * 2 WHERE ci.id = OLD.creditInsurance;
	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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
ALTER DATABASE `vn` 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 `vn`.`solunionCAP_BEFORE_DELETE` BEFORE DELETE ON `solunionCAP` FOR EACH ROW
BEGIN
	UPDATE vn2008.Clientes c
		JOIN creditClassification cc ON c.Id_Cliente = cc.client 
		JOIN creditInsurance ci ON ci.creditClassification = cc.id
	SET creditInsurance = ci.credit  WHERE ci.id = OLD.creditInsurance;
END */;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Table structure for table `stockBuyed`
--

DROP TABLE IF EXISTS `stockBuyed`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `stockBuyed` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user` int(10) unsigned DEFAULT NULL,
  `buyed` decimal(10,2) DEFAULT NULL,
  `date` date DEFAULT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `reserved` decimal(10,2) DEFAULT NULL,
  `requested` decimal(10,2) DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `date_UNIQUE` (`date`,`user`),
  KEY `stockBuyed_user_idx` (`user`),
  CONSTRAINT `stockBuyedUserFk` FOREIGN KEY (`user`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=222154 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tag`
--

DROP TABLE IF EXISTS `tag`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tag` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) CHARACTER SET utf8 NOT NULL,
  `free` tinyint(1) NOT NULL DEFAULT '1',
  `isQuantitatif` tinyint(4) NOT NULL DEFAULT '1',
  `sourceTable` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `unit` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=67 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Categorias para etiquetar los productos';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `tagI18n`
--

DROP TABLE IF EXISTS `tagI18n`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `tagI18n` (
  `tagFk` int(10) unsigned NOT NULL,
  `lang` char(2) CHARACTER SET utf8 NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`tagFk`,`lang`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `taxArea`
--

DROP TABLE IF EXISTS `taxArea`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `taxArea` (
  `code` varchar(15) COLLATE utf8_unicode_ci NOT NULL,
  `ClaveOperacionFactura` varchar(1) COLLATE utf8_unicode_ci DEFAULT NULL,
  `CodigoTransaccion` int(2) 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 `ticketLog`
--

DROP TABLE IF EXISTS `ticketLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `action` set('insert','update','delete','select') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `logTicketoriginFk` (`originFk`),
  KEY `logTicketuserFk` (`userFk`),
  CONSTRAINT `ticketLog_ibfk_1` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketLog_ibfk_2` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=265343 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ticketPackage`
--

DROP TABLE IF EXISTS `ticketPackage`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketPackage` (
  `ticket` int(11) NOT NULL,
  `counter` int(10) unsigned NOT NULL DEFAULT '0',
  PRIMARY KEY (`ticket`),
  CONSTRAINT `ticketPackage_ticketFk` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) 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 `ticketPackaging`
--

DROP TABLE IF EXISTS `ticketPackaging`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketPackaging` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `ticketFk` int(11) NOT NULL,
  `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `quantity` int(10) DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `pvp` double DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `ticketPackaging_fk1_idx` (`ticketFk`),
  KEY `ticketPackaging_fk2_idx` (`packagingFk`),
  CONSTRAINT `ticketPackaging_fk1` FOREIGN KEY (`ticketFk`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketPackaging_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5454 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `ticketPackagingStartingStock`
--

DROP TABLE IF EXISTS `ticketPackagingStartingStock`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketPackagingStartingStock` (
  `clientFk` int(11) NOT NULL,
  `packagingFk` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
  `itemFk` int(11) NOT NULL,
  `sent` int(11) DEFAULT NULL,
  `returned` int(11) DEFAULT NULL,
  PRIMARY KEY (`clientFk`,`packagingFk`),
  KEY `ticketPackagingStartingStock_fk2_idx` (`packagingFk`),
  KEY `ticketPackagingStartingStock_fk3_idx` (`itemFk`),
  CONSTRAINT `ticketPackagingStartingStock_fk1` FOREIGN KEY (`clientFk`) REFERENCES `vn2008`.`Clientes` (`id_cliente`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketPackagingStartingStock_fk2` FOREIGN KEY (`packagingFk`) REFERENCES `vn2008`.`Cubos` (`Id_Cubo`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `ticketPackagingStartingStock_fk3` FOREIGN KEY (`itemFk`) REFERENCES `vn2008`.`Articles` (`Id_Article`) 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 `ticketTrolley`
--

DROP TABLE IF EXISTS `ticketTrolley`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ticketTrolley` (
  `ticket` int(11) NOT NULL,
  `labelCount` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ticket`),
  CONSTRAINT `fk_ticketTrolley_vs_ticket` FOREIGN KEY (`ticket`) REFERENCES `vn2008`.`Tickets` (`Id_Ticket`) 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 `town`
--

DROP TABLE IF EXISTS `town`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `town` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) COLLATE utf8_unicode_ci NOT NULL,
  `provinceFk` smallint(6) unsigned NOT NULL,
  `geoFk` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `provinceFk_idx` (`provinceFk`),
  KEY `town_ix2` (`name`),
  CONSTRAINT `provinceFk` FOREIGN KEY (`provinceFk`) REFERENCES `vn2008`.`province` (`province_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=55237 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `travelObservation`
--

DROP TABLE IF EXISTS `travelObservation`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `travelObservation` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(11) NOT NULL,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Observaciones de travel';
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workCenter`
--

DROP TABLE IF EXISTS `workCenter`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workCenter` (
  `id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(255) DEFAULT NULL,
  `payrollCenterFk` int(11) DEFAULT NULL,
  `counter` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerDocument`
--

DROP TABLE IF EXISTS `workerDocument`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerDocument` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `worker` int(10) unsigned DEFAULT NULL,
  `document` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `workerDocument_ibfk_1` (`worker`),
  KEY `workerDocument_ibfk_2` (`document`),
  CONSTRAINT `workerDocument_ibfk_1` FOREIGN KEY (`worker`) REFERENCES `vn2008`.`Trabajadores` (`user_id`) ON UPDATE CASCADE,
  CONSTRAINT `workerDocument_ibfk_2` FOREIGN KEY (`document`) REFERENCES `vn2008`.`gestdoc` (`id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=3058 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerLog`
--

DROP TABLE IF EXISTS `workerLog`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerLog` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `originFk` int(11) NOT NULL,
  `userFk` int(10) unsigned NOT NULL,
  `action` set('insert','update','delete') COLLATE utf8_unicode_ci NOT NULL,
  `creationDate` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
  `description` text COLLATE utf8_unicode_ci NOT NULL,
  PRIMARY KEY (`id`),
  KEY `workerFk_idx` (`originFk`),
  KEY `userFk_idx` (`userFk`),
  CONSTRAINT `userFk` FOREIGN KEY (`userFk`) REFERENCES `account`.`user` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `workerFk` FOREIGN KEY (`originFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=1154 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workerTeam_kk`
--

DROP TABLE IF EXISTS `workerTeam_kk`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workerTeam_kk` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `team` int(11) NOT NULL,
  `user` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_team_idx` (`user`),
  CONSTRAINT `user_team` FOREIGN KEY (`user`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=77 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `workingHours`
--

DROP TABLE IF EXISTS `workingHours`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `workingHours` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `timeIn` datetime NOT NULL,
  `timeOut` datetime DEFAULT NULL,
  `userId` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `user_working_hour_idx` (`userId`),
  CONSTRAINT `user_working_hour` FOREIGN KEY (`userId`) REFERENCES `account`.`user` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=14428 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci COMMENT='Almacena horas de Entrada y de Salida del personal';
/*!40101 SET character_set_client = @saved_cs_client */;
ALTER DATABASE `vn` 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 `vn`.`workingHoursBeforeInsert` BEFORE INSERT ON `workingHours` FOR EACH ROW
BEGIN
	IF (SELECT COUNT(*) FROM workingHours WHERE userId = NEW.userId AND DATE(timeIn) = CURDATE()) > 0 THEN
		CALL util.throw ('ALREADY_LOGGED');
    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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;

--
-- Table structure for table `zone`
--

DROP TABLE IF EXISTS `zone`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zone` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(45) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL,
  `hour` int(11) NOT NULL,
  `warehouseFk` int(11) NOT NULL,
  `agencyFk` int(11) NOT NULL,
  `travelingDays` int(11) NOT NULL DEFAULT '1',
  `price` double NOT NULL DEFAULT '0',
  `bonus` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`,`name`),
  UNIQUE KEY `name_UNIQUE` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `zoneCalendar`
--

DROP TABLE IF EXISTS `zoneCalendar`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneCalendar` (
  `zoneFk` int(11) NOT NULL,
  `delivered` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`zoneFk`,`delivered`),
  CONSTRAINT `zoneFk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`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 `zoneGeo`
--

DROP TABLE IF EXISTS `zoneGeo`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneGeo` (
  `zoneFk` int(11) NOT NULL,
  `geoFk` int(11) NOT NULL,
  `isIncluded` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`zoneFk`,`geoFk`),
  KEY `geoFk_idx` (`geoFk`),
  CONSTRAINT `geoFk` FOREIGN KEY (`geoFk`) REFERENCES `zoneNest` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
  CONSTRAINT `zoneGeoFk` FOREIGN KEY (`zoneFk`) REFERENCES `zone` (`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 `zoneNest`
--

DROP TABLE IF EXISTS `zoneNest`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneNest` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `lft` int(11) DEFAULT NULL,
  `rgt` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=20944 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `zoneNestTree`
--

DROP TABLE IF EXISTS `zoneNestTree`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `zoneNestTree` (
  `id` int(11) NOT NULL DEFAULT '0',
  `name` varchar(100) COLLATE utf8_unicode_ci DEFAULT NULL,
  `lft` int(11) DEFAULT NULL,
  `rgt` int(11) DEFAULT NULL,
  `depth` bigint(22) NOT NULL DEFAULT '0',
  `sons` decimal(10,0) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping events for database 'vn'
--
/*!50106 SET @save_time_zone= @@TIME_ZONE */ ;
/*!50106 DROP EVENT IF EXISTS `ticketClosure` */;
DELIMITER ;;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;;
/*!50003 SET character_set_client  = utf8mb4 */ ;;
/*!50003 SET character_set_results = utf8mb4 */ ;;
/*!50003 SET collation_connection  = utf8mb4_general_ci */ ;;
/*!50003 SET @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 `ticketClosure` ON SCHEDULE EVERY 1 DAY STARTS '2017-09-18 00:30:00' ON COMPLETION NOT PRESERVE ENABLE COMMENT 'Realiza el cierre de todos los almacenes del dia actual' DO CALL ticketClosureMultiWarehouse(DATE_ADD(CURDATE(), INTERVAL -1 DAY)) */ ;;
/*!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 'vn'
--
/*!50003 DROP FUNCTION IF EXISTS `addressTaxArea` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `addressTaxArea`(vAddresId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8
    DETERMINISTIC
BEGIN
/**
 * Devuelve el area de un Consignatario, 
 * intracomunitario, extracomunitario, nacional o recargo de equivalencia.
 * Asumimos que no tenemos ninguna empresa 
 *
 * @param vAddresId Id del Consignatario
 * @param vCompanyId Compañia desde la que se factura
 * @return Código de area
 */
	DECLARE vTaxArea VARCHAR(25);
    DECLARE vClientIsUeeMember INT;
    DECLARE vSupplierIsUeeMember INT;
    DECLARE vSpainCountryCode INT DEFAULT 1;
    DECLARE vSupplierCountry INT;
	DECLARE vClientCountry INT;
    DECLARE vIsEqualizated BOOLEAN;
    DECLARE vIsVies BOOLEAN;
    
	SELECT cClient.isUeeMember, c.countryFk, a.isEqualizated, cSupplier.isUeeMember, s.countryFk, c.isVies
			INTO vClientIsUeeMember, vClientCountry, vIsEqualizated, vSupplierIsUeeMember, vSupplierCountry, vIsVies
		FROM address a
			JOIN `client` c ON c.id = a.clientFk
			JOIN country cClient ON cClient.id = c.countryFk
			JOIN supplier s ON s.id = vCompanyId
            JOIN country cSupplier ON cSupplier.id = s.countryFk
		WHERE a.id = vAddresId;
    
	CASE 
		WHEN NOT vClientIsUeeMember THEN 
			SET vTaxArea = 'WORLD';
		WHEN vClientIsUeeMember AND vSupplierIsUeeMember AND vClientCountry != vSupplierCountry AND vIsVies THEN 
			SET vTaxArea = 'CEE';
		WHEN vIsEqualizated AND vClientCountry = vSpainCountryCode THEN 
			SET vTaxArea = 'EQU';    
		ELSE
			SET vTaxArea = 'NATIONAL';
	END CASE;

	RETURN vTaxArea;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `agencyIsAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `agencyIsAvailable`(vAgency INT, vDate DATE, vAddress INT) RETURNS tinyint(1)
BEGIN
/**
 * Comprueba si la agencia esta disponible para la fecha y
 * dirección dadas, es decir, si es posible enviar mercancía
 * desde al menos uno de los almacenes por la agencia, fecha
 * y direcciones especificadas.
 * 
 * @param vAgency Id de agencia
 * @param vDate Fecha de recepción de mercancía
 * @param vAddress Id consignatario, %NULL para recogida
 * @return %TRUE si la agencia esta disponible, %FALSE en caso contrario
 */
	DECLARE vMaxDays INT DEFAULT DATEDIFF(vDate, CURDATE());
	DECLARE vWday TINYINT DEFAULT WEEKDAY(vDate);
	DECLARE vHour TINYINT DEFAULT HOUR(NOW());
	DECLARE vProvince INT;
	DECLARE isAvailable BOOL;

	SELECT provinceFk INTO vProvince
		FROM address
		WHERE id = vAddress;

	SELECT COUNT(*) > 0 INTO isAvailable
		FROM agencyHour h
			JOIN agencyMode a
				ON a.agencyFk = h.agencyFk
		WHERE (h.provinceFk = vProvince
				OR h.provinceFk IS NULL)
			AND (h.weekDay = vWday
				OR h.weekDay IS NULL)
			AND (h.substractDay < vMaxDays
				OR (h.substractDay = vMaxDays AND h.maxHour > vHour))
			AND a.id = vAgency;
				
	RETURN isAvailable;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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`(vClient INT, vDate DATE) RETURNS decimal(10,2)
BEGIN
/**
 * Devuelve el saldo de un cliente.
 *
 * @param vClient Identificador del cliente
 * @param vDate Fecha hasta la que tener en cuenta
 * @return Saldo del cliente
 */
	DECLARE vDateEnd DATETIME;
	DECLARE vDateIni DATETIME;
	DECLARE vDebt DECIMAL(10,2);

	SET vDate = IFNULL(vDate, CURDATE());
					
	SET vDateIni = TIMESTAMPADD(MONTH, -2, CURDATE());
	SET vDateEnd = TIMESTAMP(vDate, '23:59:59');
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT id ticketFk
			FROM ticket
			WHERE clientFk = vClient
				AND refFk IS NULL
				AND shipped BETWEEN vDateIni AND vDateEnd;

	CALL vn.ticketGetTotal;

	SELECT IFNULL(SUM(t.amount), 0) INTO vDebt
		FROM (
			SELECT SUM(total) amount
				FROM tmp.ticketTotal
			UNION ALL
			SELECT SUM(Entregado)
				FROM vn2008.Recibos
				WHERE Id_Cliente = vClient
					AND Fechacobro > vDateEnd
			UNION ALL
			SELECT SUM(amount)
				FROM bi.customer_risk r
				WHERE customer_id = vClient
			UNION ALL
			SELECT CAST(-SUM(amount) / 100 AS DECIMAL(10,2))
				FROM hedera.tpvTransaction
				WHERE clientFk = vClient
					AND receiptFk IS NULL
					AND `status` = 'ok'
		) t;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal;

	RETURN vDebt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `clientGetMana` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`%` FUNCTION `clientGetMana`(vClient INT) RETURNS decimal(10,2)
BEGIN
/**
 * Devuelve el maná del cliente.
 *
 * @param vClient Id del cliente
 * @return Maná del cliente
 */

DECLARE vMana DECIMAL(10,2);
DECLARE vFromDated DATE;

SELECT max(dated) INTO vFromDated
FROM vn.clientManaCache
WHERE clientFk = vClient;

SELECT sum(mana) INTO vMana
    FROM 
		(
		SELECT mana
			FROM vn.clientManaCache
			WHERE clientFk = vClient
            AND dated = vFromDated
            
		UNION ALL
        
        SELECT s.quantity * Valor
             FROM vn.ticket t
				JOIN vn.address a ON a.id = t.addressFk
                JOIN vn.sale s on s.ticketFk = t.id
                JOIN vn2008.Movimientos_componentes mc on mc.Id_Movimiento = s.id
					WHERE Id_Componente IN (37, 39)
						AND t.shipped > vFromDated 
                        AND t.clientFk = vClient

		UNION ALL

		SELECT - Entregado
			FROM vn2008.Recibos r
				JOIN vn2008.Clientes c using(Id_Cliente)
			WHERE r.Id_Banco = 66
				AND r.Fechacobro > vFromDated
				AND c.Id_Cliente = vClient
			
        UNION ALL
        
        SELECT  g.Importe
			FROM vn2008.Greuges g
				JOIN vn2008.Clientes c using(Id_Cliente)
			WHERE g.Greuges_type_id = 3 -- Maná
				AND g.Fecha > vFromDated
				AND c.Id_Cliente = vClient
	
		) sub;

RETURN IFNULL(vMana,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 FUNCTION IF EXISTS `clientTaxArea` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `clientTaxArea`(vClientId INT, vCompanyId INT) RETURNS varchar(25) CHARSET utf8
BEGIN
/**
 * Devuelve el area de un cliente, 
 * intracomunitario, extracomunitario y nacional.
 *
 * @param vClient Id del cliente
 * @param vCompanyFk Compañia desde la que se factura
 * @return Código de area
 */
 DECLARE vTaxArea VARCHAR(25);
    DECLARE vCee INT;
    
 SELECT ct.Cee INTO vCee
  FROM `client` c
   JOIN country ct ON ct.id = c.countryFk
   JOIN supplier s ON s.id = vCompanyId
  WHERE 
   c.id = vClientId
   AND c.isVies
   AND c.countryFk != s.countryFk;
    
 IF vCee < 2 THEN
  SET vTaxArea = 'CEE';
    ELSEIF vCee = 2 THEN
  SET vTaxArea = 'WORLD';
 ELSE
  SET vTaxArea = 'NATIONAL';
    END IF;
    
    RETURN vTaxArea;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getAlert3State` */;
ALTER DATABASE `vn` 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`@`%` FUNCTION `getAlert3State`(vTicket INT) RETURNS varchar(45) CHARSET latin1
BEGIN
	DECLARE vDeliveryType INTEGER DEFAULT 0;
	DECLARE vWorker INT;
    DECLARE isWaitingForPickUp BOOLEAN DEFAULT FALSE;
    DECLARE vCode VARCHAR(45);
    
	SELECT IFNULL(aw.Vista,a.Vista) INTO vDeliveryType 
		FROM vn2008.Tickets t 
			JOIN vn2008.Agencias a ON a.Id_Agencia = t.Id_Agencia
            LEFT JOIN vn2008.agency_warehouse aw ON a.agency_id = aw.agency_id AND t.warehouse_id = aw.warehouse_id 
		WHERE Id_Ticket = vTicket;
        
	SELECT getUser() INTO vWorker;
    
    CASE vDeliveryType
		WHEN 1 THEN -- AGENCIAS
			SELECT COUNT(*) INTO isWaitingForPickUp
				FROM vn2008.Tickets t 
					JOIN vn2008.warehouse_pickup w ON w.agency_id = t.Id_Agencia 
				WHERE t.Id_Ticket = vTicket AND w.warehouse_id <> t.warehouse_id;
                
			IF isWaitingForPickUp THEN
				SET vCode = 'WAITING_FOR_PICKUP';
            ELSE
				SET vCode = 'DELIVERED';
			END IF;
            
        WHEN 2 THEN -- REPARTO
			SET vCode = 'ON_DELIVERY';
            
        ELSE -- MERCADO, OTROS
			SET vCode = 'DELIVERED';
    END CASE;
    RETURN vCode;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getDueDate` */;
ALTER DATABASE `vn` 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 `getDueDate`(vDated DATE, vDayToPay INT) RETURNS date
BEGIN

DECLARE vDued DATE;

SET vDued = IF (vDayToPay > 30 or vDayToPay < 1
                 ,TIMESTAMPADD(DAY, vDayToPay, vDated) 
                 ,TIMESTAMPADD(DAY, vDayToPay, LAST_DAY(vDated)));

RETURN vDued;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getInventoryDate` */;
ALTER DATABASE `vn` 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 `getInventoryDate`() RETURNS date
    DETERMINISTIC
BEGIN
	RETURN vn2008.date_inv();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getShipmentHour` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getShipmentHour`(vTicket INT) RETURNS int(11)
BEGIN
	DECLARE vShipmentHour INT;
    
    SELECT HOUR(shipped) INTO vShipmentHour
		FROM ticket
		WHERE id = vTicket;
    
    IF vShipmentHour = 0
    THEN
 		DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
		CREATE TEMPORARY TABLE tmp.production_buffer
			ENGINE = MEMORY
			SELECT am.agency as agency_id
				, t.warehouseFk as warehouse_id
				, a.province as province_id
				, 0 as Hora
                , 0 as Departure
				FROM ticket t
				JOIN agencyMode am on am.id = t.agencyModeFk
				JOIN address a on a.id = t.addressFk
				WHERE t.id = vTicket;
                 
		CALL vn2008.production_buffer_set_priority;
    
		SELECT Hora INTO vShipmentHour 
			FROM tmp.production_buffer;
    END IF;
        
	RETURN vShipmentHour;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getSpecialPrice` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getSpecialPrice`(vItemFk int(11),vClientFk int(11)) RETURNS decimal(10,2)
BEGIN
    DECLARE price DECIMAL(10,2);

    SELECT rate3 INTO price
		FROM vn.priceFixed
		WHERE itemFk = vItemFk 
			AND CURDATE() BETWEEN started AND ended ORDER BY created DESC LIMIT 1;
    
    SELECT `value` INTO price 
		FROM vn.especialPrice
		WHERE itemFk =  vItemFk 
			AND clientFk = vClientFk ;
RETURN price;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `getTicketToPrepare` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getTicketToPrepare`(`vWorker` INT, `vWarehouse` INT) RETURNS int(11)
BEGIN
/**
 * Devuelve el ticket que debe de preparar el trabajador
 *
 * @param vWorker Id del trabajador 
 * @param vWarehouse Id del almacén
 * @return Id del ticket
 **/
 
	DECLARE vToday DATETIME DEFAULT CURDATE();
	DECLARE vYesterday DATETIME;
	DECLARE vTodayvMidniight DATETIME DEFAULT midnight(vToday);
	DECLARE vTicket INT DEFAULT NULL;

	SET vYesterday = TIMESTAMPADD(DAY,-1,vToday);
    
    DROP TEMPORARY TABLE IF EXISTS tmp.workerComercial;
	CREATE TEMPORARY TABLE tmp.workerComercial
		ENGINE = MEMORY
		SELECT worker FROM `grant` g 
				JOIN grantGroup gg ON g.`group` = gg.id 
			WHERE gg.description  = 'Comerciales'
            AND worker != 2; -- PAKO numero
     
        
	DROP TEMPORARY TABLE IF EXISTS tmp.production_buffer;
	CREATE TEMPORARY TABLE tmp.production_buffer
		ENGINE = MEMORY
		SELECT t.id as ticket
			, am.agency as agency_id
			, t.warehouseFk as warehouse_id
			, a.province as province_id
			, Hour(t.shipped) as Hora
            , Hour(t.shipped) as Departure
            , Minute(t.shipped) as Minuto
			, tls.code
			, IFNULL(t.priority,0) loadingOrder
			FROM ticket t
			JOIN ticketState tls on t.id = tls.ticket
			JOIN agencyMode am on am.id = t.agencyModeFk
			JOIN address a on a.id = t.addressFk
			LEFT JOIN tmp.workerComercial wc ON wc.worker = vWorker
			 WHERE t.shipped BETWEEN vYesterday AND vTodayvMidniight
			 AND t.warehouseFk = vWarehouse
				 AND 
				(
					(tls.code = 'PRINTED' AND wc.worker IS NULL)
				OR 
					(tls.code ='PICKER_DESIGNED' AND tls.worker = vWorker)
				OR 
					(tls.code = 'PRINTED_BACK')
				);
                
			 
	CALL vn2008.production_buffer_set_priority;
	 
	SELECT ticket INTO vTicket
		FROM tmp.production_buffer
		ORDER BY (code = 'PICKER_DESIGNED') DESC , Hora, Minuto, loadingOrder
		LIMIT 1;

	RETURN vTicket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `getTicketTrolleyLabelCount` */;
ALTER DATABASE `vn` 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`@`%` FUNCTION `getTicketTrolleyLabelCount`(vTicket INT) RETURNS int(11)
BEGIN

DECLARE vLabelCount INT DEFAULT 0;

SELECT labelCount INTO vLabelCount 
FROM ticketTrolley
WHERE ticket = vTicket;

SET vLabelCount = vLabelCount +1 ;

REPLACE ticketTrolley(ticket,labelCount)
SELECT vTicket, vLabelCount;

RETURN vlabelCount;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getUser` */;
ALTER DATABASE `vn` 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`@`%` FUNCTION `getUser`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	RETURN getWorker();
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getUserId` */;
ALTER DATABASE `vn` 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 `getUserId`(userName varchar(30)) RETURNS int(11)
BEGIN
	DECLARE vUser INT;
    
    SELECT id INTO vUser
		FROM account.user
		WHERE `name` = userName;
    
	RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `getWorker` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getWorker`() RETURNS int(11)
    DETERMINISTIC
BEGIN
    DECLARE vUser INT;
    
    SELECT id INTO vUser
        FROM worker
        WHERE userFk = account.userGetId();
    
    RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `getWorkerkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getWorkerkk`() RETURNS int(11)
    DETERMINISTIC
BEGIN
	DECLARE vUser INT;
    
    SELECT id INTO vUser
		FROM worker
		WHERE user = account.userGetId();
    
	RETURN vUser;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `hasAnyNegativeBase` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `hasAnyNegativeBase`() RETURNS tinyint(1)
BEGIN

/*	Calcula si existe alguna base imponible negativa
*	Requiere la tabla temporal vn.ticketToInvoice(id)
*
*	returns BOOLEAN
*/

    DECLARE vCountry INT;
	DECLARE hasAnyNegativeBase BOOLEAN;

    SELECT s.countryFk 
            INTO vCountry
        FROM supplier s
            JOIN ticket t ON t.companyFk = s.id
            JOIN vn.ticketToInvoice tl ON tl.id = t.id
		LIMIT 1;

    SELECT COUNT(*) INTO hasAnyNegativeBase
        FROM (
                SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase
                    FROM sale s 
                        JOIN item i ON i.id = s.itemFk
                        JOIN itemTaxCountry itc 
                            ON itc.itemFk = i.id AND itc.countryFk = vCountry
                        JOIN vn.ticketToInvoice tl ON tl.id = s.ticketFk
                    GROUP BY itc.taxClassFk
                    HAVING taxableBase < 0
            ) t1 ;

	RETURN hasAnyNegativeBase;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `hasSomeNegativeBase` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `hasSomeNegativeBase`(vTicket INT) RETURNS tinyint(1)
BEGIN

    DECLARE vCountry INT;
	DECLARE hasSomeNegativeBase BOOLEAN;

    SELECT s.countryFk 
            INTO vCountry
        FROM supplier s
            JOIN ticket t ON t.companyFk = s.id
        WHERE t.id = vTicket;

    SELECT COUNT(*) INTO hasSomeNegativeBase
        FROM (
                SELECT SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)) taxableBase
                    FROM sale s 
                        JOIN item i ON i.id = s.itemFk
                        JOIN itemTaxCountry itc 
                            ON itc.itemFk = i.id AND itc.countryFk = vCountry
                        WHERE s.ticketFk = vTicket
                    GROUP BY itc.taxClassFk
                    HAVING taxableBase < 0
            ) t1 ;

	RETURN hasSomeNegativeBase;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `invoiceOutAmount` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutAmount`(vInvoiceRef VARCHAR(15)) RETURNS decimal(10,2)
BEGIN
	DECLARE totalAmount DECIMAL(10,2);

	SELECT SUM(vat) INTO totalAmount
		FROM
		(	
		SELECT iot.vat
			FROM invoiceOutTax iot
				JOIN invoiceOut io ON io.id = iot.invoiceOutFk
			WHERE io.ref = vInvoiceRef
		UNION ALL 
		SELECT ioe.amount
			FROM invoiceOutExpence ioe
				JOIN invoiceOut io ON io.id = ioe.invoiceOutFk
			WHERE io.ref = vInvoiceRef
		) t1;
    
RETURN totalAmount;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `invoiceSerial` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceSerial`(vClientFk INT, vCompanyFk INT, vType CHAR(1)) RETURNS char(1) CHARSET utf8
BEGIN
	/**
	* Obtiene la serie de de una factura 
	* dependiendo del area del cliente.
	* 
	* @param vClientFk Id del cliente
	* @param vCompanyFk Id de la empresa
	* @param vType Tipo de factura ["R", "M", "G"]
	* @return Serie de la factura
	*/
	DECLARE vArea VARCHAR(25);
	DECLARE vSerie CHAR(1);

	IF (SELECT hasInvoiceSimplified FROM client WHERE id = vClientFk) THEN
		RETURN 'S';
	END IF;

	SELECT clientTaxArea(vClientFk, vCompanyFk) INTO vArea;
	-- Factura rápida
	IF vType = 'R' THEN
		SELECT 
			CASE vArea 
				WHEN 'CEE'
			THEN 'H'
				WHEN 'WORLD'
			THEN 'E'
				WHEN 'NATIONAL' 
			THEN 'T'
		END
		INTO vSerie;
		-- Factura multiple
	ELSEIF vType = 'M' THEN
		SELECT 
			CASE vArea 
				WHEN 'CEE'
			THEN 'H'
				WHEN 'WORLD'
			THEN 'E'
				WHEN 'NATIONAL' 
			THEN 'M'
		END
		INTO vSerie;
	-- Factura global
	ELSEIF vType = 'G' THEN
		SELECT 
			CASE vArea 
				WHEN 'CEE'
			THEN 'V'
				WHEN 'WORLD'
			THEN 'X'
				WHEN 'NATIONAL' 
			THEN 'A'
		END
		INTO vSerie;
	END IF;
	RETURN vSerie;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `isPalletHomogeneus` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `isPalletHomogeneus`(vExpedition INT) RETURNS tinyint(1)
BEGIN
	DECLARE vScanId INT;
	DECLARE vDistinctRoutesInThePallet INT;

	SELECT scan_id INTO vScanId
		FROM vn2008.scan_line
		WHERE code = vExpedition;

	 SELECT COUNT(*) INTO vDistinctRoutesInThePallet
		FROM (
			SELECT DISTINCT t.Id_Ruta
			FROM vn2008.scan_line sl
				JOIN vn2008.expeditions e ON e.expeditions_id = sl.code
				JOIN vn2008.Tickets t ON t.Id_Ticket = e.ticket_id
			WHERE sl.scan_id = vScanId
				AND t.Id_Ruta
		) t1;
			
	RETURN vDistinctRoutesInThePallet = 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 FUNCTION IF EXISTS `isWorkerBoss` */;
ALTER DATABASE `vn` 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 `isWorkerBoss`(vUserId INT(11)) RETURNS tinyint(1)
    DETERMINISTIC
BEGIN

    DECLARE subjectId INT(11) DEFAULT vUserId;
    DECLARE tmpSubjectId INT(11);
	DECLARE tmpBossId INT(11);
    
    LOOP
		SELECT 
			bossWorker.user_id AS tmpBossId,
            subjectWorker.user_id AS tmpSubjectId
		INTO tmpBossId, tmpSubjectId
		FROM
			vn2008.Trabajadores AS subjectWorker
				JOIN
			vn2008.Trabajadores AS bossWorker ON bossWorker.Id_Trabajador = subjectWorker.boss
		WHERE
			subjectWorker.user_id = subjectId;
        
		IF tmpBossId = tmpSubjectId THEN
			RETURN FALSE;
        ELSEIF tmpBossId = account.userGetId() THEN
			RETURN TRUE;
		ELSE
			SET subjectId = tmpBossId;
		END IF; 
    END LOOP;
    
RETURN FALSE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `messageSend` */;
ALTER DATABASE `vn` 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 `messageSend`(vRecipient VARCHAR(255), vMessage TEXT) RETURNS int(11)
BEGIN
/**
 * Envia un mensaje a un usuario o a una lista de usuarios.
 *
 * @param vRecipient Nombre de usuario o de alias
 * @param vMessage Texto del mensaje
 * @return Número de destinatarios
 **/
	DECLARE vCount INT;
	DECLARE vUuid VARCHAR(255);
	DECLARE vSendDate DATETIME DEFAULT NOW();
	DECLARE vUser VARCHAR(255) DEFAULT account.userGetName();

	SET vRecipient = LOWER(vRecipient);

	DROP TEMPORARY TABLE IF EXISTS tRecipients;
	CREATE TEMPORARY TABLE tRecipients
		SELECT u.name finalRecipient
			FROM account.mailAlias a
				JOIN account.mailAliasAccount aa ON aa.mailAlias = a.id
				JOIN account.user u ON u.id = aa.account
			WHERE a.alias = vRecipient COLLATE utf8_unicode_ci
				AND u.name != vUser
				AND u.active
		UNION
		SELECT u.name FROM account.user u
			WHERE u.name = vRecipient
				AND u.active;

	SELECT COUNT(*) INTO vCount FROM tRecipients;

	IF vCount = 0 THEN
		RETURN vCount;
	END IF;    

	SET vUuid = UUID();

	INSERT INTO message
		SET uuid = vUuid,
			sender = vUser,
			recipient = vRecipient,
			message = vMessage,
			sendDate = vSendDate;

	INSERT INTO messageInbox (uuid, sender, recipient, finalRecipient, message, sendDate) 
		SELECT vUuid, vUser, vRecipient, finalRecipient, vMessage, vSendDate
			FROM tRecipients;

	DROP TEMPORARY TABLE tRecipients;
	RETURN vCount;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `midnight` */;
ALTER DATABASE `vn` 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`@`%` FUNCTION `midnight`(vDate DATE) RETURNS datetime
    DETERMINISTIC
BEGIN
	RETURN TIMESTAMP(vDate,'23:59:59');
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `noticeHasActive` */;
ALTER DATABASE `vn` 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 `noticeHasActive`(vCategoryKey VARCHAR(50), vUser INT) RETURNS tinyint(1)
BEGIN
/**
 * Comprueba si el usuario tiene activada o no la categoría
 * 
 * @param vNoticeCategory Id de la categoría
 * @param vUser Id del usuario
 * @return %True si el usuario tiene activada la notificación, %False en caso contrario
 */
	DECLARE vActive INT;
    
    SELECT COUNT(*) INTO vActive
		FROM noticeSubscription s
        JOIN noticeCategory c ON c.id = s.noticeCategoryFk
        WHERE c.keyName = vCategoryKey AND userFk = vUser;
        
	RETURN vActive;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP FUNCTION IF EXISTS `phytoPassport` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `phytoPassport`(vRef VARCHAR(15)) RETURNS text CHARSET utf8
BEGIN
DECLARE vPhyto TEXT CHARSET utf8 COLLATE utf8_unicode_ci;
SELECT 
		GROUP_CONCAT(i.id,
			':',
			ppa.denomination,
			' ',
			pp.number,
            CHAR(13,10)
			SEPARATOR '') fitosanitario
	INTO vPhyto
FROM
    sale s
        JOIN
	ticket t ON t.id = s.ticketFk
		JOIN
    item i ON i.id = s.itemFk
        JOIN
    plantpassport pp ON pp.producerFk = i.producerFk
        JOIN
    plantpassportAuthority ppa ON ppa.id = pp.plantpassportAuthorityFk
        JOIN
    itemBotanicalWithGenus ib ON ib.itemFk = i.id
        JOIN
    botanicExport be ON be.restriction = 'Se Requiere Certificado'
        LEFT JOIN
    ediGenus eg ON eg.id = be.ediGenusFk
        LEFT JOIN
    ediSpecie es ON es.id = be.ediSpecieFk
WHERE
    t.refFk = vRef
        AND ib.ediBotanic LIKE CONCAT(IFNULL(eg.latinGenusName, ''),
            IF(latinSpeciesName > '',
                CONCAT(' ', latinSpeciesName),
                ''),
            '%');
RETURN vPhyto;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `ticketGetTotal` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketGetTotal`(vTicketId INT) RETURNS decimal(10,2)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * Calcula el total con IVA de un ticket.
 *
 * @param vTicketId Identificador del ticket
 * @return Total del ticket
 */
	DECLARE vTotal DECIMAL(10,2);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		ENGINE = MEMORY
		SELECT vTicketId ticketFk;

	CALL ticketGetTotal;

	SELECT total INTO vTotal FROM tmp.ticketTotal;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal;
	
	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 `ticketGetTotalkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketGetTotalkk`(vTicketId INT) RETURNS decimal(10,2)
    READS SQL DATA
    DETERMINISTIC
BEGIN
/**
 * Calcula el total con IVA de un ticket.
 *
 * @param vTicketId Identificador del ticket
 * @return Total del ticket
 */
	DECLARE vTotal DECIMAL(10,2);

	DROP TEMPORARY TABLE IF EXISTS tmp.ticket;
	CREATE TEMPORARY TABLE tmp.ticket
		ENGINE = MEMORY
		SELECT vTicketId ticketFk;

	CALL ticketGetTotal;

	SELECT total INTO vTotal FROM tmp.ticketTotal;

	DROP TEMPORARY TABLE
		tmp.ticket,
		tmp.ticketTotal;
	
	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 `ticketPositionInPath` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketPositionInPath`(vTicketId INT) RETURNS varchar(10) CHARSET utf8
BEGIN

 DECLARE vRestTicketsMaxOrder INT;
 DECLARE vRestTicketsMinOrder INT;
 DECLARE vRestTicketsPacking INT;
 DECLARE vMyProductionOrder INT;
 DECLARE vPosition VARCHAR(10) DEFAULT 'MID';
 DECLARE vMyPath INT;
 DECLARE vMyWarehouse INT;
 DECLARE PACKING_ORDER INT;
 DECLARE vExpeditionsCount INT;
 DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;

SELECT `order` 
 INTO PACKING_ORDER
  FROM state
  WHERE code = 'PACKING';

SELECT t.routeFk, t.warehouseFk, IFNULL(ts.productionOrder,0)
 INTO vMyPath, vMyWarehouse, vMyProductionOrder
  FROM ticket t
   LEFT JOIN ticketState ts on ts.ticket = t.id
  WHERE t.id = vTicketId;

SELECT (ag.`name` = 'VN_VALENCIA') 
 INTO vIsValenciaPath
  FROM vn2008.Rutas r
   JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
   JOIN vn2008.agency ag on ag.agency_id = a.agency_id
  WHERE r.Id_Ruta = vMyPath;

IF vIsValenciaPath THEN -- Rutas Valencia

 SELECT COUNT(*)
  INTO vExpeditionsCount
   FROM expedition e
    JOIN ticket t ON t.id = e.ticket
   WHERE t.routeFk = vMyPath;
   
 SELECT MAX(ts.productionOrder), MIN(ts.productionOrder)
  INTO vRestTicketsMaxOrder, vRestTicketsMinOrder
   FROM ticket t
    LEFT JOIN ticketState ts on t.id = ts.ticket
   WHERE t.routeFk = vMyPath
    AND t.warehouseFk = vMyWarehouse
    AND t.id != vTicketid;

 SELECT COUNT(*) 
  INTO vRestTicketsPacking
   FROM ticket t
    LEFT JOIN ticketState ts on t.id = ts.ticket
   WHERE ts.productionOrder = PACKING_ORDER
    AND t.routeFk = vMyPath
    AND t.warehouseFk = vMyWarehouse
    AND t.id != vTicketid;

  IF  vExpeditionsCount = 1 THEN
    SET vPosition = 'FIRST';
   ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN
    SET vPosition = 'LAST';
   ELSEIF vRestTicketsPacking THEN
    SET vPosition = 'SHARED';
   ELSE
    SET vPosition = 'MID';
  END IF;

ELSE
 SET vPosition = 'MID';

END IF;

RETURN vPosition;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 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 `ticketPositionInPathkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketPositionInPathkk`(vTicketId INT) RETURNS varchar(10) CHARSET utf8
BEGIN


DECLARE vRestTicketsMaxOrder INT;
DECLARE vRestTicketsMinOrder INT;
DECLARE vRestTicketsPacking INT;
DECLARE vMyProductionOrder INT;
DECLARE vPosition VARCHAR(10) DEFAULT 'MID';
DECLARE vMyPath INT;
DECLARE vMyWarehouse INT;
DECLARE PACKING_ORDER INT;
DECLARE vExpeditionsCount INT;
DECLARE vIsValenciaPath BOOLEAN DEFAULT FALSE;

SELECT `order` 
	INTO PACKING_ORDER
	FROM state
	WHERE code = 'PACKING';

SELECT path, warehouse, IFNULL(productionOrder,0)
	INTO vMyPath, vMyWarehouse, vMyProductionOrder
	FROM ticket t
    LEFT JOIN ticketState ts on ts.ticket = t.id
	WHERE id = vTicketId;

SELECT (ag.`name` = 'VN_VALENCIA') 
	INTO vIsValenciaPath
	FROM vn2008.Rutas r
	JOIN vn2008.Agencias a on a.Id_Agencia = r.Id_Agencia
	JOIN vn2008.agency ag on ag.agency_id = a.agency_id
	WHERE r.Id_Ruta = vMyPath;


IF vIsValenciaPath THEN -- Rutas Valencia

	SELECT COUNT(*)
			INTO vExpeditionsCount
			FROM expedition e
			JOIN ticket t ON t.id = e.ticket
			WHERE t.path = vMyPath;
			
		SELECT MAX(productionOrder), MIN(productionOrder)
			INTO vRestTicketsMaxOrder, vRestTicketsMinOrder
			FROM ticket t
			LEFT JOIN ticketState ts on t.id = ts.ticket
			WHERE t.path = vMyPath
			AND t.warehouse = vMyWarehouse
			AND t.id != vTicketid;

		SELECT COUNT(*) 
			INTO vRestTicketsPacking
			FROM ticket t
			LEFT JOIN ticketState ts on t.id = ts.ticket
			WHERE productionOrder = PACKING_ORDER
			AND t.path = vMyPath
			AND t.warehouse = vMyWarehouse
			AND t.id != vTicketid;

		
	
		IF  vExpeditionsCount = 1 THEN

				SET vPosition = 'FIRST';

			ELSEIF vRestTicketsMinOrder > PACKING_ORDER THEN

				SET vPosition = 'LAST';
			
			ELSEIF vRestTicketsPacking THEN

				SET vPosition = 'SHARED';
			
			ELSE

				SET vPosition = 'MID';
			
		END IF;

ELSE

		SET vPosition = 'MID';

END IF;

RETURN vPosition;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP FUNCTION IF EXISTS `workerIsBoss` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `workerIsBoss`(vUserId INT) RETURNS int(11)
BEGIN
/**
 * Comprueba por jerarquía si el trabajador actual es jefe
 * de un trabajador en concreto.
 *
 * @param vUserId Id del trabajador que se desea comprobar.
 * @return Revuelve verdadero si es jefe del empleado por escala jerárquica.
 */
    DECLARE vWorkerId INT;
    DECLARE vBossId INT;

    SELECT id INTO vWorkerId
        FROM vn.worker
        WHERE userFk = vUserId;
    IF vWorkerId IS NULL THEN
        CALL util.throw('USER_NOT_FOUND');
    END IF;

    DROP TEMPORARY TABLE IF EXISTS tCheckedWorker;
    CREATE TEMPORARY TABLE tCheckedWorker
        (PRIMARY KEY (workerFk))
        ENGINE = MEMORY
        SELECT id workerFk FROM worker LIMIT 0;
    LOOP
        SELECT bossFk INTO vBossId
            FROM vn.worker
            WHERE id = vWorkerId;
        IF (SELECT COUNT(*) FROM tCheckedWorker WHERE workerFk = vBossId) THEN
            CALL util.throw('INFINITE_LOOP');
        END IF;
        IF vBossId = vWorkerId THEN
            RETURN FALSE;
        ELSEIF vBossId = vn.getWorker() THEN
            RETURN TRUE;
        ELSE
            INSERT INTO tCheckedWorker VALUES (vWorkerId);
            SET vWorkerId = vBossId;
        END IF;
    END LOOP;
    DROP TEMPORARY TABLE tCheckedWorker;
    RETURN FALSE;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `agencyListAvailable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `agencyListAvailable`(vDate DATE, vAddress INT)
BEGIN
/**
 * Devuelve la lista de almacenes disponibles y la fecha de
 * envío desde cada uno.
 *
 * @param vDate Fecha de recepción de mercancía
 * @param vAddress Id consignatario, %NULL para recogida
 * @return travel_tree Lista de almacenes disponibles
 */
	DECLARE vMaxDays INT DEFAULT DATEDIFF(vDate, CURDATE());
	DECLARE vWday TINYINT DEFAULT WEEKDAY(vDate);
	DECLARE vHour TINYINT DEFAULT HOUR(NOW());
	DECLARE vProvince INT;

	SELECT provinceFk INTO vProvince
		FROM address
		WHERE id = vAddress;

	DROP TEMPORARY TABLE IF EXISTS tmp.agencyAvailable;
	CREATE TEMPORARY TABLE tmp.agencyAvailable
		(INDEX (agencyFk))
		ENGINE = MEMORY
		SELECT agencyFk, warehouseFk
			FROM agencyHour h
			WHERE (provinceFk = vProvince
					OR provinceFk IS NULL)
				AND (weekDay = vWday
					OR weekDay IS NULL)
				AND (substractDay < vMaxDays
					OR (substractDay = vMaxDays AND maxHour > vHour));
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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;

    SET vDateShort = TIMESTAMPADD(MONTH, -2, CURDATE());
    
    DELETE FROM vn.dailyTaskLog WHERE created < vDateShort;
    
	INSERT INTO vn.dailyTaskLog(state) VALUES('clean START');

	DELETE FROM vn.message WHERE sendDate < vDateShort;
    DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
    DELETE FROM vn.messageInbox WHERE sendDate < vDateShort;
    
	INSERT INTO vn.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 `clientFreeze` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `clientFreeze`()
BEGIN

	IF day(CURDATE()) IN (10,20,30) THEN
		
		UPDATE vn.client c
			JOIN bi.defaulters d ON d.client = c.id AND d.date = CURDATE()
			JOIN vn.config ON TRUE
			SET c.isFreezed = TRUE
		WHERE d.amount > config.defaultersMaxAmount;
		
    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 `copyComponentsFromSaleList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `copyComponentsFromSaleList`(vTargetTicketFk INT)
BEGIN

/*   Copy sales and components to the target ticket
*
*	¡¡¡¡    Requires tmp.saleList(saleFk, itemFk, quantity, concept, price, discount, orden)  !!!!!
*
*   param VTargetTicketFk id del ticket a rellenar
*/

	INSERT INTO vn.sale(ticketFk, itemFk, quantity,concept,price,discount)
		SELECT vTargetTicketFk, itemFk, quantity,concept,price,discount
			FROM tmp.saleList
			ORDER BY orden;

	SET @order = 0;

	DROP TEMPORARY TABLE IF EXISTS tmp.newSaleList;

	CREATE TEMPORARY TABLE tmp.newSaleList
		SELECT id as saleFk, @order := @order + 1 as orden
			FROM vn.sale
			WHERE ticketFk = vTargetTicketFk
			ORDER BY saleFk;

	INSERT INTO vn.saleComponent(saleFk,componentFk,value)
		SELECT ns.saleFk, sc.componentFk, sc.value
			FROM vn.saleComponent sc
				JOIN tmp.saleList s ON s.saleFk = sc.saleFk
				JOIN tmp.newSaleList ns ON ns.orden = s.orden;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `createExternalWorkerkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `createExternalWorkerkk`(
    vFirstName VARCHAR(50),
    vSurname1 VARCHAR(50),
    vSurname2 VARCHAR(50),
    vUser VARCHAR(20),
    vPassword VARCHAR(50),
    vWorkerCode VARCHAR(3)
    )
BEGIN

	DECLARE vUserId INT;
    DECLARE vWorkerPako INT DEFAULT 2;
    DECLARE vSurnames VARCHAR(100);

	INSERT INTO account.user(name,password,role)
		SELECT vUser,MD5(vPassword),1;
            
	SET vUserId = LAST_INSERT_ID();
    /* 
		INSERT INTO vn.worker(firstName,name,bossFk,workerCode,user_id)
			SELECT vFirstName,CONCAT(vSurname1,' ',vSurname2),2,vWorkerCode,vUser;
	*/
    
    IF vSurname2 IS NULL THEN
		SET vSurnames = vSurname1;
    ELSE
		SET vSurnames = CONCAT(vSurname1, ' ', vSurname2);
    END IF;
	
	INSERT INTO vn2008.Trabajadores(Nombre, Apellidos, boss, CodigoTrabajador, user_id)
		SELECT vFirstName, vSurnames, vWorkerPako, vWorkerCode, vUserId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `entryConverter` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `entryConverter`(vEntry INT)
BEGIN

    DECLARE vWarehouseIn INT;
    DECLARE vWarehouseOut INT;
    DECLARE vTravel INT;

    DECLARE done BOOL DEFAULT FALSE;

    DECLARE vId_Entrada INT;
    DECLARE vId_Article INT;
    DECLARE vEtiquetas INT;
    DECLARE vId_Cubo VARCHAR(10);
    DECLARE vPacking INT;
    DECLARE vGrouping INT;
    DECLARE vCantidad INT;    
    DECLARE vCostefijo DECIMAL(10,3);
    DECLARE vPortefijo DECIMAL(10,3);
    DECLARE vEmbalajefijo DECIMAL(10);
    DECLARE vComisionfija DECIMAL(10,3);
    DECLARE vCaja INT;
    DECLARE vNicho VARCHAR(5);
    DECLARE vTarifa1 DECIMAL(10,2);
    DECLARE vTarifa2 DECIMAL(10,2);
    DECLARE vTarifa3 DECIMAL(10,2);
    DECLARE vPVP DECIMAL(10,2);
    DECLARE vCompra INT;

    DECLARE rs CURSOR FOR
		SELECT 
                b.Id_Entrada,
                b.Id_Article,
                b.Etiquetas,
                b.Id_Cubo,
                b.Packing,
                b.grouping,
                b.Cantidad,    
                b.Costefijo,
                b.Portefijo,
                b.Embalajefijo,
                b.Comisionfija,
                b.caja,
                b.Nicho,
                b.Tarifa1,
                b.Tarifa2,
                b.Tarifa3,
                b.PVP 
            FROM vn2008.Compres b 
                JOIN vn.itemConversor ic ON ic.espItemFk = b.Id_Article
            WHERE Id_Entrada = vEntry;

    DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

    SELECT warehouseInFk, warehouseOutFk, tr.id
            INTO vWarehouseIn, vWarehouseOut, vTravel
        FROM travel tr 
            JOIN entry e ON e.travelFk = tr.id
        WHERE e.id = vEntry;

    UPDATE travel 
        SET warehouseInFk = vWarehouseOut,
            warehouseOutFk = vWarehouseIn
        WHERE id = vTravel;
        
	UPDATE vn2008.Compres c 
		LEFT JOIN vn.itemConversor ic ON ic.espItemFk = c.Id_Article
		SET Etiquetas = 0, Cantidad = 0
		WHERE c.Id_Entrada = vEntry
			AND ic.espItemFk IS NULL;

    OPEN rs;
    
    DELETE FROM vn2008.Compres WHERE Id_Entrada = vEntry;

    FETCH rs INTO  
                    vId_Entrada,
                    vId_Article,
                    vEtiquetas,
                    vId_Cubo,
                    vPacking,
                    vGrouping,
                    vCantidad,
                    vCostefijo,
                    vPortefijo,
                    vEmbalajefijo,
                    vComisionfija,
                    vCaja,
                    vNicho,
                    vTarifa1,
                    vTarifa2,
                    vTarifa3,
                    vPVP;

    WHILE NOT done DO

        -- Primero la linea original con las cantidades invertidas
        INSERT INTO vn2008.Compres
                    (
                    Id_Entrada,
                    Id_Article,
                    Etiquetas,
                    Id_Cubo,
                    Packing,
                    grouping,
                    Cantidad,    
                    Costefijo,
                    Portefijo,
                    Embalajefijo,
                    Comisionfija,
                    caja,
                    Nicho,
                    Tarifa1,
                    Tarifa2,
                    Tarifa3,
                    PVP    
                    )
            VALUES
                    (
                    vId_Entrada,
                    vId_Article,
                    - vEtiquetas,
                    vId_Cubo,
                    vPacking,
                    vGrouping,
                    - vCantidad,
                    vCostefijo,
                    vPortefijo,
                    vEmbalajefijo,
                    vComisionfija,
                    vCaja,
                    vNicho,
                    vTarifa1,
                    vTarifa2,
                    vTarifa3,
                    vPVP);

            -- Ahora la linea nueva, con el item genérico
            INSERT INTO vn2008.Compres
                    (
                    Id_Entrada,
                    Id_Article,
                    Etiquetas,
                    Id_Cubo,
                    Packing,
                    grouping,
                    Cantidad,    
                    Costefijo,
                    Portefijo,
                    Embalajefijo,
                    Comisionfija,
                    caja,
                    Nicho,
                    Tarifa1,
                    Tarifa2,
                    Tarifa3,
                    PVP    
                    )
            SELECT 
                    vId_Entrada,
                    genItemFk as Id_Article,
                    vEtiquetas,
                    vId_Cubo,
                    vPacking,
                    vGrouping,
                    vCantidad,
                    vCostefijo,
                    vPortefijo,
                    vEmbalajefijo,
                    vComisionfija,
                    vCaja,
                    vNicho,
                    vTarifa1,
                    vTarifa2,
                    vTarifa3,
                    vPVP
                FROM itemConversor 
                WHERE espItemFk = vId_Article;

            SELECT LAST_INSERT_ID() 
                INTO vCompra;

		    REPLACE vn2008.Compres_mark(Id_Compra,`comment`) 
			    SELECT vCompra, vId_Article;


        FETCH rs INTO  
                        vId_Entrada,
                        vId_Article,
                        vEtiquetas,
                        vId_Cubo,
                        vPacking,
                        vGrouping,
                        vCantidad,
                        vCostefijo,
                        vPortefijo,
                        vEmbalajefijo,
                        vComisionfija,
                        vCaja,
                        vNicho,
                        vTarifa1,
                        vTarifa2,
                        vTarifa3,
                        vPVP;

    END WHILE;


    CLOSE rs;



END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getDebtKk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `getDebtKk`(vDate DATE)
BEGIN
/**
 * Calcula el riesgo para los clientes activos de la tabla temporal tmp.client_list
 *
 * @deprecated usar vn.clientGetDebt
 * @table tmp.client_list
 * @param vDate Fecha maxima de los registros
 * @treturn tmp.risk
 */
	DECLARE vDateIni DATETIME DEFAULT TIMESTAMPADD(DAY, - DAYOFMONTH(CURDATE()) - 5, CURDATE());
	DECLARE vDateEnd DATETIME;
	DECLARE MAX_RISK_ALLOWED INT DEFAULT 200;

	SET vDateEnd = TIMESTAMP(IFNULL(vDate, CURDATE()), '23:59:59');

	DROP TEMPORARY TABLE IF EXISTS tmp.clientList2;
	CREATE TEMPORARY TABLE tmp.clientList2
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT *
			FROM tmp.client_list;

	DROP TEMPORARY TABLE IF EXISTS tmp.clientList3;
	CREATE TEMPORARY TABLE tmp.clientList3
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT *
			FROM tmp.client_list;

	DROP TEMPORARY TABLE IF EXISTS vn2008.ticket_tmp;
	CREATE TEMPORARY TABLE vn2008.ticket_tmp
		(INDEX (ticket_id))
		ENGINE = MEMORY
		SELECT id ticket_id, cl.Id_Cliente
			FROM ticket t
				JOIN  tmp.clientList2 cl ON t.clientFk = cl.Id_Cliente
			WHERE refFk IS NULL
				AND shipped BETWEEN vDateIni AND vDateEnd;
				
	CALL vn2008.ticket_total;     

	DROP TEMPORARY TABLE IF EXISTS tmp.risk;
	CREATE TEMPORARY TABLE tmp.risk
		(PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT Id_Cliente, SUM(amount) risk
			FROM vn2008.Clientes c
			JOIN (
				SELECT customer_id, SUM(amount) amount
					FROM bi.customer_risk cr
						JOIN tmp.client_list on tmp.client_list.Id_Cliente = cr.customer_id
					GROUP BY customer_id
				UNION ALL
				SELECT Id_Cliente, SUM(Entregado)
					FROM vn2008.Recibos
						JOIN tmp.clientList2 using(Id_Cliente)
					WHERE  Fechacobro > vDateIni
					GROUP BY Id_Cliente
				UNION ALL
				SELECT t.Id_Cliente, total
					FROM vn2008.ticket_total tt
						JOIN vn2008.ticket_tmp t ON tt.ticket_id = t.ticket_id
				UNION ALL
				SELECT t.clientFk customer_id, CAST(-SUM(t.amount) / 100 AS DECIMAL(10,2))
					FROM hedera.tpvTransaction t
						JOIN tmp.clientList3 l ON l.Id_Cliente = t.clientFk
					WHERE  t.receiptFk IS NULL
						AND t.status = 'ok'
					GROUP BY t.clientFk
			) t ON c.Id_Cliente = t.customer_id
			WHERE c.activo != FALSE
			GROUP BY c.Id_Cliente;
		 
	DROP TEMPORARY TABLE
		vn2008.ticket_tmp,
		vn2008.ticket_total,
		tmp.clientList2,
		tmp.clientList3;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `getItemVisibleAvailable` */;
ALTER DATABASE `vn` 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 `getItemVisibleAvailable`(IN vItem INT,IN vDate DATE,IN vWarehouse TINYINT,IN isForcedToRecalculate BOOLEAN)
BEGIN

	DECLARE vCacheVisibleCalculated INTEGER;
    DECLARE vCacheAvailableCalculated INTEGER;
    
	CALL cache.visible_refresh(vCacheVisibleCalculated, isForcedToRecalculate, vWarehouse);
    CALL cache.available_refresh(vCacheAvailableCalculated, isForcedToRecalculate, vWarehouse, vDate);

	SELECT a.Id_Article, a.Article, a.Medida, a.Tallos, a.caja, O.Abreviatura as origen, a.Color, tipo_id, an.Nicho,
			a.Categoria, p.`name` as producer, v.visible, av.available
  		FROM vn2008.Articles a 
		LEFT JOIN vn2008.Articles_nicho an ON a.Id_Article = an.Id_Article AND an.warehouse_id = vWarehouse
        LEFT JOIN vn2008.Origen O ON O.id = a.id_origen
        LEFT JOIN vn2008.producer p ON p.producer_id = a.producer_id
        LEFT JOIN cache.visible v ON (vItem IS NULL OR v.item_id = vItem) AND v.calc_id = vCacheVisibleCalculated
        LEFT JOIN cache.available av ON (vItem IS NULL OR av.item_id = vItem) AND av.calc_id = vCacheAvailableCalculated
		WHERE (vItem IS NULL OR a.Id_Article = vItem);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceCorrectedSalekk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceCorrectedSalekk`(vInvoiceOut INT)
BEGIN

/* Devuelve los registros de la factura en cuestion, para preparar la factura rectificativa
*	
*	param vInvoiceOutId Referencia de la factura emitida, tal como se ve en el ticket
*
*/


SELECT 
        s.id,
        s.itemFk,
        s.quantity,
        s.price,
        s.discount
    FROM sale s
        JOIN ticket t ON t.id = s.ticketFk
        WHERE t.invoice = vInvoiceOut;



END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceExpenceMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceExpenceMake`(IN vInvoice INT)
BEGIN
/* Inserta las partidas de gasto correspondientes a la factura
 * REQUIERE tabla ticketToInvoice
 *
 * @param vInvoice Numero de factura
 *
 */
	DELETE FROM invoiceOutExpence
		WHERE invoiceOutFk = vInvoice;

	INSERT INTO invoiceOutExpence(
									invoiceOutFk,
									expenceFk,
									amount
								)
		SELECT
			vInvoice,
			expenceFk,
			SUM(ROUND(quantity * price * (100 - discount)/100,2)) amount
			FROM ticketToInvoice t
				JOIN sale s ON s.ticketFk = t.id
				JOIN item i ON i.id = s.itemFk
			GROUP BY i.expenceFk
			HAVING 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 `invoiceFromAddress` */;
ALTER DATABASE `vn` 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 `invoiceFromAddress`(vMaxTicketDate DATETIME,vAddress INT,vCompany INT)
BEGIN    

	DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(MONTH, -3, CURDATE());
    
	SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate);
    
	DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`;
    
	CREATE TEMPORARY TABLE `ticketToInvoice`
		(PRIMARY KEY  (`id`))
        ENGINE = MEMORY
		SELECT Id_Ticket id FROM vn2008.Tickets WHERE (Fecha BETWEEN vMinDateTicket
			AND vMaxTicketDate) AND Id_Consigna = vAddress 
            AND Factura IS NULL AND empresa_id = 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 */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromClient` */;
ALTER DATABASE `vn` 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 `invoiceFromClient`(vMaxTicketDate DATETIME, vClient INT, vCompany INT)
BEGIN    

	DECLARE vMinDateTicket DATE DEFAULT TIMESTAMPADD(YEAR, -3, CURDATE());
    
    SET vMaxTicketDate = vn2008.DAYEND(vMaxTicketDate);
    
	DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`;
    
	CREATE TEMPORARY TABLE `ticketToInvoice`
		(PRIMARY KEY  (`id`))
        ENGINE = MEMORY
			SELECT Id_Ticket id FROM vn2008.Tickets 
				WHERE Id_Cliente = vClient 
                AND Factura IS NULL 
                AND empresa_id = vCompany
				AND (Fecha BETWEEN vMinDateTicket AND vMaxTicketDate) 
					;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceFromTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceFromTicket`(IN vTicket INT)
BEGIN    

	DROP TEMPORARY TABLE IF EXISTS `ticketToInvoice`;
    
	CREATE TEMPORARY TABLE `ticketToInvoice`
	(PRIMARY KEY  (`id`))
        ENGINE = MEMORY
        SELECT id FROM vn.ticket
            WHERE id = vTicket AND refFk IS 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 `invoiceInBookingCommon` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceInBookingCommon`(vInvoiceInId INT, OUT vSerialNumber INT)
BEGIN

	DROP TEMPORARY TABLE IF EXISTS newInvoiceIn;

	CREATE TEMPORARY TABLE newInvoiceIn
		SELECT 
				i.*,
				YEAR(i.booked) datedYear,
				-- CONCAT('s/fra',RIGHT(i.supplierRef,8)) concept,
				CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, 
				(cc.id = c.id) isSameCountry,
				cit.id invoicesCount
			FROM invoiceIn i
				JOIN cplusInvoiceType472 cit ON cit.id = i.cplusInvoiceType472Fk
				JOIN supplier s ON s.id = i.supplierFk
				JOIN country c ON c.id = s.countryFk
				JOIN supplier sc ON sc.id = i.companyFk
				JOIN country cc ON cc.id = sc.countryFk
			WHERE i.id = vInvoiceInId;

	DROP TEMPORARY TABLE IF EXISTS newSupplier;
	CREATE TEMPORARY TABLE newSupplier
		SELECT 
                s.*,
                REPLACE(s.account,' ','') supplierAccount,
                IF(c.CEE < 2, TRUE, FALSE) isUeeMember
            FROM supplier s
                JOIN newInvoiceIn n
                JOIN country c ON c.id = s.countryFk
            WHERE s.id = n.supplierFk;

	IF (SELECT isActive FROM newSupplier) = 0 THEN
		CALL util.throw('INACTIVE_PROVIDER');
	END IF;

    SELECT IFNULL(MAX(i.serialNumber) + 1,1) 
			INTO vSerialNumber
		FROM invoiceIn i
			JOIN newInvoiceIn n
		WHERE i.serial LIKE n.serial 
			AND YEAR(i.booked) = n.datedYear
			AND i.companyFk = n.companyFk
		GROUP BY i.companyFk;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingExtra` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceInBookingExtra`(vInvoiceInId INT)
BEGIN
	DECLARE vBookNumber,vSerialNumber INT;
    
	CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber);
    
	SELECT MAX(ASIEN) + 1 
		INTO vBookNumber
	FROM vn2008.XDiario;
    
	-- Actualizacion de la fecha de contabilizado y de operacion de las importaciones
	UPDATE invoiceInEntry iie 
			JOIN invoiceIn ii ON ii.id = iie.invoiceInFk
            JOIN invoiceInAwb iia ON iia.invoiceInFk = iie.invoiceInAwbFk
            JOIN awb a ON a.id = iia.awbFk
		SET ii.isBooked = TRUE,
			ii.booked = IFNULL(ii.booked,a.booked),
			ii.operated = IFNULL(ii.operated,a.operated),
            ii.issued = IFNULL(ii.issued,a.issued),
            ii.bookEntried = IFNULL(ii.bookEntried,a.bookEntried)
		WHERE iie.invoiceInAwbFk = vInvoiceInId;
        
	-- Extracomunitarias gasto contra proveedor/acreedor 
	INSERT INTO vn2008.XDiario (
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA,
		EURODEBE,
		CONCEPTO, 
        CAMBIO,
		DEBEME,
		NFACTICK,
		empresa_id
	)
	SELECT
			vBookNumber ASIEN,
			IFNULL(a.bookEntried, n.bookEntried) FECHA,
			iit.expenceFk SUBCTA,
			s.account CONTRA,
			ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EURODEBE,
			CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO,
            SUM(iit.taxableBase) / SUM(iit.foreignValue) CAMBIO,
            ROUND(SUM(iit.foreignValue) * (iie.percentage / 100),2) DEBEME,
			n.invoicesCount NFACTICK,
			n.companyFk empresa_id
		FROM newInvoiceIn n 
			JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id
			JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk 
			JOIN invoiceIn i ON i.id = iit.invoiceInFk
			JOIN supplier s ON s.id = i.supplierFk
			LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id
			LEFT JOIN awb a ON a.id = iia.awbFk
		WHERE iie.percentage 
		GROUP BY i.id;

	-- Extracomunitarias proveedor contra gasto
	INSERT INTO vn2008.XDiario (
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA,
		EUROHABER,
		CONCEPTO, 
		CAMBIO,
		HABERME,
		NFACTICK,
		empresa_id
	)
	SELECT
			vBookNumber ASIEN,
			IFNULL(a.bookEntried, n.bookEntried) FECHA,
			s.account SUBCTA,
			iit.expenceFk CONTRA,
			ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EUROHABER,
			CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO,
            SUM(iit.taxableBase) / SUM(iit.foreignValue) CAMBIO,
            SUM(iit.foreignValue) HABERME,
			n.invoicesCount NFACTICK,
			n.companyFk empresa_id
		FROM newInvoiceIn n 
			JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id
			JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk 
			JOIN invoiceIn i ON i.id = iit.invoiceInFk
			JOIN supplier s ON s.id = i.supplierFk
			LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id
			LEFT JOIN awb a ON a.id = iia.awbFk
		WHERE iie.percentage 
		GROUP BY i.id;

	-- Iva Importacion pendiente

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONCEPTO, 
		EUROHABER,-- EURODEBE
		SERIE,
		empresa_id)

	SELECT 
			vBookNumber,
			a.bookEntried,
			'4700000999',
			n.conceptWithSupplier,
			ROUND(SUM(iii.amount * (tc.rate/100)),2) eurohaber,
			n.serial,
			n.companyFk
		FROM newInvoiceIn n
			JOIN invoiceInIntrastat iii ON n.id = iii.invoiceInFk
			JOIN intrastat ii ON ii.id = iii.intrastatFk
			JOIN taxCode tc ON tc.id = ii.taxCodeFk
            JOIN invoiceInAwb iia ON iia.invoiceInFk = iii.invoiceInFk
			JOIN awb a ON a.id = iia.awbFk
		HAVING eurohaber IS NOT NULL;

        -- Linea iva importacion extracomunitaria

	SET @cont:=1;
	SET @total:=0;

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EURODEBE,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		FECHA_EX,
		FECHA_OP,
		FACTURAEX,
		NFACTICK,
		L340,
		LDIFADUAN,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		empresa_id,
		FECREGCON
	)

	SELECT 
			vBookNumber ASIEN,
			x.FECHA,
			x.SUBCTA,
			x.CONTRA,
			IF (n.isSameCountry OR NOT s.isUeeMember, 
			x.EURODEBE,
			NULL
			) EURODEBE,
			x.BASEEURO, 
			x.CONCEPTO,
			vSerialNumber FACTURA,
			x.IVA,
			'*' AUXILIAR, 
			x.SERIE,
			x.FECHA_EX,
			x.FECHA_OP,
			x.dua FACTURAEX,
			n.invoicesCount NFACTICK,
			IF(@total:=@total + x.EURODEBE AND @cont:=@cont + 1 ,1,1) L340,
			TRUE LDIFADUAN,
			x.TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			5 TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
			x.TERIDNIF,
			x.TERNIF,
			x.TERNOM,
			n.companyFk,
			IFNULL(x.FECREGCON,n.booked) FECREGCON

		FROM newInvoiceIn n
			JOIN newSupplier s 
			JOIN ( 
				SELECT 
						-- CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10))
						CONCAT('COMPRA s/fra ',ii.supplierRef,':',LEFT(s.name, 10)) CONCEPTO,
						tc.code SUBCTA,
						s.account CONTRA,
						tc.rate IVA,
						ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount)*(tc.rate/100),2) EURODEBE,
						ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount),2) BASEEURO,
						ii.serial SERIE,
						e.supplierFk,
						iia.dua,
						iis.cplusTerIdNifFk TERIDNIF,
						s.nif AS TERNIF,
						s.name AS TERNOM,
						ii.booked FECREGCON,
						ii.cplusTrascendency472Fk TIPOCLAVE,
						a.issued FECHA_EX,
						a.operated FECHA_OP,
						a.bookEntried FECHA
					FROM invoiceInAwb iia
						JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = iia.invoiceInFk
						JOIN awb a ON a.id = iia.awbFk
						JOIN invoiceIn ii ON ii.id = iie.invoiceInFk
						JOIN invoiceInSerial iis ON iis.code = ii.serial
						JOIN buy b ON b.entryFk = iie.entryFk
						JOIN item i ON i.id = b.itemFk
			JOIN (
				SELECT 
						i.intrastatFk,
						sum(b.buyingValue * b.quantity) as intrastatSum
					FROM buy b
						JOIN item i ON i.id = b.itemFk
						JOIN invoiceInEntry iie ON iie.entryFk = b.entryFk 
						JOIN invoiceInAwb iia ON iia.invoiceInFk = iie.invoiceInAwbFk
						JOIN awb aw ON aw.id =iia.awbFk 
					WHERE iie.percentage AND iia.invoiceInFk = vInvoiceInId
					GROUP BY i.intrastatFk
			) intraSub ON intraSub.intrastatFk = i.intrastatFk
			JOIN (
				SELECT 
						iii.intrastatFk,
						iii.amount,
						intr.taxCodeFk
					FROM invoiceInIntrastat iii
						JOIN intrastat intr	ON intr.id = iii.intrastatFk
					WHERE iii.invoiceInFk = vInvoiceInId
			) taxSub ON taxSub.intrastatFk = i.intrastatFk
			JOIN taxCode tc ON tc.id = taxSub.taxCodeFk
			JOIN entry e ON e.id = iie.entryFk
			JOIN supplier s ON s.id = e.supplierFk
		WHERE iie.invoiceInAwbFk = vInvoiceInId AND iie.percentage 
			GROUP BY e.supplierFk, taxSub.taxCodeFk
			) x
		GROUP BY x.supplierFk, x.IVA;

	/*UPDATE newInvoiceIn n
			JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = vInvoiceInId
			JOIN invoiceIn ii ON ii.id = iie.invoiceInFk
		SET ii.isBooked = TRUE,
			ii.booked = IFNULL(ii.booked,n.booked),
			ii.operated = IFNULL(ii.operated,n.operated),
            ii.issued = IFNULL(ii.issued,n.issued);*/
            
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceInBookingkk`(vInvoiceInId INT)
BEGIN
	/* OBSOLETO usar invoiceInBookingMain o invoiceInBookingExtra */
	DECLARE vSerialNumber, vBookNumber, vBookNumberPlus1 INT;
	DECLARE vTotalAmount DECIMAL(10,2);

	DROP TEMPORARY TABLE IF EXISTS newInvoiceIn;

	CREATE TEMPORARY TABLE newInvoiceIn
		SELECT 
				i.*,
				YEAR(i.booked) datedYear,
				-- CONCAT('s/fra',RIGHT(i.supplierRef,8)) concept,
				CONCAT('s/fra',RIGHT(i.supplierRef,8),':',LEFT(s.name, 10)) conceptWithSupplier, 
				(cc.id = c.id) isSameCountry,
				cit.id invoicesCount
			FROM invoiceIn i
				JOIN cplusInvoiceType472 cit ON cit.id = i.cplusInvoiceType472Fk
				JOIN supplier s ON s.id = i.supplierFk
				JOIN country c ON c.id = s.countryFk
				JOIN supplier sc ON sc.id = i.companyFk
				JOIN country cc ON cc.id = sc.countryFk
			WHERE i.id = vInvoiceInId;

	DROP TEMPORARY TABLE IF EXISTS newSupplier;
	CREATE TEMPORARY TABLE newSupplier
		SELECT 
			s.*,
			REPLACE(s.account,' ','') supplierAccount,
			IF(c.CEE < 2, TRUE, FALSE) isUeeMember
		FROM supplier s
			JOIN newInvoiceIn n
			JOIN country c ON c.id = s.countryFk
		WHERE s.id = n.supplierFk;

	IF (SELECT isActive FROM newSupplier) = 0 THEN
		CALL util.throw('INACTIVE_PROVIDER');
	END IF;

	SELECT IFNULL(MAX(i.serialNumber) + 1,1) 
			INTO vSerialNumber
		FROM invoiceIn i
			JOIN newInvoiceIn n
		WHERE i.serial LIKE n.serial 
			AND YEAR(i.booked) = n.datedYear
			AND i.companyFk = n.companyFk
		GROUP BY i.companyFk;

	SELECT MAX(ASIEN) + 1 
			INTO vBookNumber
		FROM vn2008.XDiario;

	SET vBookNumberPlus1 = vBookNumber + 1;

	SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1))
			INTO vTotalAmount
		FROM invoiceIn i
			JOIN invoiceInTax iit ON iit.invoiceInFk = i.id
			JOIN taxCode tc ON iit.taxCodeFk = tc.id
		WHERE i.id = vInvoiceInId;

	-- Apunte del proveedor

	INSERT INTO vn2008.XDiario(
			ASIEN,
			FECHA,
			SUBCTA,
			EUROHABER,
			CONCEPTO,
			NFACTICK,
			empresa_id)
			SELECT 
			vBookNumber,
			n.booked,
			s.supplierAccount,
			vTotalAmount,
			n.conceptWithSupplier,
			n.invoicesCount,
			n.companyFk
		FROM newInvoiceIn n 
			JOIN newSupplier s;

	-- ----------------------------------------------------------- Linea de Gastos
	INSERT INTO vn2008.XDiario (
	ASIEN,
	FECHA,
	SUBCTA,
	CONTRA,
	EURODEBE,
	EUROHABER,
	CONCEPTO, 
	NFACTICK,
	empresa_id
	)
	SELECT
	vBookNumber ASIEN,
	n.booked FECHA,
	if(
	e.isWithheld,
	LPAD(RIGHT(s.supplierAccount ,5),10,iit.expenceFk),
	iit.expenceFk
	) SUBCTA,
	s.supplierAccount CONTRA,
	if(
	e.isWithheld,
	NULL,
	ABS(ROUND(SUM(iit.taxableBase),2))
	) EURODEBE,
	if(
	e.isWithheld,
	ABS(ROUND(SUM(iit.taxableBase),2)),
	NULL
	) EUROHABER,
	n.conceptWithSupplier CONCEPTO,
	n.invoicesCount NFACTICK,
	n.companyFk empresa_id
	FROM newInvoiceIn n
	JOIN newSupplier s 
	JOIN invoiceInTax iit ON iit.invoiceInFk = n.id
	JOIN taxCode tc ON tc.id = iit.taxCodeFk
	JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk
	WHERE iit.expenceFk != 5660000002 
	GROUP BY iit.expenceFk;

	-- Extracomunitarias gasto contra proveedor/acreedor 
	INSERT INTO vn2008.XDiario (
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA,
		EURODEBE,
		CONCEPTO, 
		NFACTICK,
		empresa_id
	)
	SELECT
			vBookNumberPlus1 ASIEN,
			IFNULL(a.booked, n.booked) FECHA,
			iit.expenceFk SUBCTA,
			s.account CONTRA,
			ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EURODEBE, 
			CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO,
			n.invoicesCount NFACTICK,
			n.companyFk empresa_id
		FROM newInvoiceIn n 
			JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id
			JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk 
			JOIN invoiceIn i ON i.id = iit.invoiceInFk
			JOIN supplier s ON s.id = i.supplierFk
			LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id
			LEFT JOIN awb a ON a.id = iia.awbFk
		WHERE iie.percentage 
		GROUP BY i.id;

	-- Extracomunitarias proveedor contra gasto
	INSERT INTO vn2008.XDiario (
	ASIEN,
	FECHA,
	SUBCTA,
	CONTRA,
	EUROHABER,
	CONCEPTO, 
	NFACTICK,
	empresa_id
	)
	SELECT
	vBookNumberPlus1 ASIEN,
	IFNULL(a.booked, n.booked) FECHA,
	s.account SUBCTA,
	iit.expenceFk CONTRA,
	ROUND(SUM(iit.taxableBase) * (iie.percentage / 100),2) EUROHABER,
	CONCAT('COMPRA s/fra ',i.supplierRef,':',LEFT(s.name, 10)) CONCEPTO,
	n.invoicesCount NFACTICK,
	n.companyFk empresa_id
	FROM newInvoiceIn n 
	JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = n.id
	JOIN invoiceInTax iit ON iit.invoiceInFk = iie.invoiceInFk 
	JOIN invoiceIn i ON i.id = iit.invoiceInFk
	JOIN supplier s ON s.id = i.supplierFk
    LEFT JOIN invoiceInAwb iia ON iia.invoiceInFk = n.id
	LEFT JOIN awb a ON a.id = iia.awbFk
	WHERE iie.percentage 
	GROUP BY i.id;

	-- --------------------------------------------------------------------
	-- ------- Lineas de IVA ---------------
	-- --------------------------------------------------------------------

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EURODEBE,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		TIPOOPE,
		FECHA_EX,
		FECHA_OP,
		NFACTICK,
		FACTURAEX,
		L340,
		LRECT349,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		FECREGCON,
		empresa_id
	)
		SELECT 	vBookNumber ASIEN,
			n.booked FECHA,
			tc.code SUBCTA,
			s.supplierAccount CONTRA,
			SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE,
			SUM(it.taxableBase) BASEEURO,
			GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
			vSerialNumber FACTURA,
			tc.rate IVA,
			IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR,
			n.serial SERIE,
			tt.TIPOOPE,
			n.issued FECHA_EX,
			n.operated FECHA_OP,
			n.invoicesCount NFACTICK,
			n.supplierRef FACTURAEX,
			TRUE L340,
			(isSameCountry OR NOT isUeeMember) LRECT349,
			n.cplusTrascendency472Fk TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			n.cplusInvoiceType472Fk TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
			iis.cplusTerIdNifFk TERIDNIF,
			s.nif AS TERNIF,
			s.name AS TERNOM,
			n.booked FECREGCON,
			n.companyFk

	FROM newInvoiceIn n
		JOIN newSupplier s 
		JOIN invoiceInTax it ON n.id = it.invoiceInFk
		JOIN taxCode tc ON tc.id = it.taxCodeFk
		JOIN taxType tt ON tt.id = tc.taxTypeFk
		JOIN invoiceInSerial iis ON iis.code = tt.serial
		JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
		LEFT JOIN 
			(SELECT eWithheld.id 
				FROM invoiceInTax hold 
					JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld 
				WHERE hold.invoiceInFk = 58262 LIMIT 1
			) eWithheld ON TRUE 
	WHERE tc.type != '-' 
		AND tc.isActive
	GROUP BY tc.rate;

	-- Linea iva inversor sujeto pasivo

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EUROHABER,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		TIPOOPE,
		FECHA_EX,
		FECHA_OP,
		NFACTICK,
		FACTURAEX,
		L340,
		LRECT349,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		empresa_id
	)

	SELECT 
			vBookNumber ASIEN,
			n.booked FECHA,
			tcLink.code SUBCTA,
			s.supplierAccount CONTRA,
			ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER,
			ROUND(SUM(it.taxableBase),2) BASEEURO,
			GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
			vSerialNumber FACTURA,
			tcLink.rate IVA,
			'*' AUXILIAR,
			n.serial SERIE,
			tt.TIPOOPE,
			n.issued FECHA_EX,
			n.operated FECHA_OP,
			n.invoicesCount NFACTICK,
			n.supplierRef FACTURAEX,
			FALSE L340,
			(isSameCountry OR NOT isUeeMember) LRECT349,
			1 TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			n.cplusInvoiceType472Fk TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
            iis.cplusTerIdNifFk TERIDNIF,
			s.nif AS TERNIF,
			s.name AS TERNOM,
			n.companyFk

		FROM newInvoiceIn n 
			JOIN newSupplier s 
			JOIN invoiceInTax it ON n.id = it.invoiceInFk
			JOIN taxCode tc ON tc.id = it.taxCodeFk
			JOIN taxType tt ON tt.id = tc.taxTypeFk
			JOIN invoiceInSerial iis ON iis.code = tt.serial
			JOIN taxCode tcLink ON tcLink.linkFk = tc.linkFk AND tc.id != tcLink.id
			JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
		WHERE tc.isActive 
		GROUP BY tcLink.rate, e.id;

	-- Iva Importacion pendiente

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONCEPTO, 
		EUROHABER,-- EURODEBE
		SERIE,
		empresa_id)

	SELECT 
			vBookNumberPlus1,
			a.booked,
			'4700000999',
			n.conceptWithSupplier,
			ROUND(SUM(iii.amount * (tc.rate/100)),2) eurohaber,
			n.serial,
			n.companyFk
		FROM newInvoiceIn n
			JOIN invoiceInIntrastat iii ON n.id = iii.invoiceInFk
			JOIN intrastat ii ON ii.id = iii.intrastatFk
			JOIN taxCode tc ON tc.id = ii.taxCodeFk
            JOIN invoiceInAwb iia ON iia.invoiceInFk = iii.invoiceInFk
			JOIN awb a ON a.id = iia.awbFk
		HAVING eurohaber IS NOT NULL;


	-- Linea iva importacion extracomunitaria

	SET @cont:=1;
	SET @total:=0;
	SET @base:=2;

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EURODEBE,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		FECHA_EX,
		FECHA_OP,
		FACTURAEX,
		NFACTICK,
		L340,
		LDIFADUAN,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		empresa_id,
		FECREGCON
	)

	SELECT 
			vBookNumberPlus1 ASIEN,
			x.FECHA,
			x.SUBCTA,
			x.CONTRA,
			IF (n.isSameCountry OR NOT s.isUeeMember, 
			x.EURODEBE,
			NULL
			) EURODEBE,
			x.BASEEURO, 
			x.CONCEPTO,
			vSerialNumber FACTURA,
			x.IVA,
			'*' AUXILIAR, 
			x.SERIE,
			x.FECHA_EX,
			x.FECHA_OP,
			x.dua FACTURAEX,
			n.invoicesCount NFACTICK,
			IF(@total:=@total + x.EURODEBE AND @cont:=@cont + 1 ,1,1) L340,
			TRUE LDIFADUAN,
			x.TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			5 TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
			x.TERIDNIF,
			x.TERNIF,
			x.TERNOM,
			n.companyFk,
			IFNULL(x.FECREGCON,n.booked) FECREGCON

		FROM newInvoiceIn n
			JOIN newSupplier s 
			JOIN ( 
				SELECT 
				-- CONCAT('COMPRA s/fra ',sref,':',LEFT(p.Proveedor, 10))
				CONCAT('COMPRA s/fra ',ii.supplierRef,':',LEFT(s.name, 10)) CONCEPTO,
				tc.code SUBCTA,
				s.account CONTRA,
				tc.rate IVA,
				ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount)*(tc.rate/100),2) EURODEBE,
				ROUND(sum(b.buyingValue * b.quantity / intraSub.intrastatSum * taxSub.amount),2) BASEEURO,
				ii.serial SERIE,
				e.supplierFk,
				iia.dua,
				iis.cplusTerIdNifFk TERIDNIF,
				s.nif AS TERNIF,
				s.name AS TERNOM,
				ii.booked FECREGCON,
                ii.cplusTrascendency472Fk TIPOCLAVE,
                a.issued FECHA_EX,
				a.operated FECHA_OP,
                a.booked FECHA
				FROM invoiceInAwb iia
				JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = iia.invoiceInFk
				JOIN awb a ON a.id = iia.awbFk
				JOIN invoiceIn ii ON ii.id = iie.invoiceInFk
				JOIN invoiceInSerial iis ON iis.code = ii.serial
				JOIN buy b ON b.entryFk = iie.entryFk
				JOIN item i ON i.id = b.itemFk
			JOIN (
				SELECT 
				i.intrastatFk,
				sum(b.buyingValue * b.quantity) as intrastatSum
				FROM buy b
				JOIN item i ON i.id = b.itemFk
				JOIN invoiceInEntry iie 
				ON iie.entryFk = b.entryFk 
				JOIN invoiceInAwb iia
				ON iia.invoiceInFk = iie.invoiceInAwbFk
				JOIN awb aw ON aw.id =iia.awbFk 
				WHERE iie.percentage AND iia.invoiceInFk = vInvoiceInId
				GROUP BY i.intrastatFk
			) intraSub ON intraSub.intrastatFk = i.intrastatFk
			JOIN (
				SELECT 
				iii.intrastatFk,
				iii.amount,
				intr.taxCodeFk
				FROM invoiceInIntrastat iii
				JOIN intrastat intr
				ON intr.id = iii.intrastatFk
				WHERE iii.invoiceInFk = vInvoiceInId
			) taxSub ON taxSub.intrastatFk = i.intrastatFk
			JOIN taxCode tc ON tc.id = taxSub.taxCodeFk
			JOIN entry e ON e.id = iie.entryFk
			JOIN supplier s ON s.id = e.supplierFk
		WHERE iie.invoiceInAwbFk = vInvoiceInId AND iie.percentage 
			GROUP BY e.supplierFk, taxSub.taxCodeFk
			) x
			GROUP BY x.supplierFk, x.IVA;

	-- Actualizacion de la fecha de contabilizado y de operacion de las importaciones
	UPDATE newInvoiceIn n
			JOIN invoiceInEntry iie ON iie.invoiceInAwbFk = vInvoiceInId
			JOIN invoiceIn ii ON ii.id = iie.invoiceInFk
		SET ii.booked = IFNULL(ii.booked,n.booked),
			ii.operated = IFNULL(ii.operated,n.issued);
            
	-- Actualización del registro original        
	UPDATE invoiceIn 
		SET 
			serialNumber = vSerialNumber,
			isBooked = TRUE
		WHERE
			id = vInvoiceInId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceInBookingMain` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceInBookingMain`(vInvoiceInId INT)
BEGIN
	DECLARE vTotalAmount,vTotalAmountDivisa DECIMAL(10,2);
    DECLARE vBookNumber,vSerialNumber INT;
    DECLARE vRate DECIMAL(10,4);
    
    CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber);
       
    SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1)),
			SUM(iit.foreignValue * IF(i.serial = 'R', 1 +(tc.rate/100),1)),
            iit.taxableBase/iit.foreignValue
			INTO vTotalAmount, vTotalAmountDivisa, vRate
		FROM newInvoiceIn i
			JOIN invoiceInTax iit ON iit.invoiceInFk = i.id
			JOIN taxCode tc ON iit.taxCodeFk = tc.id;
        
    SELECT MAX(ASIEN) + 1 
            INTO vBookNumber
		FROM vn2008.XDiario;
 
	-- Apunte del proveedor

	INSERT INTO vn2008.XDiario(
			ASIEN,
			FECHA,
			SUBCTA,
			EUROHABER,
			CONCEPTO,
            CAMBIO,
            HABERME,
			NFACTICK,
            CLAVE,
			empresa_id)
        SELECT 
			vBookNumber,
			n.bookEntried,
			s.supplierAccount,
			vTotalAmount,
			n.conceptWithSupplier,
            vRate,
            vTotalAmountDivisa,
			n.invoicesCount,
            vInvoiceInId,
			n.companyFk
		FROM newInvoiceIn n 
			JOIN newSupplier s;

            -- ----------------------------------------------------------- Linea de Gastos
	INSERT INTO vn2008.XDiario (
	ASIEN,
	FECHA,
	SUBCTA,
	CONTRA,
	EURODEBE,
	EUROHABER,
	CONCEPTO, 
    CAMBIO,
    DEBEME,
	HABERME,
	NFACTICK,
	empresa_id
	)
	SELECT
		vBookNumber ASIEN,
		n.bookEntried FECHA,
		if(
			e.isWithheld,
			LPAD(RIGHT(s.supplierAccount,5),10,iit.expenceFk),
			iit.expenceFk
		) SUBCTA,
		s.supplierAccount CONTRA,
		if(
			e.isWithheld,
			NULL,
			ABS(ROUND(SUM(iit.taxableBase),2))
		) EURODEBE,
		if(
			e.isWithheld,
			ABS(ROUND(SUM(iit.taxableBase),2)),
			NULL
		) EUROHABER,
		n.conceptWithSupplier CONCEPTO,
		vRate,
        if(
			e.isWithheld,
			NULL,
			ABS(ROUND(SUM(iit.foreignValue),2))
		) DEBEME,
		if(
			e.isWithheld,
			ABS(ROUND(SUM(iit.foreignValue),2)),
			NULL
		) HABERME,
		n.invoicesCount NFACTICK,
		n.companyFk empresa_id
	FROM newInvoiceIn n
		JOIN newSupplier s 
		JOIN invoiceInTax iit ON iit.invoiceInFk = n.id
		JOIN taxCode tc ON tc.id = iit.taxCodeFk
		JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk
	WHERE iit.expenceFk != 5660000002 
	GROUP BY iit.expenceFk;

    
	-- --------------------------------------------------------------------
	-- ------- Lineas de IVA ---------------
	-- --------------------------------------------------------------------

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EURODEBE,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		TIPOOPE,
		FECHA_EX,
		FECHA_OP,
		NFACTICK,
		FACTURAEX,
		L340,
		LRECT349,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		FECREGCON,
		empresa_id
	)
		SELECT 	vBookNumber ASIEN,
			n.bookEntried FECHA,
			tc.code SUBCTA,
			s.supplierAccount CONTRA,
			SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE,
			SUM(it.taxableBase) BASEEURO,
			GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
			vSerialNumber FACTURA,
			tc.rate IVA,
			IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR,
			n.serial SERIE,
			tt.TIPOOPE,
			n.issued FECHA_EX,
			n.operated FECHA_OP,
			n.invoicesCount NFACTICK,
			n.supplierRef FACTURAEX,
			TRUE L340,
			(isSameCountry OR NOT isUeeMember) LRECT349,
			n.cplusTrascendency472Fk TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			n.cplusInvoiceType472Fk TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
			iis.cplusTerIdNifFk TERIDNIF,
			s.nif AS TERNIF,
			s.name AS TERNOM,
			n.booked FECREGCON,
			n.companyFk

	FROM newInvoiceIn n
		JOIN newSupplier s 
		JOIN invoiceInTax it ON n.id = it.invoiceInFk
		JOIN taxCode tc ON tc.id = it.taxCodeFk
		JOIN taxType tt ON tt.id = tc.taxTypeFk
		JOIN invoiceInSerial iis ON iis.code = tt.serial
		JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
		LEFT JOIN 
			(SELECT eWithheld.id 
				FROM invoiceInTax hold 
					JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld 
				WHERE hold.invoiceInFk = 58262 LIMIT 1
			) eWithheld ON TRUE 
	WHERE tc.type != '-' 
		AND tc.isActive
	GROUP BY tc.rate;

	-- Linea iva inversor sujeto pasivo

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EUROHABER,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		TIPOOPE,
		FECHA_EX,
		FECHA_OP,
		NFACTICK,
		FACTURAEX,
		L340,
		LRECT349,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		empresa_id
	)

	SELECT 
			vBookNumber ASIEN,
			n.bookEntried FECHA,
			tcLink.code SUBCTA,
			s.supplierAccount CONTRA,
			ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER,
			ROUND(SUM(it.taxableBase),2) BASEEURO,
			GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
			vSerialNumber FACTURA,
			tcLink.rate IVA,
			'*' AUXILIAR,
			n.serial SERIE,
			tt.TIPOOPE,
			n.issued FECHA_EX,
			n.operated FECHA_OP,
			n.invoicesCount NFACTICK,
			n.supplierRef FACTURAEX,
			FALSE L340,
			(isSameCountry OR NOT isUeeMember) LRECT349,
			1 TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			n.cplusInvoiceType472Fk TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
            iis.cplusTerIdNifFk TERIDNIF,
			s.nif AS TERNIF,
			s.name AS TERNOM,
			n.companyFk

		FROM newInvoiceIn n 
			JOIN newSupplier s 
			JOIN invoiceInTax it ON n.id = it.invoiceInFk
			JOIN taxCode tc ON tc.id = it.taxCodeFk
			JOIN taxType tt ON tt.id = tc.taxTypeFk
			JOIN invoiceInSerial iis ON iis.code = tt.serial
			JOIN taxCode tcLink ON tcLink.link = tc.link AND tc.id != tcLink.id
			JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
		WHERE tc.isActive 
		GROUP BY tcLink.rate, e.id;

-- Actualización del registro original        
	UPDATE invoiceIn ii
		JOIN newInvoiceIn ni ON ii.id = ni.id
		SET 
			ii.serialNumber = vSerialNumber,
			ii.isBooked = 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 `invoiceInBookingMainkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceInBookingMainkk`(vInvoiceInId INT)
BEGIN
	DECLARE vTotalAmount DECIMAL(10,2);
    DECLARE vBookNumber,vSerialNumber INT;
    
    CALL invoiceInBookingCommon(vInvoiceInId,vSerialNumber);
       
    SELECT SUM(iit.taxableBase * IF(i.serial = 'R', 1 +(tc.rate/100),1))
			INTO vTotalAmount
		FROM newInvoiceIn i
			JOIN invoiceInTax iit ON iit.invoiceInFk = i.id
			JOIN taxCode tc ON iit.taxCodeFk = tc.id;
        
    SELECT MAX(ASIEN) + 1 
            INTO vBookNumber
		FROM vn2008.XDiario;
 
	-- Apunte del proveedor

	INSERT INTO vn2008.XDiario(
			ASIEN,
			FECHA,
			SUBCTA,
			EUROHABER,
			CONCEPTO,
			NFACTICK,
			empresa_id)
        SELECT 
			vBookNumber,
			n.bookEntried,
			s.supplierAccount,
			vTotalAmount,
			n.conceptWithSupplier,
			n.invoicesCount,
			n.companyFk
		FROM newInvoiceIn n 
			JOIN newSupplier s;

            -- ----------------------------------------------------------- Linea de Gastos
	INSERT INTO vn2008.XDiario (
	ASIEN,
	FECHA,
	SUBCTA,
	CONTRA,
	EURODEBE,
	EUROHABER,
	CONCEPTO, 
	NFACTICK,
	empresa_id
	)
	SELECT
	vBookNumber ASIEN,
	n.bookEntried FECHA,
	if(
	e.isWithheld,
	LPAD(RIGHT(s.supplierAccount ,5),10,iit.expenceFk),
	iit.expenceFk
	) SUBCTA,
	s.supplierAccount CONTRA,
	if(
	e.isWithheld,
	NULL,
	ABS(ROUND(SUM(iit.taxableBase),2))
	) EURODEBE,
	if(
	e.isWithheld,
	ABS(ROUND(SUM(iit.taxableBase),2)),
	NULL
	) EUROHABER,
	n.conceptWithSupplier CONCEPTO,
	n.invoicesCount NFACTICK,
	n.companyFk empresa_id
	FROM newInvoiceIn n
	JOIN newSupplier s 
	JOIN invoiceInTax iit ON iit.invoiceInFk = n.id
	JOIN taxCode tc ON tc.id = iit.taxCodeFk
	JOIN expence e ON e.id = iit.expenceFk AND e.taxTypeFk = tc.taxTypeFk
	WHERE iit.expenceFk != 5660000002 
	GROUP BY iit.expenceFk;

    
	-- --------------------------------------------------------------------
	-- ------- Lineas de IVA ---------------
	-- --------------------------------------------------------------------

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EURODEBE,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		TIPOOPE,
		FECHA_EX,
		FECHA_OP,
		NFACTICK,
		FACTURAEX,
		L340,
		LRECT349,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		FECREGCON,
		empresa_id
	)
		SELECT 	vBookNumber ASIEN,
			n.bookEntried FECHA,
			tc.code SUBCTA,
			s.supplierAccount CONTRA,
			SUM(ROUND(tc.rate/100*it.taxableBase + 0.0001,2)) EURODEBE,
			SUM(it.taxableBase) BASEEURO,
			GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
			vSerialNumber FACTURA,
			tc.rate IVA,
			IF(isUeeMember AND eWithheld.id IS NULL,'','*') AUXILIAR,
			n.serial SERIE,
			tt.TIPOOPE,
			n.issued FECHA_EX,
			n.operated FECHA_OP,
			n.invoicesCount NFACTICK,
			n.supplierRef FACTURAEX,
			TRUE L340,
			(isSameCountry OR NOT isUeeMember) LRECT349,
			n.cplusTrascendency472Fk TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			n.cplusInvoiceType472Fk TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
			iis.cplusTerIdNifFk TERIDNIF,
			s.nif AS TERNIF,
			s.name AS TERNOM,
			n.booked FECREGCON,
			n.companyFk

	FROM newInvoiceIn n
		JOIN newSupplier s 
		JOIN invoiceInTax it ON n.id = it.invoiceInFk
		JOIN taxCode tc ON tc.id = it.taxCodeFk
		JOIN taxType tt ON tt.id = tc.taxTypeFk
		JOIN invoiceInSerial iis ON iis.code = tt.serial
		JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
		LEFT JOIN 
			(SELECT eWithheld.id 
				FROM invoiceInTax hold 
					JOIN expence eWithheld ON eWithheld.id = hold.expenceFk AND eWithheld.isWithheld 
				WHERE hold.invoiceInFk = 58262 LIMIT 1
			) eWithheld ON TRUE 
	WHERE tc.type != '-' 
		AND tc.isActive
	GROUP BY tc.rate;

	-- Linea iva inversor sujeto pasivo

	INSERT INTO vn2008.XDiario(
		ASIEN,
		FECHA,
		SUBCTA,
		CONTRA, 
		EUROHABER,
		BASEEURO,
		CONCEPTO, 
		FACTURA, 
		IVA,
		AUXILIAR, 
		SERIE,
		TIPOOPE,
		FECHA_EX,
		FECHA_OP,
		NFACTICK,
		FACTURAEX,
		L340,
		LRECT349,
		TIPOCLAVE,
		TIPOEXENCI,
		TIPONOSUJE,
		TIPOFACT,
		TIPORECTIF,
		TERIDNIF,
		TERNIF,
		TERNOM,
		empresa_id
	)

	SELECT 
			vBookNumber ASIEN,
			n.bookEntried FECHA,
			tcLink.code SUBCTA,
			s.supplierAccount CONTRA,
			ROUND(tcLink.rate/100*SUM(it.taxableBase) + 0.0001,2) EUROHABER,
			ROUND(SUM(it.taxableBase),2) BASEEURO,
			GROUP_CONCAT(DISTINCT e.`name` SEPARATOR ', ') CONCEPTO,
			vSerialNumber FACTURA,
			tcLink.rate IVA,
			'*' AUXILIAR,
			n.serial SERIE,
			tt.TIPOOPE,
			n.issued FECHA_EX,
			n.operated FECHA_OP,
			n.invoicesCount NFACTICK,
			n.supplierRef FACTURAEX,
			FALSE L340,
			(isSameCountry OR NOT isUeeMember) LRECT349,
			1 TIPOCLAVE,
			n.cplusTaxBreakFk TIPOEXENCI,
			n.cplusSubjectOpFk TIPONOSUJE,
			n.cplusInvoiceType472Fk TIPOFACT,
			n.cplusRectificationTypeFk TIPORECTIF,
            iis.cplusTerIdNifFk TERIDNIF,
			s.nif AS TERNIF,
			s.name AS TERNOM,
			n.companyFk

		FROM newInvoiceIn n 
			JOIN newSupplier s 
			JOIN invoiceInTax it ON n.id = it.invoiceInFk
			JOIN taxCode tc ON tc.id = it.taxCodeFk
			JOIN taxType tt ON tt.id = tc.taxTypeFk
			JOIN invoiceInSerial iis ON iis.code = tt.serial
			JOIN taxCode tcLink ON tcLink.linkFk = tc.linkFk AND tc.id != tcLink.id
			JOIN expence e ON e.id = it.expenceFk AND e.taxTypeFk = tc.taxTypeFk
		WHERE tc.isActive 
		GROUP BY tcLink.rate, e.id;

-- Actualización del registro original        
	UPDATE invoiceIn ii
		JOIN newInvoiceIn ni ON ii.id = ni.id
		SET 
			ii.serialNumber = vSerialNumber,
			ii.isBooked = 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 `invoiceMakeByClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceMakeByClient`(vClientFk INT, vSerial CHAR(1), vShipped DATE, vCompanyFk INT, OUT vInvoiceId INT)
BEGIN
/**
 * Factura un ticket
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @return Id factura
 */
	CALL invoiceFromClient(vShipped, vClientFk, vCompanyFk);
    CALL invoiceOutMake(vSerial, CURDATE(), vInvoiceId);

    IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
		CALL invoiceOutBooking(vInvoiceId);
        INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); 
    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 `invoiceMakeByTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceMakeByTicket`(vTicketFk INT, vSerial CHAR(1), OUT vInvoiceId INT)
BEGIN
/**
 * Factura un ticket
 * @param vTicketFk Id del ticket
 * @param vSerial Serie de factura
 * @return Id factura
 */
	CALL invoiceFromTicket(vTicketFk);
    CALL invoiceOutMake(vSerial, CURDATE(), vInvoiceId);

    IF vSerial <> 'R' AND NOT ISNULL(vInvoiceId) AND vInvoiceId <> 0 THEN
		CALL invoiceOutBooking(vInvoiceId);
        INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(1, 3, vInvoiceId); 
    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 `invoiceOutAgain` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutAgain`(IN vInvoiceRef VARCHAR(15))
BEGIN

/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
*
* @param vInvoice Numero de factura
*/

	DECLARE vInvoice INT;
    DECLARE vCountry INT;
    DECLARE vTaxArea VARCHAR(15);
    DECLARE vSpainCountryCode INT DEFAULT 1;
    
	SELECT id
		    INTO vInvoice
		FROM invoiceOut 
        WHERE ref =  vInvoiceRef;
        
	UPDATE invoiceOut 
		SET pdf = 0
        WHERE id = vInvoice;
        
	SELECT s.countryFk 
			INTO vCountry
		FROM supplier s
			JOIN invoiceOut io ON io.companyFk = s.id
		WHERE io.id = vInvoice;
        
	SELECT IF(a.isEqualizated 
					AND c.countryFk = vSpainCountryCode 
                    AND i.taxAreaFk = 'NATIONAL',
				'EQU',
                i.taxAreaFk)
			INTO vTaxArea
		FROM invoiceOutSerial i
			JOIN invoiceOut io
			JOIN ticket t ON t.refFk = io.ref
			JOIN address a ON a.id = t.addressFk
            JOIN client c ON c.id = t.clientFk
		WHERE io.id = vInvoice AND i.code = invoiceSerial(io.clientFk,io.companyFk,'R')
        LIMIT 1;
  
	DROP TEMPORARY TABLE IF EXISTS ticketToInvoice;

	CREATE TEMPORARY TABLE ticketToInvoice
        SELECT id 
            FROM ticket 
            WHERE refFk = vInvoiceRef;

	CALL invoiceExpenceMake(vInvoice);
	CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea);
    
    UPDATE invoiceOut io
		JOIN (
			SELECT SUM(amount) AS total
				FROM invoiceOutExpence 
                WHERE invoiceOutFk = vInvoice
			) base
		JOIN (
			SELECT SUM(vat) AS total
				FROM invoiceOutTax 
                WHERE invoiceOutFk = vInvoice
			) vat
	SET io.amount = base.total + vat.total
    WHERE io.id = vInvoice;
   
	CALL vn.invoiceOutBooking(vInvoice);
    

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutAgainDateRange` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutAgainDateRange`(IN vFirstDate DATE, IN vLastDate DATE)
BEGIN

	DECLARE done BOOL DEFAULT FALSE;
	DECLARE vInvoice INT;
	DECLARE vInvoiceRef VARCHAR(15);
    DECLARE vContador INT DEFAULT 0;

	DECLARE rs CURSOR FOR 
		SELECT id, ref 
			FROM vn.invoiceOut 
            WHERE issued BETWEEN vFirstDate AND vLastDate
				AND booked IS NULL;

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoice, vInvoiceRef;

	WHILE NOT done DO

		CALL vn.invoiceOutAgain(vInvoiceRef);

		FETCH rs INTO vInvoice, vInvoiceRef;
        
        SET vContador = vContador + 1;
        
        IF vContador MOD 50 = 0 THEN
        
			SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS;
        
		END IF;
	END WHILE;

	CLOSE rs;

	SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBooking` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutBooking`(IN vInvoice INT)
BEGIN

/* Asienta la factura emitida
*
* param vInvoice factura_id
*/

	DECLARE vBookNumber INT;
    DECLARE vExpenceConcept VARCHAR(50);
    DECLARE isUEENotSpain INT DEFAULT 1;
    DECLARE vSpain INT DEFAULT 1;
    DECLARE vOldBookNumber INT;
    
    SELECT ASIEN
			INTO vOldBookNumber
		FROM vn2008.XDiario x
			JOIN vn.invoiceOut io ON io.id = vInvoice
        WHERE x.SERIE = io.serial
			AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1)
		LIMIT 1;
        
	DELETE 
		FROM vn2008.XDiario
		WHERE ASIEN = vOldBookNumber;

	DROP TEMPORARY TABLE IF EXISTS rs;
	CREATE TEMPORARY TABLE rs
		SELECT 
				c.accountingAccount AS clientBookingAccount,
				io.amount as totalAmount,
				CONCAT('n/fra ', io.ref) as simpleConcept,
				CONCAT('n/fra ', io.ref, ' ', c.name) as Concept,
				io.serial AS SERIE,
				io.issued AS FECHA_EX,
				opDate.FECHA_OP,
				io.issued AS FECHA,
				1 AS NFACTICK,
				IF(ic.correctingFk,'D','') AS  TIPOOPE,
				io.cplusTrascendency477Fk AS TIPOCLAVE,
				io.cplusTaxBreakFk AS TIPOEXENCI,
				io.cplusSubjectOpFk AS TIPONOSUJE,
				io.cplusInvoiceType477Fk AS TIPOFACT,
				ic.cplusRectificationTypeFk AS TIPORECTIF,
				io.companyFk,
				RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum,
                IF(ct.politicalCountryFk = vSpain, 1, IF(ct.CEE = isUEENotSpain,2,4)) AS TERIDNIF,
				CONCAT(IF(ct.CEE = isUEENotSpain,ct.code,''),c.fi) AS TERNIF,
				c.socialName AS TERNOM,
                ior.serial AS SERIE_RT,
                RIGHT(ior.ref, LENGTH(ior.ref) - 1) AS FACTU_RT,
                ior.issued AS FECHA_RT,
                IF(ior.id,TRUE,FALSE) AS RECTIFICA

		FROM invoiceOut io
			JOIN (	
					SELECT GREATEST(MAX(shipped), TIMESTAMPADD(DAY,-15,io.issued)) as FECHA_OP 
						FROM ticket t
							JOIN invoiceOut io ON io.ref = t.refFk
						WHERE io.id = vInvoice ) opDate
			JOIN invoiceOutSerial ios ON ios.code = io.serial
			JOIN client c ON c.id = io.clientFk
			JOIN country ct ON ct.id = c.countryFk
			LEFT JOIN invoiceCorrection ic ON ic.correctingFk = io.id
            LEFT JOIN invoiceOut ior ON ior.id = ic.correctedFk
			WHERE io.id = vInvoice;

	SELECT MAX(ASIEN) + 1 
			INTO vBookNumber
		FROM vn2008.XDiario;
    
	-- Linea del cliente
	INSERT INTO vn2008.XDiario(
								ASIEN,
								FECHA,
								SUBCTA,              
								EURODEBE,
								CONCEPTO, 
								FECHA_EX,
								FECHA_OP,
								empresa_id
								)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				rs.clientBookingAccount AS SUBCTA,
				rs.totalAmount AS EURODEBE,
				rs.simpleConcept AS CONCEPTO,
				rs.FECHA_EX,
				rs.FECHA_OP,
				rs.companyFk AS empresa_id
			FROM rs;

		-- Lineas de gasto
		INSERT INTO vn2008.XDiario(
									ASIEN,
									FECHA,
									SUBCTA,
									CONTRA,              
									EUROHABER,
									CONCEPTO, 
									FECHA_EX,
									FECHA_OP,
									empresa_id
									)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				ioe.expenceFk AS SUBCTA,
				rs.clientBookingAccount AS CONTRA,
				ioe.amount AS EUROHABER,
				rs.Concept AS CONCEPTO,
				rs.FECHA_EX,
				rs.FECHA_OP,
				rs.companyFk AS empresa_id
			FROM rs
				JOIN invoiceOutExpence ioe
			WHERE ioe.invoiceOutFk = vInvoice;

    SELECT GROUP_CONCAT(`name` SEPARATOR ',') 
            INTO vExpenceConcept 
        FROM expence e
            JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id
        WHERE ioe.invoiceOutFk = vInvoice;

		-- Lineas de IVA
	INSERT INTO vn2008.XDiario(
								ASIEN,
								FECHA,
								SUBCTA,
								CONTRA,              
								EUROHABER,
								BASEEURO,
								CONCEPTO,
								FACTURA,
								IVA,
								RECEQUIV,
								AUXILIAR,
								SERIE,
								SERIE_RT,
								FACTU_RT,
								RECTIFICA,
								FECHA_RT,
								FECHA_OP,
								FECHA_EX,
								TIPOOPE,
								NFACTICK,
								TERIDNIF,
								TERNIF,
								TERNOM,
								L340,
								TIPOCLAVE,
								TIPOEXENCI,
								TIPONOSUJE,
								TIPOFACT,
								TIPORECTIF,
								empresa_id
								)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				iot.pgcFk AS SUBCTA,
				rs.clientBookingAccount AS CONTRA,
				iot.vat AS EUROHABER,
				iot.taxableBase AS BASEEURO,
				CONCAT(vExpenceConcept,' : ',rs.Concept) AS CONCEPTO,
				rs.invoiceNum AS FACTURA,
                IF(pe2.equFk,0,pgc.rate) AS IVA,
				IF(pe2.equFk,0,pgce.rate) AS RECEQUIV,
				IF(pgc.mod347,'','*') AS AUXILIAR,
				rs.SERIE,
				rs.SERIE_RT,
				rs.FACTU_RT,
				rs.RECTIFICA,
				rs.FECHA_RT,
				rs.FECHA_OP,
				rs.FECHA_EX,
				rs.TIPOOPE,
				rs.NFACTICK,   
				rs.TERIDNIF,
				rs.TERNIF,
				rs.TERNOM,
				pgc.mod340 AS L340,   
				pgc.cplusTrascendency477Fk AS TIPOCLAVE,
				pgc.cplusTaxBreakFk as TIPOEXENCI,
				rs.TIPONOSUJE,
				rs.TIPOFACT,
				rs.TIPORECTIF,
				rs.companyFk AS empresa_id
			FROM rs
				JOIN invoiceOutTax iot 
				JOIN pgc ON pgc.code = iot.pgcFk
				LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk		-- --------------- Comprueba si la linea es de iva con rec.equiv. asociado
				LEFT JOIN pgc pgce ON pgce.code = pe.equFk 
				LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk  	-- --------------- Comprueba si la linea es de rec.equiv.
			WHERE iot.invoiceOutFk = vInvoice;
            
            UPDATE invoiceOut
				SET booked = CURDATE()
                WHERE id = vInvoice;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutBookingkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutBookingkk`(IN vInvoice INT)
BEGIN

/* Asienta la factura emitida
*
* param vInvoice factura_id
*/

	DECLARE vBookNumber INT;
    DECLARE vExpenceConcept VARCHAR(50);
    DECLARE isUEENotSpain INT DEFAULT 1;
    DECLARE vOldBookNumber INT;
    
    SELECT ASIEN
			INTO vOldBookNumber
		FROM vn2008.XDiario x
			JOIN vn.invoiceOut io ON io.id = vInvoice
        WHERE x.SERIE = io.serial
			AND x.FACTURA = RIGHT(io.ref, LENGTH(io.ref) - 1)
		LIMIT 1;
        
	DELETE 
		FROM vn2008.XDiario
		WHERE ASIEN = vOldBookNumber;

	SELECT MAX(ASIEN) + 1 
		INTO vBookNumber
	FROM vn2008.XDiario;

	DROP TEMPORARY TABLE IF EXISTS rs;
	CREATE TEMPORARY TABLE rs
		SELECT 
				c.accountingAccount AS clientBookingAccount,
				io.amount as totalAmount,
				CONCAT('n/fra ', io.ref) as simpleConcept,
				CONCAT('n/fra ', io.ref, ' ', c.name) as Concept,
				io.serial AS SERIE,
				io.issued AS FECHA_EX,
				opDate.FECHA_OP,
				io.issued AS FECHA,
				1 AS NFACTICK,
				IF(ic.correctingFk,'D','') AS  TIPOOPE,
				io.cplusTrascendency477Fk AS TIPOCLAVE,
				io.cplusTaxBreakFk AS TIPOEXENCI,
				io.cplusSubjectOpFk AS TIPONOSUJE,
				io.cplusInvoiceType477Fk AS TIPOFACT,
				ic.cplusRectificationTypeFk AS TIPORECTIF,
				io.companyFk,
				RIGHT(io.ref, LENGTH(io.ref) - 1) AS invoiceNum,
                IF(ct.CEE = 0, 1, IF(ct.CEE = isUEENotSpain,2,4)) AS TERIDNIF,
				CONCAT(IF(ct.CEE = isUEENotSpain,ct.code,''),c.fi) AS TERNIF,
				c.socialName AS TERNOM,
                ior.serial AS SERIE_RT,
                RIGHT(ior.ref, LENGTH(ior.ref) - 1) AS FACTU_RT,
                ior.issued AS FECHA_RT,
                IF(ior.id,TRUE,FALSE) AS RECTIFICA

		FROM invoiceOut io
			JOIN (	
					SELECT MAX(shipped) as FECHA_OP 
						FROM ticket t
							JOIN invoiceOut io ON io.ref = t.refFk
						WHERE io.id = vInvoice ) opDate
			JOIN invoiceOutSerial ios ON ios.code = io.serial
			JOIN client c ON c.id = io.clientFk
			JOIN country ct ON ct.id = c.countryFk
			LEFT JOIN invoiceCorrection ic ON ic.correctingFk = io.id
            LEFT JOIN invoiceOut ior ON ior.id = ic.correctedFk
			WHERE io.id = vInvoice;

	-- Linea del cliente
	INSERT INTO vn2008.XDiario(
								ASIEN,
								FECHA,
								SUBCTA,              
								EURODEBE,
								CONCEPTO, 
								FECHA_EX,
								FECHA_OP,
								empresa_id
								)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				rs.clientBookingAccount AS SUBCTA,
				rs.totalAmount AS EURODEBE,
				rs.simpleConcept AS CONCEPTO,
				rs.FECHA_EX,
				rs.FECHA_OP,
				rs.companyFk AS empresa_id
			FROM rs;

		-- Lineas de gasto
		INSERT INTO vn2008.XDiario(
									ASIEN,
									FECHA,
									SUBCTA,
									CONTRA,              
									EUROHABER,
									CONCEPTO, 
									FECHA_EX,
									FECHA_OP,
									empresa_id
									)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				ioe.expenceFk AS SUBCTA,
				rs.clientBookingAccount AS CONTRA,
				ioe.amount AS EUROHABER,
				rs.Concept AS CONCEPTO,
				rs.FECHA_EX,
				rs.FECHA_OP,
				rs.companyFk AS empresa_id
			FROM rs
				JOIN invoiceOutExpence ioe
			WHERE ioe.invoiceOutFk = vInvoice;

    SELECT GROUP_CONCAT(`name` SEPARATOR ',') 
            INTO vExpenceConcept 
        FROM expence e
            JOIN invoiceOutExpence ioe ON ioe.expenceFk = e.id
        WHERE ioe.invoiceOutFk = vInvoice;

		-- Lineas de IVA
	INSERT INTO vn2008.XDiario(
								ASIEN,
								FECHA,
								SUBCTA,
								CONTRA,              
								EUROHABER,
								BASEEURO,
								CONCEPTO,
								FACTURA,
								IVA,
								RECEQUIV,
								AUXILIAR,
								SERIE,
								SERIE_RT,
								FACTU_RT,
								RECTIFICA,
								FECHA_RT,
								FECHA_OP,
								FECHA_EX,
								TIPOOPE,
								NFACTICK,
								TERIDNIF,
								TERNIF,
								TERNOM,
								L340,
								TIPOCLAVE,
								TIPOEXENCI,
								TIPONOSUJE,
								TIPOFACT,
								TIPORECTIF,
								empresa_id
								)
		SELECT 
				vBookNumber AS ASIEN,
				rs.FECHA,
				iot.pgcFk AS SUBCTA,
				rs.clientBookingAccount AS CONTRA,
				iot.vat AS EUROHABER,
				iot.taxableBase AS BASEEURO,
				CONCAT(vExpenceConcept,' : ',rs.Concept) AS CONCEPTO,
				rs.invoiceNum AS FACTURA,
                IF(pe2.equFk,0,pgc.rate) AS IVA,
				IF(pe2.equFk,0,pgce.rate) AS RECEQUIV,
				IF(pgc.mod347,'','*') AS AUXILIAR,
				rs.SERIE,
				rs.SERIE_RT,
				rs.FACTU_RT,
				rs.RECTIFICA,
				rs.FECHA_RT,
				rs.FECHA_OP,
				rs.FECHA_EX,
				rs.TIPOOPE,
				rs.NFACTICK,   
				rs.TERIDNIF,
				rs.TERNIF,
				rs.TERNOM,
				pgc.mod340 AS L340,   
				pgc.cplusTrascendency477Fk AS TIPOCLAVE,
				pgc.cplusTaxBreakFk as TIPOEXENCI,
				rs.TIPONOSUJE,
				rs.TIPOFACT,
				rs.TIPORECTIF,
				rs.companyFk AS empresa_id
			FROM rs
				JOIN invoiceOutTax iot 
				JOIN pgc ON pgc.code = iot.pgcFk
				LEFT JOIN pgcEqu pe ON pe.vatFk = iot.pgcFk		-- --------------- Comprueba si la linea es de iva con rec.equiv. asociado
				LEFT JOIN pgc pgce ON pgce.code = pe.equFk 
				LEFT JOIN pgcEqu pe2 ON pe2.equFk = iot.pgcFk  	-- --------------- Comprueba si la linea es de rec.equiv.
			WHERE iot.invoiceOutFk = vInvoice;
            
            UPDATE invoiceOut
				SET booked = CURDATE()
                WHERE id = vInvoice;


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

/* Reasentar facturas
*/


	DECLARE vInvoice INT;
	DECLARE vContador INT DEFAULT 0;

	DECLARE done BOOL DEFAULT FALSE;

	DECLARE rs CURSOR FOR   
   			SELECT io.id
			FROM invoiceOut io
			WHERE RIGHT(ref,7) BETWEEN 1724215  AND 1724224
				AND serial = 'T';

	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoice;

	WHILE NOT done DO

		CALL invoiceOutBooking(vInvoice);
	  
		FETCH rs INTO  vInvoice ;
        
        SET vContador = vContador + 1;
        
        IF vContador MOD 50 = 0 THEN
        
			SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS;
        
		END IF;

	END WHILE;

	CLOSE rs;

	SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutDelete` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutDelete`(vRef VARCHAR(15))
BEGIN

		UPDATE ticket
			SET refFk = NULL
            WHERE refFk = vRef;
            
		DELETE 
			FROM invoiceOut
			WHERE ref = vRef;

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

DECLARE done BOOL DEFAULT FALSE;
DECLARE vInvoice INT;

DECLARE rs CURSOR FOR
		SELECT factura_id
        FROM vn2008.Facturas
		WHERE Importe != BI7 + BI16 + RE4 + RE1 + IVA7 + IVA16
		AND Fecha >= '2017-07-01';

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

OPEN rs;

FETCH rs INTO vInvoice;

SELECT vInvoice, done;

WHILE NOT done DO

		UPDATE invoiceOut io
		JOIN (
			SELECT SUM(amount) AS total
				FROM invoiceOutExpence 
                WHERE invoiceOutFk = vInvoice
			) base
		JOIN (
			SELECT SUM(vat) AS total
				FROM invoiceOutTax 
                WHERE invoiceOutFk = vInvoice
			) vat
	SET io.amount = base.total + vat.total
    WHERE io.id = vInvoice;

	UPDATE vn2008.Facturas 
		SET BI16 = 0,
			BI7 = 0,
            RE1 = 0,
            RE4 = 0,
            IVA7 = 0,
            IVA16 = 0
		WHERE factura_id = vInvoice;

    UPDATE vn2008.Facturas f
            JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id
        SET f.BI16 = iot.taxableBase, f.IVA16 = iot.vat
        WHERE f.factura_id = vInvoice
            AND iot.pgcFk IN ('4770000021' ,'4770000215', '4770000002','4771000000','4770000000','4770000020');

    UPDATE vn2008.Facturas f
            JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id
        SET f.RE4 = iot.vat
        WHERE f.factura_id = vInvoice
            AND iot.pgcFk = '4770000521';
	
    UPDATE vn2008.Facturas f
            JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id
        SET f.BI7 = iot.taxableBase, f.IVA7 = iot.vat
        WHERE f.factura_id = vInvoice
            AND iot.pgcFk IN ('4770000010' ,'4770000101');

    UPDATE vn2008.Facturas f
            JOIN invoiceOutTax iot ON iot.invoiceOutFk = f.factura_id
        SET f.RE1 = iot.vat
        WHERE f.factura_id = vInvoice
            AND iot.pgcFk = '4770000110';

FETCH rs INTO vInvoice;

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 `invoiceOutListByCompany` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutListByCompany`(vCompany INT, vStarted DATE, vEnded DATE)
BEGIN

SELECT 
		c.socialName as RazonSocial,
		c.fi as NIF,
        io.ref as Factura,
        io.serial as Serie,
        io.issued as Fecha,
        io.amount as Importe,
        c.id as Id_Cliente,
        iot.taxableBase as Base,
        pgc.rate as Tipo,
        iot.vat as Cuota,
        pgc.name as Concepto
        
	FROM vn.invoiceOut io
		JOIN vn.invoiceOutTax iot ON iot.invoiceOutFk = io.id
        JOIN vn.client c ON c.id = io.clientFk
        JOIN vn.pgc ON pgc.code = iot.pgcFk
	WHERE io.companyFk = vCompany
		AND io.issued BETWEEN vStarted AND vEnded
		ORDER BY io.ref DESC;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceOutMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutMake`(
	vSerial VARCHAR(255),
	vInvoiceDate DATETIME,
	OUT vNewInvoiceId INT)
BEGIN

/* Creación de facturas emitidas. 
* REQUIERE previamente tabla ticketToInvoice.
*
* @param vSerial, vInvoiceDate, vCompany, vClient
*
* @return vNewInvoiceId
*/
	
    DECLARE vSpainCountryCode INT DEFAULT 1;
	DECLARE vIsAnySaleToInvoice BOOL;
	DECLARE vCountry TINYINT DEFAULT 1;
	DECLARE vTaxArea VARCHAR(15);
	DECLARE vNewRef VARCHAR(255);
	DECLARE vWorker INT DEFAULT vn.getWorker();
    DECLARE vCompany INT;
	DECLARE vClient INT;
	DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1;
    DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6;
	DECLARE vCplusSimplifiedInvoiceTypeFk INT DEFAULT 2;
    DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R';
	DECLARE vSimplifiedSerial VARCHAR(1) DEFAULT 'S';
    
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN 
		ROLLBACK;
		RESIGNAL;
	END;
    
	SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE());

	SELECT t.clientFk, t.companyFk
			INTO vClient, vCompany
		FROM ticketToInvoice tt
			JOIN ticket t ON t.id = tt.id
            LIMIT 1;

	SELECT countryFk 
			INTO vCountry
		FROM supplier
		WHERE id = vCompany;
 
	  	SELECT IF(a.isEqualizated 
					AND c.countryFk = vSpainCountryCode 
                    AND i.taxAreaFk = 'NATIONAL',
				'EQU',
                i.taxAreaFk)
			INTO vTaxArea
		FROM invoiceOutSerial i
			JOIN ticketToInvoice tti 
			JOIN ticket t ON t.id = tti.id
			JOIN address a ON a.id = t.addressFk
            JOIN client c ON c.id = t.clientFk
		WHERE i.code = invoiceSerial(t.clientFk,t.companyFk,'R')
        LIMIT 1;
    
	START TRANSACTION;
	
	-- Elimina tickets sense moviments
/*	UPDATE ticket t 
            JOIN ticketToInvoice ti ON ti.id = t.id 
            LEFT JOIN sale s ON s.ticketFk = ti.id
            LEFT JOIN expedition e ON e.ticketFk = t.id
            LEFT JOIN ticketPackaging tp ON tp.ticketFk = t.id
        SET t.shipped = '2000-02-01 00:00:00'
        WHERE s.ticketFk IS NULL AND e.ticketFk IS NULL AND e.ticketFk IS NULL;
*/
    -- Eliminem de ticketToInvoice els tickets que no han de ser facturats
	DELETE ti.* 
        FROM ticketToInvoice ti 
            JOIN ticket t ON t.id = ti.id
            JOIN client c ON c.id = t.clientFk
        WHERE YEAR(t.shipped) < 2001
			OR c.isTaxDataChecked = FALSE;

    SELECT SUM(quantity * price * (100 - discount)/100)
            INTO vIsAnySaleToInvoice
        FROM sale s 
            JOIN ticketToInvoice t on t.id = s.ticketFk;

	IF vIsAnySaleToInvoice THEN
		
        -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
		   -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
		INSERT INTO invoiceOut
		(
			ref,
			serial,
			issued,
			clientFk,
			dued,
			companyFk,
            cplusInvoiceType477Fk
		)
		SELECT 
				1,
				vSerial,
				vInvoiceDate,
				vClient,
				getDueDate(vInvoiceDate, dueDay),
				vCompany,
                IF(vSerial = vCorrectingSerial, 
					vCplusCorrectingInvoiceTypeFk, 
					IF(vSerial = vSimplifiedSerial,
						vCplusSimplifiedInvoiceTypeFk,
						vCplusStandardInvoiceTypeFk))
            FROM client
            WHERE id = vClient;


		SET vNewInvoiceId = LAST_INSERT_ID();
        
		SELECT ref
				INTO vNewRef 
			FROM invoiceOut
			WHERE id = vNewInvoiceId;

		UPDATE ticket t
    			JOIN ticketToInvoice ti ON ti.id = t.id
        	SET t.refFk = vNewRef;

		DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
        CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
			SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador 
				FROM ticketToInvoice ti
					JOIN vn.ticketState ts ON ti.id = ts.ticket
                    JOIN state s 
				WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id);
	
		INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador)
			SELECT * FROM tmp.updateInter;
            

		INSERT INTO ticketLog (action, userFk,originFk, description) 
			SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef)
				FROM ticketToInvoice ti;

		CALL invoiceExpenceMake(vNewInvoiceId);
		CALL invoiceTaxMake(vNewInvoiceId,vCountry,vTaxArea);
		
		UPDATE invoiceOut io
				JOIN (
					SELECT SUM(amount) AS total
						FROM invoiceOutExpence 
						WHERE invoiceOutFk = vNewInvoiceId
					) base
				JOIN (
					SELECT SUM(vat) AS total
						FROM invoiceOutTax 
						WHERE invoiceOutFk = vNewInvoiceId
					) vat
			SET io.amount = base.total + vat.total
			WHERE io.id = vNewInvoiceId;
		
	END IF;
    
	DROP TEMPORARY TABLE `ticketToInvoice`;
	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 `invoiceOutMakekk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutMakekk`(
	vSerial VARCHAR(255),
	vInvoiceDate DATETIME,
	OUT vNewInvoiceId INT)
BEGIN

/* Creación de facturas emitidas. 
* REQUIERE previamente tabla ticketToInvoice.
*
* @param vSerial, vInvoiceDate, vCompany, vClient
*
* @return vNewInvoiceId
*/
	
    DECLARE vSpainCountryCode INT DEFAULT 1;
	DECLARE vIsAnySaleToInvoice BOOL;
	DECLARE vCountry TINYINT DEFAULT 1;
	DECLARE vTaxArea VARCHAR(15);
	DECLARE vNewRef VARCHAR(255);
	DECLARE vWorker INT DEFAULT vn.getWorker();
    DECLARE vCompany INT;
	DECLARE vClient INT;
	DECLARE vCplusStandardInvoiceTypeFk INT DEFAULT 1;
    DECLARE vCplusCorrectingInvoiceTypeFk INT DEFAULT 6;
    DECLARE vCorrectingSerial VARCHAR(1) DEFAULT 'R';
    
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN 
		ROLLBACK;
		RESIGNAL;
	END;
    
	SET vInvoiceDate = IFNULL(vInvoiceDate,CURDATE());

	SELECT t.clientFk, t.companyFk
			INTO vClient, vCompany
		FROM ticketToInvoice tt
			JOIN ticket t ON t.id = tt.id
            LIMIT 1;

	SELECT countryFk 
			INTO vCountry
		FROM supplier
		WHERE id = vCompany;
 
	  	SELECT IF(a.isEqualizated 
					AND c.countryFk = vSpainCountryCode 
                    AND i.taxAreaFk = 'NATIONAL',
				'EQU',
                i.taxAreaFk)
			INTO vTaxArea
		FROM invoiceOutSerial i
			JOIN ticketToInvoice tti 
			JOIN ticket t ON t.id = tti.id
			JOIN address a ON a.id = t.addressFk
            JOIN client c ON c.id = t.clientFk
		WHERE i.code = invoiceSerial(t.clientFk,t.companyFk,'R')
        LIMIT 1;
    
	START TRANSACTION;
	
	-- Elimina tickets sense moviments
/*	UPDATE ticket t 
            JOIN ticketToInvoice ti ON ti.id = t.id 
            LEFT JOIN sale s ON s.ticketFk = ti.id
            LEFT JOIN expedition e ON e.ticketFk = t.id
            LEFT JOIN ticketPackaging tp ON tp.ticketFk = t.id
        SET t.shipped = '2000-02-01 00:00:00'
        WHERE s.ticketFk IS NULL AND e.ticketFk IS NULL AND e.ticketFk IS NULL;
*/
    -- Eliminem de ticketToInvoice els tickets que no han de ser facturats
	DELETE ti.* 
        FROM ticketToInvoice ti 
            JOIN ticket t ON t.id = ti.id
            JOIN client c ON c.id = t.clientFk
        WHERE YEAR(t.shipped) < 2001
			OR c.isTaxDataChecked = FALSE;

    SELECT SUM(quantity * price * (100 - discount)/100)
            INTO vIsAnySaleToInvoice
        FROM sale s 
            JOIN ticketToInvoice t on t.id = s.ticketFk;

	IF vIsAnySaleToInvoice THEN
		
        -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
		   -- el trigger añade el siguiente Id_Factura correspondiente a la vSerial
		INSERT INTO invoiceOut
		(
			ref,
			serial,
			issued,
			clientFk,
			dued,
			companyFk,
            cplusInvoiceType477Fk
		)
		SELECT 
				1,
				vSerial,
				vInvoiceDate,
				vClient,
				getDueDate(vInvoiceDate, dueDay),
				vCompany,
                IF(vSerial = vCorrectingSerial, vCplusCorrectingInvoiceTypeFk, vCplusStandardInvoiceTypeFk)
            FROM client
            WHERE id = vClient;


		SET vNewInvoiceId = LAST_INSERT_ID();
        
		SELECT ref
				INTO vNewRef 
			FROM invoiceOut
			WHERE id = vNewInvoiceId;

		UPDATE ticket t
    			JOIN ticketToInvoice ti ON ti.id = t.id
        	SET t.refFk = vNewRef;

		DROP TEMPORARY TABLE IF EXISTS tmp.updateInter;
        CREATE TEMPORARY TABLE tmp.updateInter ENGINE = MEMORY
			SELECT s.id,ti.id ticket_id,vWorker Id_Trabajador 
				FROM ticketToInvoice ti
					JOIN vn.ticketState ts ON ti.id = ts.ticket
                    JOIN state s 
				WHERE IFNULL(ts.alertLevel,0) < 3 and s.`code` = vn.getAlert3State(ti.id);
	
		INSERT INTO vncontrol.inter(state_id,Id_Ticket,Id_Trabajador)
			SELECT * FROM tmp.updateInter;
            

		INSERT INTO ticketLog (action, userFk,originFk, description) 
			SELECT 'UPDATE',account.userGetId(),ti.id, CONCAT('Crea factura ',vNewRef)
				FROM ticketToInvoice ti;

		CALL invoiceExpenceMake(vNewInvoiceId);
		CALL invoiceTaxMake(vNewInvoiceId,vCountry,vTaxArea);
		
		UPDATE invoiceOut io
				JOIN (
					SELECT SUM(amount) AS total
						FROM invoiceOutExpence 
						WHERE invoiceOutFk = vNewInvoiceId
					) base
				JOIN (
					SELECT SUM(vat) AS total
						FROM invoiceOutTax 
						WHERE invoiceOutFk = vNewInvoiceId
					) vat
			SET io.amount = base.total + vat.total
			WHERE io.id = vNewInvoiceId;
		
	END IF;
    
	DROP TEMPORARY TABLE `ticketToInvoice`;
	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 `invoiceOutTaxAndExpence` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceOutTaxAndExpence`()
BEGIN

/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
*
* @param vInvoice Numero de factura
*/



	DECLARE vInvoice INT;
    DECLARE vInvoiceRef VARCHAR(15);
    DECLARE vCountry INT;
    DECLARE vTaxArea VARCHAR(15);
	DECLARE vContador INT DEFAULT 0;

	DECLARE done BOOL DEFAULT FALSE;

	DECLARE rs CURSOR FOR   
    SELECT id,ref
   		FROM invoiceOut io
		
				WHERE issued >= '2017-07-01'
                AND companyFk = 1381
			AND io.amount IS NULL
		;


	DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

	OPEN rs;

	FETCH rs INTO vInvoice ,vInvoiceRef;

	WHILE NOT done DO

		SELECT s.countryFk 
				INTO vCountry
			FROM supplier s
				JOIN invoiceOut io ON io.companyFk = s.id
			WHERE io.id = vInvoice;
			
		SELECT IF(c.isEqualizated AND i.taxAreaFk = 'NATIONAL','EQU',i.taxAreaFk)
				INTO vTaxArea
			FROM invoiceOutSerial i
				JOIN invoiceOut io ON io.serial = i.code 
				JOIN client c ON c.id = io.clientFk
			WHERE io.id = vInvoice;
	  
		DROP TEMPORARY TABLE IF EXISTS ticketToInvoice;

		CREATE TEMPORARY TABLE ticketToInvoice
			SELECT id 
				FROM ticket 
				WHERE refFk = vInvoiceRef;

		CALL invoiceExpenceMake(vInvoice);
		CALL invoiceTaxMake(vInvoice,vCountry,vTaxArea);
	  
		FETCH rs INTO  vInvoice ,vInvoiceRef;
        
        SET vContador = vContador + 1;
        
        IF vContador MOD 50 = 0 THEN
        
			SELECT CONCAT(vContador, ' de momento') AS FACTURAS_ASENTADAS;
        
		END IF;

	END WHILE;

	CLOSE rs;

	SELECT CONCAT(vContador, ' total') AS FACTURAS_ASENTADAS;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `invoiceTaxMake` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceTaxMake`(IN vInvoice INT, IN vCountry INT, IN vTaxArea VARCHAR(15))
BEGIN
/* Inserta los registros de iva de la factura emitida
* REQUIERE tabla ticketToInvoice
*
* @param vInvoice Id de la factura
*/
	
    DELETE FROM invoiceOutTax
			WHERE invoiceOutFk = vInvoice;
            
    INSERT INTO invoiceOutTax(
							invoiceOutFk,
							pgcFk,
							taxableBase,
							vat
							)
	SELECT vInvoice,
			bp.pgcFk,
			SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) 
                ) taxableBase,
			SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
                ) * pgc.rate / 100
		FROM ticketToInvoice t
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN itemTaxCountry itc 
				ON itc.itemFk = i.id AND itc.countryFk = vCountry
			JOIN bookingPlanner bp 
				ON bp.countryFk = vCountry 
					AND bp.taxAreaFk = vTaxArea
					AND bp.taxClassFk = itc.taxClassFk
			JOIN pgc ON pgc.code = bp.pgcFk
		GROUP BY pgc.code
        HAVING taxableBase != 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 `invoiceTaxMakekk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `invoiceTaxMakekk`(IN vInvoice INT, IN vCountry INT, IN vTaxArea VARCHAR(15))
BEGIN
/* Inserta los registros de iva de la factura emitida
* REQUIERE tabla ticketToInvoice
*
* @param vInvoice Id de la factura
*/
	
    DELETE FROM invoiceOutTax
			WHERE invoiceOutFk = vInvoice;
            
    INSERT INTO invoiceOutTax(
							invoiceOutFk,
							pgcFk,
							taxableBase,
							vat
							)
	SELECT vInvoice,
			bp.pgcFk,
			SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2) 
                ) taxableBase,
			SUM(ROUND(s.quantity * s.price * (100 - s.discount)/100,2)
                ) * pgc.rate / 100
		FROM ticketToInvoice t
			JOIN sale s ON s.ticketFk = t.id
			JOIN item i ON i.id = s.itemFk
			JOIN itemTaxCountry itc 
				ON itc.itemFk = i.id AND itc.countryFk = vCountry
			JOIN bookingPlanner bp 
				ON bp.countryFk = vCountry 
					AND bp.taxAreaFk = vTaxArea
					AND bp.taxClassFk = itc.taxClassFk
			JOIN pgc ON pgc.code = bp.pgcFk
		GROUP BY pgc.code
        HAVING taxableBase != 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 `itemTagArrangedUpdate` */;
ALTER DATABASE `vn` 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 `itemTagArrangedUpdate`(IN vItem BIGINT)
BEGIN
/**
 * Actualiza la tabla itemTagArranged
 *
 * @param vItem El Id_item de toda la vida. Si es cero, equivale a todos.
 **/
	DELETE 
        FROM itemTagArranged
		WHERE vItem IS NULL 
            OR vItem = itemFk;

	INSERT INTO itemTagArranged(itemFk)
		SELECT id
            FROM item
            WHERE vItem IS NULL 
                OR vItem = id;

	REPLACE itemTagArranged
		SELECT i.id,
			'Medida' as tag1, 
			LEFT(i.size,15) as val1,
			'Color' as tag2,
			LEFT(ink.`name`,15) as val2,
			'Categoria' as tag3,
			LEFT(i.category,15) as val3,
			'Productor' as tag4,
			LEFT(p.`name`,15) as val4,
			'Tallos' as tag5,
			i.stems as  val5,
			'Origen' as tag6,
			o.code as val6,
			i.description
		FROM item i
			LEFT JOIN itemTagged it ON it.itemFk = i.id
			LEFT JOIN ink on ink.id = i.inkFk
			JOIN origin o ON o.id = i.originFk
			LEFT JOIN producer p ON p.id = i.producerFk
		WHERE it.itemFk IS NULL
			AND (vItem IS NULL OR vItem = i.id);
		
	CALL itemTagUpdatePriority(vItem);
	  
	UPDATE itemTagArranged ita 
			JOIN itemTag it ON it.itemFk = ita.itemFk
			JOIN tag t ON t.id = it.tagFk
		SET tag1 = t.name, val1 = it.value
		WHERE it.priority = 1
			AND (vItem IS NULL OR vItem = it.itemFk);

	UPDATE itemTagArranged ita 
			JOIN itemTag it ON it.itemFk = ita.itemFk
			JOIN tag t ON t.id = it.tagFk
		SET tag2 = t.name, val2 = it.value
		WHERE it.priority = 2
			AND (vItem IS NULL OR vItem = it.itemFk);

	UPDATE itemTagArranged ita 
			JOIN itemTag it ON it.itemFk = ita.itemFk
			JOIN tag t ON t.id = it.tagFk
		SET tag3 = t.name, val3 = it.value
		WHERE it.priority = 3
			AND (vItem IS NULL OR vItem = it.itemFk);

	UPDATE itemTagArranged ita 
			JOIN itemTag it ON it.itemFk = ita.itemFk
			JOIN tag t ON t.id = it.tagFk
		SET tag4 = t.name, val4 = it.value
		WHERE it.priority = 4
			AND (vItem IS NULL OR vItem = it.itemFk);

	UPDATE itemTagArranged ita 
			JOIN itemTag it ON it.itemFk = ita.itemFk
			JOIN tag t ON t.id = it.tagFk
		SET tag5 = t.name, val5 = it.value
		WHERE it.priority = 5
			AND (vItem IS NULL OR vItem = it.itemFk);

	UPDATE itemTagArranged ita 
			JOIN itemTag it ON it.itemFk = ita.itemFk
			JOIN tag t ON t.id = it.tagFk
		SET tag6 = t.name, val6 = it.value
		WHERE it.priority = 6
			AND (vItem IS NULL OR vItem = it.itemFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTagUpdatePriority` */;
ALTER DATABASE `vn` 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 `itemTagUpdatePriority`(IN vItem INT)
BEGIN
/*
*	Recalcula las prioridades de articleTag
*
*	@param vItem Id_Article. Si es 0, lo recalcula todo
*/
    
    SET vItem = IFNULL(vItem,0);
    
	SET @p := 0;
    SET @a := 0;

	UPDATE itemTag a
		JOIN (
				SELECT 
						id,
                        @p := IF(itemFk = @a, @p, 0) + 1 as NewPriority,
                        @a := itemFk
					FROM itemTag
					WHERE vItem IS NULL
						OR vItem = itemFk
					ORDER BY itemFk, priority
			 ) sub ON sub.id = a.id
		SET a.priority = NewPriority;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `itemTagUpdatePriority_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 `itemTagUpdatePriority_launcher`()
BEGIN

	CALL vn.itemTagUpdatePriority(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 `logAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `logAdd`(vOriginFk INT, vActionCode VARCHAR(45), vEntity VARCHAR(45), vDescription TEXT)
BEGIN
/**
 * Guarda las acciones realizadas por el usuario
 *
 * @param vOriginFk Id del registro de origen
 * @param vActionCode Código de la acción {insert | delete | update}
 * @param vEntity Nombre que hace referencia a la tabla.
 * @param descripcion Descripción de la acción realizada por el usuario
 */
	DECLARE vTableName VARCHAR(45);
    
	SET vTableName = CONCAT(vEntity, 'Log');
    
	SET @qryLog := CONCAT(
		'INSERT INTO ', vTableName, ' (originFk, userFk, action, description)',
			' VALUES (', vOriginFk, ', ', account.userGetId(), ', "', vActionCode, '", "', vDescription, '")'
    );
    
    PREPARE stmt FROM @qryLog;
    EXECUTE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `logShow` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `logShow`(vOriginFk INT, vEntity VARCHAR(45))
BEGIN
/**
 * Muestra las acciones realizadas por el usuario
 *
 * @param vOriginFk Id del registro de origen
 * @param vEntity Nombre que hace referencia a la tabla.
 */
	DECLARE vTableName VARCHAR(45);
    
    SET vTableName = CONCAT(vEntity, 'Log');
    
    SET @qryLog := CONCAT(
		'SELECT ot.id, ot.originFk, ot.userFk, u.name, ot.action, ot.creationDate, ot.description FROM ', vTableName, ' AS ot',
				' INNER JOIN account.user u ON u.id = ot.userFk',
			' WHERE ot.originFk = ', vOriginFk, ' ORDER BY ot.creationDate DESC'
    );
    
    PREPARE stmt FROM @qryLog;
    EXECUTE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketUnattended` */;
ALTER DATABASE `vn` 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 `mergeTicketUnattended`(IN vMainTicket INT(11), IN hasSameAgency BOOLEAN)
BEGIN

	DECLARE isBilled BOOLEAN;
    DECLARE arrayTickets VARCHAR(255);

	SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket;

	IF NOT isBilled THEN
    
		SELECT GROUP_CONCAT(distinct T.Id_Ticket) INTO arrayTickets
		FROM vn2008.Tickets T LEFT JOIN vn.ticketState ts ON T.Id_Ticket = ts.ticket
        JOIN vn2008.Tickets ticketOriginal ON ticketOriginal.Id_Ticket = vMainTicket
									AND T.empresa_id = ticketOriginal.empresa_id 
									AND T.Id_Consigna = ticketOriginal.Id_Consigna
									AND DATE(T.Fecha) = DATE(ticketOriginal.Fecha)
									AND T.warehouse_id = ticketOriginal.warehouse_id
									AND IF(hasSameAgency <> 0,T.Id_Agencia = ticketOriginal.Id_Agencia,TRUE)
		LEFT JOIN vn.ticketState tsOriginal ON ticketOriginal.Id_Ticket = tsOriginal.ticket
		WHERE ts.alertLevel < 3
		AND T.Factura IS NULL
		AND T.Anotadoencaja = FALSE
        AND T.Id_Ticket <> vMainTicket
        AND ts.alertLevel = tsOriginal.alertLevel;
        
		CALL mergeTicketWithArray(vMainTicket,arrayTickets);
        
	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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `mergeTicketWithArray` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `mergeTicketWithArray`(IN vMainTicket INT(11), IN arrayTickets VARCHAR(50))
BEGIN

	DECLARE isBilled BOOLEAN;
	DECLARE messageLog VARCHAR(50);
	DECLARE company INT;
	DECLARE messageForSplit VARCHAR(255);
	DECLARE vMainSplit INT;
	DECLARE worker INT(3);

	SELECT Factura IS NOT NULL INTO isBilled FROM vn2008.Tickets WHERE Id_Ticket = vMainTicket;

	IF NOT isBilled THEN
	
		SELECT Id_Trabajador INTO worker from vn2008.Trabajadores where user_id = account.userGetId();
		IF worker IS NULL THEN
			SET worker = 20;
		END IF;
        
		DROP TEMPORARY TABLE IF EXISTS vn2008.Tickets_to_fusion;

		-- He usado el util.exec porque da error la variable strId_Tickets puesta dentro del IN()
	   CALL util.exec(sql_printf('
		CREATE TEMPORARY TABLE vn2008.Tickets_to_fusion
		SELECT Id_Ticket, Localizacion
		FROM vn2008.Tickets T
		WHERE Id_Ticket IN (%s);',arrayTickets));

		INSERT INTO vn2008.ticket_observation (Id_Ticket,observation_type_id,text)
			SELECT vMainTicket,observation_type_id,CONCAT(' Ticket ', Id_Ticket, ':' , tco.text, '. ')
			FROM vn2008.Tickets_to_fusion tf
			INNER JOIN vn2008.ticket_observation tco USING(Id_Ticket)
		ON DUPLICATE KEY UPDATE `text` = CONCAT(ticket_observation.`text`,CONCAT(' Ticket ', VALUES(Id_Ticket), ':' , VALUES(`text`), '. '));
				
		UPDATE vn2008.Movimientos M
			JOIN vn2008.Tickets_to_fusion USING(Id_Ticket)
		SET M.Id_Ticket = vMainTicket;
        
		UPDATE vn2008.expeditions M
			JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = M.ticket_id
		SET M.ticket_id = vMainTicket;
        
		UPDATE vn.ticketPackaging tp
			JOIN vn2008.Tickets_to_fusion t ON t.Id_Ticket = tp.ticketFk
		SET tp.ticketFk = vMainTicket;
        
		UPDATE vn2008.Tickets
			SET Bultos = (SELECT COUNT(*) FROM vn2008.expeditions WHERE ticket_id = vMainTicket AND EsBulto)
		WHERE Id_Ticket = vMainTicket;
        
		UPDATE vn2008.Tickets
			JOIN vn2008.Tickets_to_fusion USING(Id_Ticket)
		SET Fecha = TIMESTAMPADD(YEAR,-1 * (YEAR(Fecha)-2000), Fecha);
        
		UPDATE vn2008.Tickets_dits ts
			JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket)
		SET ts.Id_Ticket = vMainTicket;
        
		UPDATE vn2008.Tickets
			SET Localizacion = CONCAT(Tickets.Localizacion,' ',IFNULL((SELECT GROUP_CONCAT(Localizacion SEPARATOR ' ') FROM vn2008.Tickets_to_fusion),''))
		WHERE Id_Ticket = vMainTicket;

		UPDATE vn2008.Splits s
			RIGHT JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket)
			SET s.Id_Ticket = vMainTicket;

		IF (SELECT COUNT(*) FROM vn2008.Splits WHERE Id_Ticket=vMainTicket) > 1 THEN
        
			SELECT Id_Split INTO vMainSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket LIMIT 1;
            
            SELECT group_concat(Notas,',') INTO messageForSplit FROM vn2008.Splits WHERE Id_Ticket = vMainTicket;
			UPDATE vn2008.Splits SET Notas = messageForSplit WHERE Id_Split=vMainSplit;
			UPDATE vn2008.Split_lines sl JOIN vn2008.Splits s USING (Id_Split) SET sl.Id_Split=vMainSplit WHERE Id_Ticket=vMainTicket;
			DELETE FROM vn2008.Splits WHERE Id_Ticket=vMainTicket AND Id_Split<>vMainSplit;
		END IF;

		SELECT GROUP_CONCAT(Id_Ticket SEPARATOR ',') into messageLog FROM vn2008.Tickets_to_fusion;
		CALL vn2008.Ditacio(vMainTicket,'Fusion','T',worker,messageLog,NULL);
           
        DELETE ts FROM vn2008.Tickets_state ts JOIN vn2008.Tickets_to_fusion t USING(Id_Ticket);
		/*
		UPDATE vncontrol.inter M
			JOIN vn2008.Tickets_to_fusion USING(Id_Ticket)
		SET M.Id_Ticket = vMainTicket;
        */
	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 `nestAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `nestAdd`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT, vChild VARCHAR(45))
BEGIN
    DECLARE vSql TEXT;
    
    -- Check parent childs
    SET vSql = sql_printf('
		SELECT COUNT(c.id) INTO @childs
			FROM %t.%t p
				LEFT JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt AND c.id != %v
			WHERE p.id = %v', 
		vScheme, vTable, vScheme, vTable, vParentFk, vParentFk);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    -- Select left from last child
    IF @childs = 0 THEN
		SET vSql = sql_printf('SELECT lft INTO @vLeft FROM %t.%t WHERE id = %v', vScheme, vTable, vParentFk);
		SET @qrySql := vSql;
    ELSE
        SET vSql = sql_printf('
			SELECT c.rgt INTO @vLeft 
				FROM %t.%t p 
					JOIN %t.%t c ON c.lft BETWEEN p.lft AND p.rgt 
				WHERE p.id = %v 
				ORDER BY c.lft 
				DESC LIMIT 1', 
			vScheme, vTable, vScheme, vTable, vParentFk);
		SET @qrySql := vSql;
    END IF;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    -- Update right
	SET vSql = sql_printf('UPDATE %t.%t SET rgt = rgt + 2 WHERE rgt > %v ORDER BY rgt DESC', vScheme, vTable, @vLeft);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    SET vSql = sql_printf('UPDATE %t.%t SET lft = lft + 2 WHERE lft > %v ORDER BY lft DESC', vScheme, vTable, @vLeft);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
    
    -- Escape character
    SET vChild = REPLACE(vChild, "'", "\\'");
    
    -- Add child
    SET vSql = sql_printf('INSERT INTO %t.%t (name, lft, rgt) VALUES (%v, %v, %v)', vScheme, vTable, vChild, @vLeft + 1, @vLeft + 2);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nestLeave` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `nestLeave`(vScheme VARCHAR(45), vTable VARCHAR(45), vParentFk INT)
BEGIN
	DECLARE vSql TEXT;
	
	DROP TEMPORARY TABLE IF EXISTS tmp.tree;
	
    SET vSql = sql_printf('
		CREATE TEMPORARY TABLE tmp.tree ENGINE = MEMORY
		SELECT 
				node.id, 
				node.name,
				node.lft, 
				node.rgt, 
				node.depth, 
				node.sons
			FROM 
				%t.%t AS node,
				%t.%t AS parent
			WHERE 
				node.lft BETWEEN parent.lft AND parent.rgt 
				AND node.depth = parent.depth + 1
				AND parent.id = %v
			GROUP BY node.id
			ORDER BY node.lft',
		vScheme, vTable, vScheme, vTable, vParentFk);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `nestTree` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `nestTree`(
	vSourceSchema VARCHAR(45), 
	vSourceTable VARCHAR(45), 
	vDestinationSchema VARCHAR(45), 
	vDestinationTable VARCHAR(45))
BEGIN
	DECLARE vSql TEXT;
    
	
	SET vSql = sql_printf('DROP TABLE IF EXISTS %t.%t', vDestinationSchema, vDestinationTable);
	SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
	
    SET vSql = sql_printf('
		CREATE TABLE %t.%t
			SELECT 
					node.id, 
                    CONCAT(  REPEAT(" ", 5 * (COUNT(parent.id) - 1)),UCASE(node.name)) name,
					node.lft, 
					node.rgt, 
					COUNT(parent.id) - 1 depth, 
					CAST((node.rgt - node.lft - 1) / 2 as DECIMAL) as sons
				FROM 
					%t.%t AS node,
					%t.%t AS parent
				WHERE node.lft BETWEEN parent.lft AND parent.rgt
				GROUP BY node.id
				ORDER BY node.lft',
		vDestinationSchema, vDestinationTable, vSourceSchema, vSourceTable, vSourceSchema, vSourceTable);
    SET @qrySql := vSql;
    
    PREPARE stmt FROM @qrySql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `noticeSend` */;
ALTER DATABASE `vn` 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 `noticeSend`(vCategoryKey VARCHAR(50), vSender INT, vRecipient INT, vBody TEXT)
BEGIN
    DECLARE vCategoryId INT;
    DECLARE vIsEnabled TINYINT(1);
    
	-- Obtenemos los datos de la categoría
	SELECT c.id, c.isEnabled INTO vCategoryId, vIsEnabled FROM vn.noticeCategory c WHERE keyName = vCategoryKey;
    
    IF vn.noticeHasActive(vCategoryKey, vRecipient) AND vIsEnabled THEN

		INSERT INTO vn.noticeInbox (noticeCategoryFk, senderFk, recipientFk, body) 
			VALUES (vCategoryId, vSender, vRecipient, vBody);

		SELECT vSender, vRecipient;
    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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `observationAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `observationAdd`(vOriginFk INT, vTableCode VARCHAR(45), vDescription TEXT)
BEGIN
/**
 * Guarda las observaciones realizadas por el usuario
 *
 * @param vOriginFk Id del registro de origen
 * @param vTypeCode Código que referencia a la tabla.
 * @param descripcion Texto de la observacion
 */
	DECLARE vTableName VARCHAR(45);
    
	SET vTableName = CONCAT(vTableCode,'Observation');
        
	IF ISNULL(vTableName) THEN
		CALL util.throw('CODE_NOT_FOUND');
	END IF;
    
	SET @qryLog := CONCAT(
		'INSERT INTO ', vTableName, ' (originFk, userFk,  description)',
			' VALUES (', vOriginFk, ', ', account.userGetId(), ', "', vDescription, '")'
    );
    
    PREPARE stmt FROM @qryLog;
    EXECUTE stmt;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `packageInvoicing` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `packageInvoicing`(	
														IN vClient INT,
														IN vDate DATE,
                                                        IN vCompany INT,
                                                        IN vIsAllInvoiceable BOOLEAN,
                                                        OUT vNewTicket INT(11)
													  )
BEGIN

	DECLARE vGraceDays INT;
    DECLARE vDateStart DATE DEFAULT '2017-11-21';
    DECLARE vIsInvoiceable BOOLEAN;
    DECLARE vWarehouse INT DEFAULT 13;
    DECLARE vAgenciaEmbalajes INT DEFAULT 628;
    DECLARE vComponentCost INT DEFAULT 28;
    DECLARE vGraceDate DATE;

	SET vGraceDays = IF(vIsAllInvoiceable,0,30);
	SET vGraceDate = TIMESTAMPADD(DAY, - vGraceDays, vDate);
    
    /* Clientes especiales: 
								3240 MADEFLOR
                                 992 JAVIER FELIU
	*/
                                 
    IF vClient IN (992, 3240) THEN
    
		SET vGraceDays = 365;
    
    END IF;

	/* Fin clientes especiales */


    DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoice;

    CREATE TEMPORARY TABLE tmp.packageToInvoice
        SELECT 	p.itemFk,
				tp.packagingFk,
                IF(tp.quantity < 0 OR t.shipped < vGraceDate, tp.quantity, 0) quantity,
                tp.ticketFk,
                p.price
            FROM ticketPackaging tp
                JOIN package p ON p.id = tp.packagingFk
                JOIN ticket t ON t.id = tp.ticketFk
            WHERE t.shipped BETWEEN vDateStart AND vDate
                AND t.clientFk = vClient;

    DROP TEMPORARY TABLE IF EXISTS tmp.packageToInvoicePositives;

    CREATE TEMPORARY TABLE tmp.packageToInvoicePositives
        SELECT itemFk, sum(quantity) as totalQuantity
            FROM tmp.packageToInvoice
            GROUP BY itemFk
            HAVING totalQuantity > 0;
    
    SELECT GREATEST(COUNT(*),vIsAllInvoiceable)
        INTO vIsInvoiceable
        FROM tmp.packageToInvoicePositives;

    IF vIsInvoiceable THEN

        CALL vn.ticketCreate(vClient, vDate, vWarehouse, vCompany, 0, vAgenciaEmbalajes, 0, vDate, vNewTicket);

        INSERT INTO ticketPackaging(
									ticketFk,
                                    packagingFk,
                                    quantity,
                                    pvp)
            SELECT 	vNewTicket, 
					pti.packagingFk, 
                    - SUM(pti.quantity) AS totalQuantity, 
                    pti.price
                FROM tmp.packageToInvoice pti
					LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk 
				WHERE ptip.itemFK IS NOT NULL 
						OR vIsAllInvoiceable
                GROUP BY packagingFk
                HAVING totalQuantity;

        INSERT INTO sale(
						ticketFk,
						itemFk, 
                        concept, 
                        quantity, 
                        price
                        )
            SELECT 		vNewTicket, 
						pti.itemFk, 
                        i.name as concept, 
                        sum(pti.quantity) as totalQuantity, 
                        pti.price
                FROM tmp.packageToInvoice pti
                    JOIN item i ON i.id = pti.itemFk
						LEFT JOIN tmp.packageToInvoicePositives ptip ON pti.itemFk = ptip.itemFk
                    WHERE ptip.itemFK IS NOT NULL 
						OR vIsAllInvoiceable
                    GROUP BY pti.itemFk
                    HAVING totalQuantity;
                    
		INSERT INTO saleComponent(saleFk, componentFk, value)
			SELECT id, vComponentCost, price
				FROM sale
				WHERE ticketFk = vNewTicket;

    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 `printTrolleyLabel` */;
ALTER DATABASE `vn` 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 `printTrolleyLabel`(vTicket INT, vPrinter INT, vReport INT)
BEGIN
/**
 * Inserta en la cola de impresion una nueva etiqueta de carro, para el sacador
 *
 * @param vTicket Numero del ticket
 * @param vPrinter Numero de impresora
 * @param vReport Numero del informe
 **/
	DECLARE vlabelCount INT DEFAULT 0;
	DECLARE PRIORITY INT DEFAULT 3;
	DECLARE vWorker INT;
	DECLARE vShipmentHour VARCHAR(10);

	SELECT getTicketTrolleyLabelCount(vTicket) INTO vLabelCount;
	SELECT getUser() INTO vWorker;
    SELECT CONCAT(getShipmentHour(vTicket),':00') INTO vShipmentHour;

	INSERT INTO printingQueue(printer
                           ,  priority
                           ,  report
                           ,  `text`
                           ,  worker
                           ,  text2
                           ,  text3)
	VALUES (vPrinter
          , PRIORITY
          , vReport
          , vTicket
          , vWorker
          , vLabelCount
          , vShipmentHour);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `refund` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `refund`(IN vMainTicket INT, OUT vNewTicket INT)
BEGIN

	DECLARE vCustomer MEDIUMINT;
	DECLARE vNewDate DATE;
	DECLARE vWarehouse TINYINT;
	DECLARE vCompany MEDIUMINT;
	DECLARE vAddress MEDIUMINT;
    DECLARE vRefundAgencyMode INT DEFAULT 23;

	SELECT clientFk, TIMESTAMPADD(DAY, 1,shipped), warehouseFk, companyFk, addressFk 
			INTO vCustomer, vNewDate, vWarehouse, vCompany, vAddress
		FROM ticket 
        WHERE id = vMainTicket;

	CALL ticketCreate(vCustomer, vNewDate, vWarehouse, vCompany, vAddress, vRefundAgencyMode,NULL,vNewDate,vNewTicket);

	INSERT INTO vn2008.Movimientos(Id_Ticket, Id_Article, Cantidad, Concepte, Preu, Descuento, PrecioFijado)
		SELECT vNewTicket, Id_Article, - Cantidad, Concepte, Preu, Descuento, TRUE FROM vn2008.Movimientos WHERE Id_Ticket = vMainTicket;
	SELECT vNewTicket;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `routeGateAsign` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `routeGateAsign`(vDevice VARCHAR(30), vRouteFk INT)
BEGIN

	UPDATE routeGate
			SET displayText = NULL,
			routeFk = NULL,
			freeTickets = NULL,
			expeditions = NULL,
			scanned = NULL, 
			flag = NULL,
			pallets = NULL,
			lastScanned = NULL
		WHERE routeFk = vRouteFk;
    
    UPDATE routeGate
			SET routeFk = vRouteFk
        WHERE deviceId = vDevice COLLATE utf8_general_ci;

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

	UPDATE vn.routeGate rg
		LEFT JOIN vn.routesControl rc ON rg.routeFk = rc.routeFk
        LEFT JOIN vn.route r ON r.id = rg.routeFk
        LEFT JOIN vn2008.Agencias a ON a.Id_Agencia = r.agencyModeFk
        LEFT JOIN
				(
                SELECT Id_Ruta, count(*) AS pedidosLibres
				FROM vn2008.Tickets t
					JOIN vn2008.Tickets_state ts ON t.Id_Ticket = ts.Id_Ticket
					JOIN vncontrol.inter i ON i.inter_id = ts.inter_id
					JOIN vn2008.state s ON i.state_id = s.id AND s.alert_level = 0
				WHERE t.Fecha BETWEEN CURDATE() AND util.dayend(CURDATE())
				AND Id_Ruta
				GROUP BY Id_Ruta
                ) t ON t.Id_Ruta = rg.routeFk
        SET rg.scanned = rc.scanned,
			rg.expeditions = rc.expeditions,
            rg.flag = a.flag,
            rg.freeTickets = t.pedidosLibres,
            rg.pallets = rc.pallets,
            rg.lastScanned = rc.lastScanned,
            rg.displayText = IF(rg.routeFk is null, rg.displayText, rg.routeFk MOD 1000);


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `saleSplit` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `saleSplit`(IN vIdMovement BIGINT, IN vQuantity  int)
BEGIN
 	DECLARE vId INT;
    DECLARE vCreated DATE;
    DECLARE vWarehouseId INT;
    DECLARE vCompanyId INT;
    DECLARE vAddressId INT;
    DECLARE vAgencyMode INT;
    DECLARE vNewTicketId BIGINT;
    DECLARE vNewSale BIGINT;
    DECLARE vLanded DATE;
	DECLARE vStarted DATETIME;
	DECLARE vEnded DATETIME;
    DECLARE vCurrentTicket INT;
    


	SELECT clientFk
			 , shipped
			 , warehouseFk
			 , companyFk
			 , addressFk
			 , AgencyModeFk
			 , Landed
			 , t.id
		 
	INTO   vId
			 , vCreated
			 , vWarehouseId
			 , vCompanyId
			 , vAddressId
			 , vAgencyMode
			 , vLanded
			 , vCurrentTicket			
		FROM ticket t
			JOIN sale m on t.id = m.ticketFk
		WHERE m.id = vIdMovement;
        
	-- Busca un ticket existente que coincida con los parametros del nuevo pedido
			
	SET vStarted = TIMESTAMP(vCreated);
	SET vEnded = TIMESTAMP(vCreated, '23:59:59');

	SELECT id INTO vNewTicketId
		FROM ticket t 
        JOIN ticketState ts on t.id = ts.ticketFk
		WHERE vAddressId = t.addressFk
			AND vWarehouseId = t.warehouseFk
			AND vAgencyMode = t.AgencyModeFk
			AND vLanded <=> t.landed
			AND t.shipment BETWEEN vStarted AND vEnded -- uso BETWEEN para aprovechar el indice
			AND t.refFk IS NULL
			AND ts.alertLevel = 0
			AND t.clientFk <> 1118
			AND t.id <> vCurrentTicket
			LIMIT 1;
            
	IF vNewTicketId IS NULL	THEN
		Call vn.ticketCreate(  vId
							 , vCreated
							 , vWarehouseId
							 , vCompanyId
							 , vAddressId
							 , vAgencyMode
							 , NULL
							 , vLanded
							 , vNewTicketId);
                          
		CALL vn2008.bionic_calc_ticket(vNewTicketId);
	ELSE
		UPDATE ticket SET landed = vLanded WHERE id = vNewTicketId;
	END IF;
          
	INSERT INTO vncontrol.inter(Id_Ticket, state_id)
		SELECT vNewTicketId, s.id
			FROM state s
			WHERE s.code = 'FIXING';

	INSERT INTO sale(ticketFk, itemFk, concept, quantity, price, discount)
		SELECT vNewTicketId, itemFk, Concept, vQuantity, price, discount
		FROM sale
		WHERE id = vIdMovement;
	
	SELECT LAST_INSERT_ID() INTO vNewSale;
	
	INSERT INTO saleComponent(saleFk, componentFk, `value`)
		SELECT vNewSale, componentFk, `value`
		FROM saleComponent 
		WHERE saleFk = vIdMovement;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `scanTreeCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `scanTreeCreate`()
BEGIN

	CALL vn.nestTree(	'vn2008', 
						'scan', 
						'vn2008', 
						'scanTree');
                        
	ALTER TABLE vn2008.scanTree 
		ADD COLUMN lastScanned DATETIME NULL,
		ADD COLUMN routeCount INT NULL,
        ADD COLUMN minRoute INT,
        ADD COLUMN maxRoute INT,
        ADD COLUMN scanned INT;

	UPDATE vn2008.scanTree st
		JOIN (
					SELECT 	sl.scan_id, 
							MAX(sl.odbc_date) lastScanned, 
                            COUNT(DISTINCT t.routeFk) routeCount, 
                            MIN(t.routeFk) mod 1000 as minRoute, 
                            MAX(t.routeFk) mod 1000 as maxRoute,
                            COUNT(sl.scan_line_id) as scanned
					FROM vn2008.scan_line sl
						JOIN vn.expedition e ON e.id = sl.`code`
                        JOIN vn.ticket t ON t.id = e.ticketFk
					WHERE t.routeFk
					GROUP BY sl.scan_id
			 ) rs ON rs.scan_id = st.id
		SET st.lastScanned = rs.lastScanned,
			st.routeCount = rs.routeCount,
            st.minRoute = rs.minRoute,
            st.maxRoute = IF(rs.minRoute != rs.maxRoute, rs.maxRoute,NULL),
            st.scanned = rs.scanned;
   

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `solunionRiskRequest` */;
ALTER DATABASE `vn` 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 `solunionRiskRequest`()
BEGIN
	
	DROP TEMPORARY TABLE IF EXISTS tmp.client_list;
    CREATE TEMPORARY TABLE tmp.client_list
    (PRIMARY KEY (Id_Cliente))
		ENGINE = MEMORY
		SELECT * FROM (SELECT cc.client Id_Cliente, ci.grade FROM vn.creditClassification cc 
				JOIN vn.creditInsurance ci ON cc.id = ci.creditClassification
                WHERE dateEnd IS NULL
                ORDER BY ci.creationDate DESC) t1 GROUP BY Id_Cliente;
    
    CALL vn2008.risk_vs_client_list(CURDATE());
    
	SELECT 
		c.Id_Cliente, c.Cliente, c.Credito credito_vn, c.creditInsurance solunion, cast(r.risk as DECIMAL(10,0)) riesgo_vivo,
        cast(c.creditInsurance - r.risk as decimal(10,0)) margen_vivo,
		f.Consumo consumo_anual, c.Vencimiento, ci.grade
	FROM
		vn2008.Clientes c
			JOIN tmp.risk r ON r.Id_Cliente = c.Id_Cliente
			JOIN tmp.client_list ci ON c.Id_Cliente = ci.Id_Cliente
			JOIN bi.facturacion_media_anual f ON c.Id_Cliente = f.Id_Cliente
		GROUP BY Id_cliente;
        
	DROP TEMPORARY TABLE IF EXISTS tmp.risk;
    DROP TEMPORARY TABLE IF EXISTS tmp.client_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyed` */;
ALTER DATABASE `vn` 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 `stockBuyed`(vDate DATE)
BEGIN
	DECLARE vVolume DECIMAL(10,2);
	DECLARE vWarehouse INT DEFAULT 7;
    
	CALL stockTraslation(vDate);

	SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1;
    
	INSERT INTO stockBuyed(user, buyed, `date`)
		SELECT tr.user_id, SUM(0.6 * ( amount / c.packing ) * vn2008.cm3(Id_Compra))/vVolume buyed, vDate
			FROM tmp_item i
				JOIN vn2008.Articles a ON a.Id_Article = i.item_id
				JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id
                JOIN vn2008.reinos r ON r.id = t.reino_id
                JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador
                JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = Id_Article AND ilb.warehouse_id = vWarehouse
                JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id
                WHERE r.display <> 0
			GROUP BY tr.Id_Trabajador
            ON DUPLICATE KEY UPDATE buyed = VALUES(buyed);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorker` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `stockBuyedByWorker`(vDate DATE, vWorker INT)
BEGIN
	
	DECLARE vVolume DECIMAL(10,2);
	DECLARE vWarehouse INT DEFAULT 7;
	CALL stockTraslation(vDate);
    
	SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1;
    
	SELECT c.Id_Entrada, a.Id_Article, a.Article, i.amount Cantidad, (0.6 * ( i.amount / c.packing ) * vn2008.cm3(Id_Compra))/vVolume buyed
		FROM tmp_item i
			JOIN vn2008.Articles a ON a.Id_Article = i.item_id
			JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id
			JOIN vn2008.reinos r ON r.id = t.reino_id
            JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador
			JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse
			JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id
		WHERE r.display <> 0 AND tr.user_id = vWorker;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockBuyedByWorkerTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `stockBuyedByWorkerTest`(vDate DATE, vWorker INT)
BEGIN
	
	DECLARE vVolume DECIMAL(10,2);
	DECLARE vWarehouse INT DEFAULT 7;
	CALL stockTraslationTest(vDate);
    
	SELECT Volumen INTO vVolume FROM vn2008.Cubos WHERE Id_Cubo = 'cc' LIMIT 1;
    
	SELECT c.Id_Entrada, a.Id_Article, a.Article, i.amount Cantidad, (0.6 * ( i.amount / c.packing ) * vn2008.cm3(Id_Compra))/vVolume buyed
		FROM tmp.item i
			JOIN vn2008.Articles a ON a.Id_Article = i.item_id
			JOIN vn2008.Tipos t ON a.tipo_id = t.tipo_id
			JOIN vn2008.reinos r ON r.id = t.reino_id
            JOIN vn2008.Trabajadores tr ON tr.Id_Trabajador = t.Id_Trabajador
			JOIN vn2008.t_item_last_buy ilb ON ilb.item_id = a.Id_Article AND ilb.warehouse_id = vWarehouse
			JOIN vn2008.Compres c ON c.Id_compra = ilb.buy_id
		WHERE r.display <> 0 AND tr.user_id = vWorker;
	DROP TEMPORARY TABLE IF EXISTS 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockTraslation` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `stockTraslation`(vDate DATE)
BEGIN
	/**
	 * Calcula el stock del vWarehouse desde FechaInventario hasta v_date
		sin tener en cuenta las salidas del mismo dia vDate
		para ver el transporte a reservar
	 **/

     DECLARE vWarehouse INT DEFAULT 7;

	DELETE FROM stockBuyed WHERE `date` = vDate;
    
	DROP TEMPORARY TABLE IF EXISTS tmp_item;
	CREATE TEMPORARY TABLE tmp_item
		(UNIQUE INDEX i USING HASH (item_id))
		ENGINE = MEMORY
			SELECT item_id, SUM(amount) amount FROM vn2008.item_entry_in
				WHERE dat = vDate and vDate >= CURDATE() 
					AND warehouse_id = vWarehouse
				GROUP BY item_id HAVING amount != 0;

    CALL `cache`.stock_refresh (FALSE);

	INSERT INTO tmp_item (item_id,amount)
	SELECT item_id,s.amount FROM `cache`.stock s
		WHERE warehouse_id = vWarehouse 
		ON DUPLICATE KEY UPDATE
			amount = tmp_item.amount + VALUES(amount);

    CALL vn2008.item_last_buy_(vWarehouse,vDate);

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `stockTraslationkk`(vDate DATE)
BEGIN
	/**
	 * Calcula el stock del vWarehouse desde FechaInventario hasta v_date
		sin tener en cuenta las salidas del mismo dia vDate
		para ver el transporte a reservar
	 **/

	DECLARE vWarehouse INT DEFAULT 7;

	DELETE FROM stockBuyed WHERE `date` = vDate;
	DROP TEMPORARY TABLE IF EXISTS tmp.item;
    
    CREATE TEMPORARY TABLE tmp.item (
		`item_id` INT,
        `amount` DECIMAL(10, 2) DEFAULT 0.00,
        PRIMARY KEY(item_id)
	) ENGINE = MEMORY;
		
    
    IF vDate >= CURDATE() THEN
		INSERT INTO tmp.item 
			SELECT item_id, SUM(amount) amount 
				FROM vn2008.item_entry_in
				WHERE dat = vDate
					AND warehouse_id = vWarehouse
				GROUP BY item_id HAVING amount != 0;
    END IF;  

    CALL `cache`.stock_refresh (FALSE);

	INSERT INTO tmp.item (item_id,amount)
	SELECT item_id,s.amount FROM `cache`.stock s
		WHERE warehouse_id = vWarehouse 
		ON DUPLICATE KEY UPDATE
			amount = tmp.item.amount + VALUES(amount);

    CALL vn2008.item_last_buy_(vWarehouse,vDate);
    
    select * FROM 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 */ ;
/*!50003 DROP PROCEDURE IF EXISTS `stockTraslationTest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `stockTraslationTest`(vDate DATE)
BEGIN
	/**
	 * Calcula el stock del vWarehouse desde FechaInventario hasta v_date
		sin tener en cuenta las salidas del mismo dia vDate
		para ver el transporte a reservar
	 **/

	DECLARE vWarehouse INT DEFAULT 7;

	DELETE FROM stockBuyed WHERE `date` = vDate;
	DROP TEMPORARY TABLE IF EXISTS tmp.item;
    
    CREATE TEMPORARY TABLE tmp.item (
		`item_id` INT,
        `amount` DECIMAL(10, 2) DEFAULT 0.00,
        PRIMARY KEY(item_id)
	) ENGINE = MEMORY;
		
    
    IF vDate >= CURDATE() THEN
		INSERT INTO tmp.item 
			SELECT item_id, SUM(amount) amount 
				FROM vn2008.item_entry_in
				WHERE dat = vDate
					AND warehouse_id = vWarehouse
				GROUP BY item_id HAVING amount != 0;
    END IF;  

    CALL `cache`.stock_refresh (FALSE);

	INSERT INTO tmp.item (item_id,amount)
	SELECT item_id,s.amount FROM `cache`.stock s
		WHERE warehouse_id = vWarehouse 
		ON DUPLICATE KEY UPDATE
			amount = tmp.item.amount + VALUES(amount);

    CALL vn2008.item_last_buy_(vWarehouse,vDate);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `taxGetRates` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `taxGetRates`(vTaxDate DATE)
    READS SQL DATA
BEGIN
/**
 * Calcula una tabla con el IVA aplicable para la fecha data.
 *
 * @param vTaxDate
 * @treturn tmp.taxGroup
 * @treturn tmp.taxTax
 */
	SET vTaxDate = IFNULL(vTaxDate, CURDATE());

	DROP TEMPORARY TABLE IF EXISTS
		tmp.taxClass,
		tmp.taxType;

	-- Calcula el tipo de IVA para cada clase en cada país.

	CREATE TEMPORARY TABLE tmp.taxClass
		(INDEX (countryFk, taxClassFk))
		ENGINE = MEMORY
		SELECT *
			FROM (
				SELECT t.countryFk, g.taxClassFk, c.type
					FROM vn.taxClassCode g
						JOIN vn.taxCode c ON c.id = g.taxCodeFk
						JOIN vn.taxType t ON t.id = c.taxTypeFk
					WHERE g.effectived <= vTaxDate
					ORDER BY g.effectived DESC
			) t
			GROUP BY countryFk, taxClassFk;

	-- Calcula el impuesto para cada tipo de IVA en cada país.

	CREATE TEMPORARY TABLE tmp.taxType
		(INDEX (countryFk, type))
		ENGINE = MEMORY
		SELECT *
			FROM (
				SELECT t.countryFk, c.type,
						c.rate / 100 rate,
						c.equalizationTax / 100 equalizationTax
					FROM vn.taxCode c
						JOIN vn.taxType t ON t.id = c.taxTypeFk 
					WHERE c.dated <= vTaxDate AND t.isAccrued
					ORDER BY c.dated DESC, c.equalizationTax DESC
			) t
			GROUP BY countryFk, type;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosure` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosure`()
BEGIN
/**
 * Realiza el cierre de todos los 
 * tickets de la table ticketClosure.
 */

	DECLARE vDone BOOL;
	DECLARE vClientFk INT;
    DECLARE vTicketFk INT;
	DECLARE vIsTaxDataChecked BOOL;
    DECLARE vCompanyFk INT;
    DECLARE vShipped DATE;
    DECLARE vPriority INT DEFAULT 1;
    DECLARE vReportDeliveryNote INT DEFAULT 1;
	DECLARE vNewInvoiceId INT;
    DECLARE vIsUeeMember BOOL;

	DECLARE cur CURSOR FOR
		SELECT ticketFk FROM tmp.ticketClosure;
        
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN 
        RESIGNAL;
	END;
        
	INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: START');
    
	OPEN cur;
    
    proc: LOOP
		SET vDone = FALSE;
        
        FETCH cur INTO vTicketFk;

        IF vDone THEN
			LEAVE proc;
		END IF;

		-- ticketClosure start
        SELECT
				c.id,
				c.isTaxDataChecked,
				t.companyFk,
                t.shipped,
                co.isUeeMember
			INTO vClientFk,
				vIsTaxDataChecked,
				vCompanyFk, 
                vShipped,
                vIsUeeMember
			FROM ticket t 
				JOIN `client` c ON c.id = t.clientFk
                JOIN province p ON p.id = c.provinceFk
                JOIN country co ON co.id = p.countryFk
			WHERE t.id = vTicketFk;

        -- Fusión de ticket
        -- CALL mergeTicketUnattended(vTicketFk, TRUE); JGF 2017/12/04

		INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
			(SELECT vTicketFk, p.id, COUNT(*)
				FROM expedition e 
					JOIN package p ON p.itemFk = e.itemFk
				WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable
				GROUP BY p.itemFk);

		-- No retornables o no catalogados
		INSERT INTO movement (item, ticket, concept, amount, price, priceFixed) 
			(SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 
				FROM expedition e 
					JOIN item i ON i.id = e.itemFk 
					LEFT JOIN package p ON p.itemFk = i.id
				WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
					AND getSpecialPrice(e.itemFk, vClientFk) > 0
				GROUP BY e.itemFk);
			
        IF(vIsUeeMember = FALSE) THEN

			-- Facturacion rapida
			CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', 20);
            -- Facturar si está contabilizado
            IF vIsTaxDataChecked THEN
            
				IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN
					CALL invoiceMakeByClient(
						vClientFk, 
                        (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), 
                        vShipped, 
                        vCompanyFk, 
                        vNewInvoiceId);
                ELSE
					CALL invoiceMakeByTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), vNewInvoiceId);
                END IF;

            END IF;
		ELSE
			-- Albaran_print
			CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20);
            INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); 
        END IF;
        
		-- ticketClosure end
	END LOOP;
	
	CLOSE cur;
    
    INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: 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 `ticketClosureAgencyList` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosureAgencyList`(vWarehouseFk INT, vDateTo DATE)
BEGIN
/**
 * Inserta los tickets de todos los almacenes en la tabla temporal
 * para ser cerrados.
 *
 * @param vWarehouseFk Id del almacén
 * @param vDate Fecha del cierre
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY (
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			INNER JOIN tmp.ticketClosureAgencyList al ON al.agencyModeFk = t.agencyModeFk
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		WHERE 
			ts.alertLevel = 2 
			AND t.warehouseFk = vWarehouseFk
			AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
		
	DROP TEMPORARY TABLE tmp.ticketClosureAgencyList;
        
	CALL ticketClosure();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureAgencyListAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosureAgencyListAdd`(vAgencyModeFk INT)
BEGIN
/**
 * Prepara un listado de agencias sobre los que se realizará el cierre. 
 * Es necesario llamar al procedimiento por cada agencia.
 *
 * @param vAgencyModeFk Id almacén
 */
	CREATE TEMPORARY TABLE IF NOT EXISTS tmp.ticketClosureAgencyList (
		`agencyModeFk` INT,
	PRIMARY KEY(agencyModeFk)) ENGINE = MEMORY;

	INSERT INTO tmp.ticketClosureAgencyList(agencyModeFk) VALUES(vAgencyModeFk);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosurekk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosurekk`()
BEGIN
/**
 * Realiza el cierre de todos los 
 * tickets de la table ticketClosure.
 */

	DECLARE vDone BOOL;
	DECLARE vClientFk INT;
    DECLARE vCredit INT;
    DECLARE vPayMethod INT;
    DECLARE vTicketFk INT;
    DECLARE vIsToBeMailed BOOL;
	DECLARE vIsTaxDataChecked BOOL;
    DECLARE vCompanyFk INT;
    DECLARE vDeliveryMethod INT;
    DECLARE vAgencyFk INT;
    DECLARE vAgencyModeFk INT;
    DECLARE vWarehouseFk INT;
    DECLARE vShipped DATE;
    DECLARE vPayMethodCard INT DEFAULT 5;
    DECLARE vPriority INT DEFAULT 1;
    DECLARE vReportDeliveryNote INT DEFAULT 1;
	DECLARE vNewInvoiceId INT;
    DECLARE vHasToInvoice BOOL;

	DECLARE cur CURSOR FOR
		SELECT ticketFk FROM tmp.ticketClosure;
        
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN 
        RESIGNAL;
	END;
        
	INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: START');
    
	OPEN cur;
    
    proc: LOOP
		SET vDone = FALSE;
        
        FETCH cur INTO vTicketFk;

        IF vDone THEN
			LEAVE proc;
		END IF;

		-- ticketClosure start
        SELECT
				c.id,
				c.credit,
				c.paymentMethodFk,
				c.isToBeMailed,
				c.isTaxDataChecked,
				t.companyFk,
				IFNULL(aw.agencyType, a.deliveryMethod) AS deliveryMethod,
				a.id AS agencyFk,
				t.agencyModeFk,
				t.warehouseFk,
                t.shipped,
                c.hasToInvoice
			INTO vClientFk, 
				vCredit,
				vPayMethod,
				vIsToBeMailed, 
				vIsTaxDataChecked,
				vCompanyFk, 
				vDeliveryMethod, 
				vAgencyFk, 
				vAgencyModeFk, 
				vWarehouseFk,
                vShipped,
                vHasToInvoice
			FROM ticket t 
				INNER JOIN `client` c ON c.id = t.clientFk
				LEFT JOIN agencyMode a ON a.id = t.agencyModeFk
				LEFT JOIN agencyWarehouse aw ON a.id = aw.agencyFk AND t.warehouseFk = aw.warehouseFk
			WHERE t.id = vTicketFk;

        -- Fusión de ticket
        CALL mergeTicketUnattended(vTicketFk, TRUE);

		INSERT INTO ticketPackaging (ticketFk, packagingFk, quantity)
			(SELECT vTicketFk, p.id, COUNT(*)
				FROM expedition e 
					JOIN package p ON p.itemFk = e.itemFk
				WHERE e.ticketFk = vTicketFk AND p.isPackageReturnable
				GROUP BY p.itemFk);

		-- No retornables o no catalogados
		INSERT INTO movement (item, ticket, concept, amount, price, priceFixed) 
			(SELECT e.itemFk, vTicketFk, i.name, COUNT(*) AS amount, getSpecialPrice(e.itemFk, vClientFk), 1 
				FROM expedition e 
					JOIN item i ON i.id = e.itemFk 
					LEFT JOIN package p ON p.itemFk = i.id
				WHERE e.ticketFk = vTicketFk AND IFNULL(p.isPackageReturnable, 0) = 0
				GROUP BY e.itemFk);
			
		-- Albaran_print
		CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20);
		INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); 

        IF((vCredit <= 1 OR vPayMethod = vPayMethodCard) AND vHasToInvoice <> FALSE) THEN

			-- Facturacion rapida
			CALL ticketTrackingAdd(vTicketFk, 'DELIVERED', 20);
            -- Facturar si está contabilizado
            IF vIsTaxDataChecked THEN
            
				IF (SELECT clientTaxArea(vClientFk, vCompanyFk)) = 'NATIONAL' THEN
					CALL invoiceMakeByClient(
						vClientFk, 
                        (SELECT invoiceSerial(vClientFk, vCompanyFk, 'M')), 
                        vShipped, 
                        vCompanyFk, 
                        vNewInvoiceId);
                ELSE
					CALL invoiceMakeByTicket(vTicketFk, (SELECT invoiceSerial(vClientFk, vCompanyFk, 'R')), vNewInvoiceId);
                END IF;

            END IF;
		ELSE
			-- Albaran_print
			CALL ticketTrackingAdd(vTicketFk, (SELECT vn.getAlert3State(vTicketFk)), 20);
            INSERT INTO printServerQueue(priorityFk, reportFk, param1) VALUES(vPriority, vReportDeliveryNote, vTicketFk); 
        END IF;
        
		-- ticketClosure end
	END LOOP;
	
	CLOSE cur;
    
    INSERT INTO dailyTaskLog(state) VALUES('ticketClosure: 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 `ticketClosureMultiWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosureMultiWarehouse`(vDateTo DATE)
BEGIN
/**
 * Inserta los tickets de todos los almacenes en la tabla temporal
 * para ser cerrados.
 *
 * @param vDate Fecha del cierre
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY (
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			INNER JOIN warehouse w ON w.id = t.warehouseFk AND hasComission
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		WHERE 
			ts.alertLevel = 2 
			AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticketClosure();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureRoute` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosureRoute`(vWarehouseFk INT, vRouteFk INT, vDateTo DATE)
BEGIN
/**
 * Inserta los tickets de la ruta en la tabla temporal
 * para ser cerrados.
 *
 * @param vWarehouseFk Almacén a cerrar
 * @param vRouteFk Ruta a cerrar
 * @param vDate Fecha del cierre
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY (
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		WHERE 
			ts.alertLevel = 2 
			AND t.warehouseFk = vWarehouseFk
			AND t.routeFk = vRouteFk
			AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticketClosure();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureTicket` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosureTicket`(vTicketFk INT)
BEGIN

/**
 * Inserta el ticket en la tabla temporal
 * para ser cerrado.
 *
 * @param vTicketFk Id del ticket
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE tmp.ticketClosure ENGINE = MEMORY (
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		WHERE 
			ts.alertLevel = 2 
            AND t.id = vTicketFk
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticketClosure();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketClosureWarehouse` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketClosureWarehouse`(vWarehouseFk INT, vDateTo DATE)
BEGIN
/**
 * Inserta los tickets del almacen en la tabla temporal
 * para ser cerrados.
 *
 * @param vWarehouseFk Almacén a cerrar
 * @param vDate Fecha del cierre
 */

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketClosure;

	CREATE TEMPORARY TABLE ticketClosure ENGINE = MEMORY(
		SELECT 
			t.id AS ticketFk
		FROM expedition e
			INNER JOIN ticket t ON t.id = e.ticketFk
			LEFT JOIN ticketState ts ON ts.ticketFk = t.id
		WHERE 
			ts.alertLevel = 2 
			AND t.warehouseFk = vWarehouseFk
			AND DATE(t.shipped) BETWEEN DATE_ADD(vDateTo, INTERVAL -2 DAY) AND vDateTo
			AND t.refFk IS NULL
		GROUP BY e.ticketFk);
        
	CALL ticketClosure();
    
    DROP TEMPORARY TABLE tmp.ticketClosure;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketCreate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketCreate`(
	 vClientId INT
	,vShipped DATE
	,vWarehouseId INT
	,vCompanyFk INT
	,vAddressFk INT
	,vAgencyType INT
	,vRouteFk INT
	,vlanded DATE
	,OUT vNewTicket INT)
BEGIN
	DECLARE vClientOrnamentales INT DEFAULT 5270;
	DECLARE vCompanyOrn INT DEFAULT 1381;
	DECLARE vProvinceName VARCHAR(255);

	SELECT p.name INTO vProvinceName
		FROM vn.client c
		JOIN province p ON p.id = c.provinceFk
		WHERE c.id = vClientId;

	IF vProvinceName IN ('SANTA CRUZ DE TENERIFE', 'LAS PALMAS DE GRAN CANARIA')
		AND vClientId <> vClientOrnamentales
	THEN
		SET vCompanyFk = vCompanyOrn;
	END IF;

	INSERT INTO vn2008.Tickets (
			Id_Cliente,
			Fecha,
			Id_Consigna,
			Id_Agencia,
			Alias,
			warehouse_id,
			Id_Ruta,
			empresa_id,
			landing
		) 
		SELECT
				vClientId,
				vShipped,
				a.id,
				IF(vAgencyType,vAgencyType,a.agencyFk),
				a.nickname,
				vWarehouseId,
				IF(vRouteFk,vRouteFk,NULL),
				vCompanyFk,
				vlanded
			FROM address a
			JOIN agencyMode am ON am.id = a.agencyFk
			WHERE IF(vAddressFk, a.id = vAddressFk, a.isDefaultAddress != FALSE)
				AND a.clientFk = vClientId
			LIMIT 1;

	SET vNewTicket = LAST_INSERT_ID();

	INSERT INTO ticketObservation(ticketFk, observationTypeFk, description)
		SELECT vNewTicket,ao.observationTypeFk, ao.description
			FROM addressObservation ao
				JOIN address a ON a.id = ao.addressFk
			WHERE a.clientFk = vClientId AND a.isDefaultAddress != FALSE;

	CALL logAdd(vNewTicket, 'insert', 'ticket', CONCAT('CREA EL TICKET', ' ', vNewTicket));

	IF (SELECT isCreatedAsServed FROM vn.client WHERE id = vClientId ) <> FALSE
	THEN
		INSERT INTO vncontrol.inter(state_id, Id_Ticket, Id_Trabajador)
			SELECT id, vNewTicket, getWorker()
				FROM state 
				WHERE `code` = 'DELIVERED';
	END IF;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketGetTax` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketGetTax`(vBillingDate DATE)
    READS SQL DATA
BEGIN
/**
 * Calcula la base imponible, el IVA y el recargo de equivalencia para
 * un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @param vBillingDate Fecha de facturación
 * @treturn tmp.ticketTax Impuesto desglosado para cada ticket
 */
	CALL vn.taxGetRates (vBillingDate);

	-- Calcula el IVA y el recargo desglosado para cada ticket.

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
	CREATE TEMPORARY TABLE tmp.ticketTax
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT t.ticketFk, 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 i.ticketFk, g.countryFk, g.type
						,SUM(CAST(m.quantity * m.price * (100 - m.discount) / 100 AS DECIMAL(10,2))) AS taxBase
						,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax
						,c.isEqualizated != FALSE AS hasEqualizationTax
					FROM tmp.ticket i
						JOIN vn.ticket t ON t.id = i.ticketFk
						JOIN vn.sale m ON m.ticketFk = t.id
						JOIN vn.item a ON a.id = m.itemFk
						JOIN vn.client c ON c.id = t.clientFk
						JOIN vn.supplier p ON p.id = t.companyFk
						JOIN tmp.taxClass g
							ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk
					GROUP BY i.ticketFk, 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 `ticketGetTaxkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketGetTaxkk`(vBillingDate DATE)
    READS SQL DATA
BEGIN
/**
 * Calcula la base imponible, el IVA y el recargo de equivalencia para
 * un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @param vBillingDate Fecha de facturación
 * @treturn tmp.ticketTax Impuesto desglosado para cada ticket
 */
	CALL vn.taxGetRates (vBillingDate);

	-- Calcula el IVA y el recargo desglosado para cada ticket.

	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTax;
	CREATE TEMPORARY TABLE tmp.ticketTax
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT t.ticketFk, 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 i.ticketFk, g.countryFk, g.type
						,SUM(CAST(m.quantity * m.price * (100 - m.discount) / 100 AS DECIMAL(10,2))) AS taxBase
						,NOT(c.isVies AND p.countryFk <> c.countryFk) hasTax
						,c.isEqualizated != FALSE AS hasEqualizationTax
					FROM tmp.ticket i
						JOIN vn.ticket t ON t.id = i.ticketFk
						JOIN vn.sale m ON m.ticketFk = t.id
						JOIN vn.item a ON a.id = m.itemFk
						JOIN vn.client c ON c.id = t.clientFk
						JOIN vn.supplier p ON p.id = t.companyFk
						JOIN tmp.taxClass g
							ON g.countryFk = p.countryFk AND g.taxClassFk = a.taxClassFk
					GROUP BY i.ticketFk, 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 `ticketGetTotal` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketGetTotal`()
    READS SQL DATA
BEGIN
/**
 * Calcula el total con IVA para un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @treturn tmp.ticketTotal Total para cada ticket
 */
	CALL ticketGetTax (NULL);
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
	CREATE TEMPORARY TABLE tmp.ticketTotal
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT ticketFk, SUM(taxBase + tax + equalizationTax) AS total
			FROM tmp.ticketTax GROUP BY ticketFk;
	
	DROP TEMPORARY TABLE 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 `ticketGetTotalkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketGetTotalkk`()
    READS SQL DATA
BEGIN
/**
 * Calcula el total con IVA para un conjunto de tickets.
 *
 * @table tmp.ticket(ticketFk) Identificadores de los tickets a calcular
 * @treturn tmp.ticketTotal Total para cada ticket
 */
	CALL ticketGetTax (NULL);
	
	DROP TEMPORARY TABLE IF EXISTS tmp.ticketTotal;
	CREATE TEMPORARY TABLE tmp.ticketTotal
		(INDEX (ticketFk))
		ENGINE = MEMORY
		SELECT ticketFk, SUM(taxBase + tax + equalizationTax) AS total
			FROM tmp.ticketTax GROUP BY ticketFk;
	
	DROP TEMPORARY TABLE 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 `ticketToInvoiceByAddress` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketToInvoiceByAddress`(
                                                            vStarted DATE,
															vEnded DATETIME,
															vAddress INT,
															vCompany INT
															)
BEGIN

	SET vEnded = util.dayEnd(vEnded);

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

    CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id
            FROM vn.ticket
            WHERE addressFk = vAddress
                AND companyFk = vCompany
                AND shipped BETWEEN vStarted AND vEnded
                AND refFk IS 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 `ticketToInvoiceByClient` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketToInvoiceByClient`(
                                                            vStarted DATE,
															vEnded DATETIME,
															vClient INT,
															vCompany INT
															)
BEGIN

	SET vEnded = util.dayEnd(vEnded);

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

    CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id
            FROM vn.ticket
            WHERE clientFk = vClient
                AND companyFk = vCompany
                AND shipped BETWEEN vStarted AND vEnded
                AND refFk IS 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 `ticketToInvoiceByDate` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketToInvoiceByDate`(
                                                            vStarted DATE,
															vEnded DATETIME,
															vClient INT,
															vCompany INT
															)
BEGIN

	SET vEnded = util.dayEnd(vEnded);

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

    CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id
            FROM vn.ticket
            WHERE clientFk = vClient
                AND companyFk = vCompany
                AND shipped BETWEEN vStarted AND vEnded
                AND refFk IS 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 `ticketToInvoiceByRef` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketToInvoiceByRef`(IN vInvoiceRef VARCHAR(15))
BEGIN

/* Para tickets ya facturados, vuelve a repetir el proceso de facturación.
*
* @param vInvoiceRef Factura
*/

	DECLARE vInvoice INT;
    DECLARE vCountry INT;
    DECLARE vTaxArea VARCHAR(15);
    DECLARE vSpainCountryCode INT DEFAULT 1;
    
	SELECT id 
		    INTO vInvoice 
		FROM vn.invoiceOut 
        WHERE ref =  vInvoiceRef;
        
	SELECT s.countryFk 
			INTO vCountry
		FROM vn.supplier s
			JOIN vn.invoiceOut io ON io.companyFk = s.id
		WHERE io.id = vInvoice;
        
	SELECT IF(
				c.isEqualizated 
					AND c.countryFk = vSpainCountryCode 
					AND i.taxAreaFk = 'NATIONAL',
				'EQU',
                i.taxAreaFk
			)
			INTO vTaxArea
		FROM vn.invoiceOutSerial i
			JOIN vn.invoiceOut io ON io.serial = i.code 
			JOIN vn.client c ON c.id = io.clientFk
        WHERE io.id = vInvoice;
  
	DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

	CREATE TEMPORARY TABLE vn.ticketToInvoice
        SELECT id 
            FROM vn.ticket 
            WHERE refFk = vInvoiceRef;

END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `ticketToInvoiceByTicketkk` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketToInvoiceByTicketkk`(vTicket INT)
BEGIN

    DROP TEMPORARY TABLE IF EXISTS vn.ticketToInvoice;

        CREATE TEMPORARY TABLE vn.ticketToInvoice
            SELECT id
                FROM vn.ticket
                WHERE id = vTicket
                    AND refFk IS 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 `ticketTrackingAdd` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `ticketTrackingAdd`(vTicketFk INT, vState VARCHAR(25) CHARSET UTF8, vWorkerFk INT)
BEGIN
/**
 * Inserta un registro de cambios en un ticket.
 * @param vTicketFk Id del ticket
 * @param vState Código del estado
 * @param vWorkerFk Id del trabajador
 */
	INSERT INTO ticketTracking (stateFk, ticketFk, workerFk)
		SELECT s.id, vTicketFk, vWorkerFk FROM state s WHERE s.code = vState;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerCreateExternal` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `workerCreateExternal`(
    vFirstName VARCHAR(50),
    vSurname1 VARCHAR(50),
    vSurname2 VARCHAR(50),
    vUser VARCHAR(20),
    vPassword VARCHAR(50),
    vWorkerCode VARCHAR(3),
    vRole INT(2)
    )
BEGIN

	DECLARE vUserId INT;
    DECLARE vWorkerPako INT DEFAULT 2;
    DECLARE vSurnames VARCHAR(100);

	INSERT INTO account.user(name,password,role)
		SELECT vUser,MD5(vPassword),vRole;
            
	SET vUserId = LAST_INSERT_ID();
    /* 
		INSERT INTO vn.worker(firstName,name,bossFk,workerCode,user_id)
			SELECT vFirstName,CONCAT(vSurname1,' ',vSurname2),2,vWorkerCode,vUser;
	*/
    
    IF vSurname2 IS NULL THEN
		SET vSurnames = vSurname1;
    ELSE
		SET vSurnames = CONCAT(vSurname1, ' ', vSurname2);
    END IF;
	
	INSERT INTO vn2008.Trabajadores(Nombre, Apellidos, boss, CodigoTrabajador, user_id)
		SELECT vFirstName, vSurnames, vWorkerPako, vWorkerCode, vUserId;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workerDisable` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 SET collation_connection  = utf8_general_ci */ ;
/*!50003 SET @saved_sql_mode       = @@sql_mode */ ;
/*!50003 SET sql_mode              = 'NO_ENGINE_SUBSTITUTION' */ ;
DELIMITER ;;
CREATE DEFINER=`root`@`localhost` PROCEDURE `workerDisable`(vUserId int)
BEGIN

	DELETE FROM account.account
		WHERE id = vUserId;

   	UPDATE account.user 
		SET role = 2
		WHERE id = vUserId;		

	UPDATE `client` 
		SET credit = 0
		WHERE id = vUserId;
    
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `workingHours` */;
ALTER DATABASE `vn` 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 `workingHours`(username varchar(255), logon boolean)
BEGIN
	DECLARE userid int(11);
        
  	SELECT vn.getUserId(username) INTO userid;
    SELECT username, userid;
		IF userid IS NOT NULL THEN     
			IF (logon) THEN
				CALL vn.workingHoursTimeIn(userid);
			ELSE
				CALL vn.workingHoursTimeOut(userid);
			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 */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeIn` */;
ALTER DATABASE `vn` 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 `workingHoursTimeIn`(vUserId INT(11))
BEGIN
	INSERT INTO vn.workingHours (timeIn, userId)
		VALUES (NOW(),vUserId);
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
ALTER DATABASE `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `workingHoursTimeOut` */;
ALTER DATABASE `vn` 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 `workingHoursTimeOut`(vUserId INT(11))
BEGIN
	UPDATE vn.workingHours
		SET timeOut = NOW()
		WHERE userId = vUserId
			AND DATE(timeIn) = 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 `vn` CHARACTER SET utf8 COLLATE utf8_unicode_ci ;
/*!50003 DROP PROCEDURE IF EXISTS `zoneNest` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `zoneNest`()
BEGIN

	DECLARE vDone BOOL;
    DECLARE vParent INT DEFAULT 1;
    DECLARE vGeoFk INT;
    DECLARE vChildFk INT;
    DECLARE vChildName VARCHAR(45);
			
	DECLARE townCur CURSOR FOR
		SELECT p.geoFk, t.id, t.`name`
			FROM town t 
				JOIN province p ON p.id = t.provinceFk
			WHERE t.id BETWEEN 30001 AND 40000;
			
	DECLARE CONTINUE HANDLER FOR NOT FOUND SET vDone = TRUE;
	
	-- > Town cursor start
	OPEN townCur;
	
	townLoop: LOOP
		SET vDone = FALSE;
        
		FETCH townCur INTO vParent, vChildFk, vChildName;
		
		IF vDone THEN
			LEAVE townLoop;
		END IF;
		
		CALL nestAdd('vn', 'zoneNest', vParent, vChildName);
		
		-- Update town geoFk
        SET vGeoFk = LAST_INSERT_ID();
        UPDATE town SET geoFk = vGeoFk WHERE id = vChildFk;
	END LOOP;
	CLOSE townCur;
	-- < Town cursor 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 */ ;

--
-- 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=177055 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
/*!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` 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 ;

--
-- 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 */;

--
-- 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 ;

--
-- 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 */;

--
-- 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 ;

--
-- 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 */;

--
-- 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 `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`;

--
-- 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 */;

--
-- 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` (
  `clientFk` int(11) NOT NULL,
  `orderFk` int(10) unsigned NOT NULL,
  PRIMARY KEY (`orderFk`,`clientFk`),
  UNIQUE KEY `customer_id` (`clientFk`),
  CONSTRAINT `basketOrder_ibfk_1` FOREIGN KEY (`orderFk`, `clientFk`) 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 (`clientFk`) 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 `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 */;

--
-- 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 */;

--
-- 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,
  `isActive` 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=37 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 */;

--
-- 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=12991 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=1232950 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,
  `guestMethod` varchar(45) CHARACTER SET utf8 NOT NULL,
  `guestAgencyFk` int(11) NOT NULL,
  `reserveTime` time NOT NULL,
  `defaultCompanyFk` smallint(6) unsigned DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `employeeFk` (`employeeFk`),
  KEY `guestAgencyFk` (`guestAgencyFk`),
  KEY `defaultCompanyFk` (`defaultCompanyFk`),
  KEY `guestMethod` (`guestMethod`),
  CONSTRAINT `orderConfig_ibfk_1` FOREIGN KEY (`employeeFk`) REFERENCES `vn2008`.`Trabajadores` (`Id_Trabajador`) ON UPDATE CASCADE,
  CONSTRAINT `orderConfig_ibfk_2` FOREIGN KEY (`defaultCompanyFk`) REFERENCES `vn2008`.`empresa` (`id`) ON UPDATE CASCADE,
  CONSTRAINT `orderConfig_ibfk_3` FOREIGN KEY (`guestAgencyFk`) REFERENCES `vn2008`.`Agencias` (`Id_Agencia`) ON UPDATE CASCADE
) 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=7678042 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 */;

--
-- 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 */;

--
-- 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=185356 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 */;

--
-- 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=1138614 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=2417840 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=1657058 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=2354048 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 `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 `myClientGetDebt` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `myClientGetDebt`(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 `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 = 'PICKUP' AND vAddress IS NULL
	THEN
		SELECT defaultAddressFk INTO vAddress
			FROM myClient;
	END IF;
        
	SET vOrder = basketGetId();

	IF vOrder IS NULL
	THEN
		SELECT companyFk INTO vCompany
			FROM vn.clientDefaultCompany
			WHERE ClientFk = account.userGetId()
				AND CURDATE() BETWEEN started AND finished
			LIMIT 1;
            
		IF vCompany IS NULL
		THEN
			SELECT defaultCompanyFk INTO vCompany
				FROM orderConfig;
        END IF;

		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 = vCompany;

		SET vOrder = LAST_INSERT_ID();
        
        INSERT INTO basketOrder SET
			clientFk = account.userGetId(),
            orderFk = 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 guestMethod, guestAgencyFk
		INTO vMethod, vAgency
        FROM orderConfig
        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
 */
	DECLARE vTaxBase DECIMAL(10,2);
	DECLARE vTax DECIMAL(10,2);

	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 SUM(taxBase), SUM(tax + equalizationTax)
		INTO vTaxBase, vTax
		FROM tmp.ticketTax;

	SELECT t.id, t.landed, t.shipped, t.refFk, ag.description agency, 
			a.street, a.postalCode, a.city, a.nickname, p.name province,
			vTaxBase taxBase, vTaxBase + vTax AS total
		FROM tmp.ticket 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
			LEFT 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 `myTicketGetPackages` */;
/*!50003 SET @saved_cs_client      = @@character_set_client */ ;
/*!50003 SET @saved_cs_results     = @@character_set_results */ ;
/*!50003 SET @saved_col_connection = @@collation_connection */ ;
/*!50003 SET character_set_client  = utf8 */ ;
/*!50003 SET character_set_results = utf8 */ ;
/*!50003 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 `myTicketGetPackages`(vTicket INT)
BEGIN
/**
 * Returns a current user ticket packages.
 *
 * @param vTicket The ticket identifier
 * @select The ticket packages
 */
	SELECT i.image, i.id, i.name, tp.quantity
		FROM myTicket t
			JOIN vn.ticketPackaging tp ON tp.ticketFk = t.id
			JOIN vn.package p ON p.id = tp.packagingFk
			JOIN vn.item i ON i.id = p.itemFk
		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 `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 shipped 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;
END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_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.
 *
 * @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 employeeFk INTO vEmployee FROM orderConfig;
	END IF;

	-- Crea los tickets del pedido

	START TRANSACTION;

	OPEN cDates;

	lDates:
	LOOP
		SET vTicket = NULL;
		SET vDone = FALSE;
		FETCH cDates INTO vShipment, vWarehouse;
		
		IF vDone THEN
			LEAVE lDates;
		END IF;

		-- Busca un ticket existente que coincida con los parametros 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 `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 `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 `__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 */ ;

--
-- Current Database: `bs`
--

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

USE `bs`;

--
-- 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 */ ;

--
-- 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 '2016-01-01';
DECLARE vDateEnd DATE DEFAULT '2016-11-30';
DECLARE vDate DATE;

SET vDate = vDateStart;

DELETE FROM bs.ventasComponentes;

WHILE vDate <= vDateEnd DO

	INSERT INTO bs.ventasComponentes
		SELECT vDate as Fecha, mc.Id_Componente, cast(sum(m.Cantidad * mc.Valor) AS DECIMAL(10,2)) as Importe
			FROM vn2008.Movimientos_componentes mc
				JOIN vn2008.Movimientos m ON m.Id_Movimiento = mc.Id_Movimiento
				JOIN bs.ventas v ON v.Id_Movimiento = mc.Id_Movimiento
			WHERE v.fecha = vDate
				AND empresa_id IN (442,567)
			GROUP BY mc.Id_Componente;

	SET vDate = TIMESTAMPADD(DAY,1,vDate);

	IF DAY(vDate) MOD 28 = 0 THEN 
    
		SELECT vDate;
        
	END IF;

END WHILE;

	SELECT vDate;


END ;;
DELIMITER ;
/*!50003 SET sql_mode              = @saved_sql_mode */ ;
/*!50003 SET character_set_client  = @saved_cs_client */ ;
/*!50003 SET character_set_results = @saved_cs_results */ ;
/*!50003 SET collation_connection  = @saved_col_connection */ ;
/*!50003 DROP PROCEDURE IF EXISTS `bancos_evolution_add` */;
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 */ ;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2018-01-23 13:26:46
